<template>
	<!-- 搜索 -->
	<div class="search">
		<el-tabs v-model="queryParams.status" class="parent-tabs" @tab-click="tabClick" v-if="!mobile">
			<el-tab-pane
v-for="item in statusTabs" :key="item.label" :label="item.label + '(' + item.count + ')'"
				:name="item.value" />
		</el-tabs>
		
		<div style="text-align: right;" class="search-input">
			<el-input v-model="queryParams.orderNo" placeholder="订单编号" @keyup.enter="handleQuery">
				<template #suffix>
					<Icon class="mr-5px" icon="ep:search" @click="handleQuery" style="cursor: pointer;" />
				</template>
				<template #append>
					<el-button :icon="Operation" @click="showSearchMore" />
				</template>
			</el-input>
		</div>
		
	</div>
	<div class="searchMore" v-show="searchMoreShow" :style="{ width: (mobile ? '83.7%' : '96%') }">
		<el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
			<el-form-item label="商品名称" prop="spuName">
				<el-input
v-model="queryParams.spuName" class="!w-240px" clearable placeholder="请输入商品 SPU 名称"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="退款编号" prop="no">
				<el-input
v-model="queryParams.no" class="!w-240px" clearable placeholder="请输入退款编号"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="订单编号" prop="orderNo">
				<el-input
v-model="queryParams.orderNo" class="!w-240px" clearable placeholder="请输入订单编号"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="售后状态" prop="status">
				<el-select v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择售后状态">
					<el-option label="全部" value="0" />
					<el-option
v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="售后方式" prop="way">
				<el-select v-model="queryParams.way" class="!w-240px" clearable placeholder="请选择售后方式">
					<el-option
v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_WAY)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="售后类型" prop="type">
				<el-select v-model="queryParams.type" class="!w-240px" clearable placeholder="请选择售后类型">
					<el-option
v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_TYPE)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="创建时间" prop="createTime">
				<el-date-picker
v-model="queryParams.createTime"
					:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" end-placeholder="自定义时间"
					start-placeholder="自定义时间" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
			</el-form-item>
			<el-row>
				<el-col>
					<el-form-item>
						<el-button @click="hideSearchMore">
							收起
						</el-button>
						<el-button @click="resetQuery">
							<!-- <Icon class="mr-5px" icon="ep:refresh" /> -->
							重置
						</el-button>
						<el-button @click="handleQuery" plain type="primary">
							<Icon class="mr-5px" icon="ep:search" />
							搜索
						</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
	<div v-if="mobile" style="width: 100%;">
			<van-tabs v-model:active="queryParams.status" class="parent-tabs" @click-tab="tabClick" >
        <van-tab v-for="item in statusTabs" :key="item.label" :title="item.label + '(' + item.count + ')'" :name="item.value" />
    </van-tabs>
		</div>
	<el-row>
		<el-col v-for="(o, index) in list" class="card" :key="index" :span="7" :xl="7" :lg="7" :md="7" :sm="24" :xs="24">
			<el-card @click="openTabs('view', o)">
				<div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 5px;">
					<p
style="width: 100%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;font-size: 16px;color:#000"
						:title="o.spuName">{{ o.spuName }}
					</p>
					<div v-if="!mobile" class="setting" @click.stop="openTabs('update', o)" v-hasPermi="['system:user:update']">
						<el-icon size="20" color="rgb(220 223 231)">
							<Setting />
						</el-icon>
					</div>
				</div>
				<div style="display:flex;">
					<div
						style="width: 216px; height: 122px; margin-right:10px; border:1px solid rgb(220, 223, 231); border-radius: 5px; display: flex; align-items: center; justify-content: center; overflow: hidden;">
						<img :src="o?.picUrl" style="width: 100%; height: 100%; object-fit: cover; object-position: center;" />
					</div>
					<!-- {{ o }} -->
					<div style='line-height: 25px;'>
						<p>￥{{ fenToYuan(o.refundPrice) }}</p>
						<p>{{ o.orderNo }}</p>
						<p>{{ o?.user?.nickname }}</p>
						<p>{{ getDictLabel(DICT_TYPE.TRADE_AFTER_SALE_WAY, o.way) }}</p>
						<p>{{ formatDate(o.createTime, 'YYYY-MM-DD HH:mm') }}</p>
					</div>
				</div>
			</el-card>
		</el-col>
	</el-row>
	<div v-if="list.length == 0">
		<p style="text-align: center;margin-top: 100px;">暂无售后退款</p>
	</div>
	<!-- 分页 -->
	<Pagination
v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
		@pagination="getList" />

	<AfterSaleTabs ref="AfterSaleTabsRef" @success="getList" />

</template>
<script lang="ts" setup>
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import { DICT_TYPE, getDictOptions, getDictLabel } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import { TabsPaneContext } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { fenToYuan } from '@/utils'
import { useRoute } from 'vue-router';
const route = useRoute();
/*********************** 中星查询列表开始 **********************/

import { Setting, Search, Operation } from '@element-plus/icons-vue'
// 从路由中引入store中的app仓库
import { useAppStore } from '@/store/modules/app'
import { useRouter } from 'vue-router'
import AfterSaleTabs from './AfterSaleTabs.vue'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
const searchMoreShow = ref(false)
// 打开更多搜索条件
const showSearchMore = () => {
	searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
	searchMoreShow.value = false
}
const AfterSaleTabsRef = ref()

const openTabs = (type: string, obj?: object) => {
	if (mobile.value) {
		// MemberUserMobileTab
		if (route.query.openType == 'tobedone' || obj.status == 10 || obj.status ==30|| obj.status == 40) {
			push({ name: 'AfterSaleMobileTab', query: { 'type': route.query.openType, 'obj': JSON.stringify(obj) } })
		}else{
			push({ name: 'AfterSaleMobileTab', query: { 'type': type, 'obj': JSON.stringify(obj) } })
		}
	} else {
		AfterSaleTabsRef.value.open(type, obj)
	}
}
/************************ 中星查询列表结束 ***************************/


defineOptions({ name: 'TradeAfterSale' })

const { push } = useRouter() // 路由跳转

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<AfterSaleApi.TradeAfterSaleVO[]>([]) // 列表的数据
const statusTabs = ref([])
const queryFormRef = ref() // 搜索的表单
// 查询参数
const queryParams = reactive({
	pageNo: 1,
	pageSize: 10,
	no: null,
	status: 10,
	orderNo: null,
	spuName: null,
	createTime: [],
	way: null,
	type: null
})
/** 查询列表 */
const getList = async () => {
	loading.value = true
	try {
		const data = cloneDeep(queryParams)
		// 处理掉全部的状态，不传就是全部
		if (data.status === '0') {
			delete data.status
		}
		// 执行查询
		const res = await AfterSaleApi.getAfterSalePage(data)
		list.value = res.list
		total.value = res.total
	} finally {
		loading.value = false
		getTabsCount()
	}
}
/** 搜索按钮操作 */
const handleQuery = async () => {
	queryParams.pageNo = 1
	await getList()
	hideSearchMore()
}
/** 重置按钮操作 */
const resetQuery = () => {
	queryFormRef.value?.resetFields()
	hideSearchMore()
	handleQuery()
}
/** tab 切换 */
const tabClick = async (tab: TabsPaneContext) => {
	queryParams.status = tab.paneName as any || tab.name;
	await getList()
}
/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
	const obj = ref({ ...queryParams })
	const res = await AfterSaleApi.getOrderCount(obj.value)
	let total = ref(0)
	for (let i in statusTabs.value) {
		// 累加全部的
		total.value += res[statusTabs.value[i].value] || 0
		for (let objName in res) {

			try {
				if (statusTabs.value[i].value == objName) {
					statusTabs.value[i].count = res[objName]
				}
				if (statusTabs.value[i].value == '') {
					statusTabs.value[i].count = total.value
				}
			} finally {
				continue
			}
		}
	}
}
/** 处理退款 */
const openAfterSaleDetail = (id: number) => {
	push({ name: 'TradeAfterSaleDetail', params: { id } })
}

/** 查看订单详情 */
const openOrderDetail = (id: number) => {
	push({ name: 'TradeOrderDetail', params: { orderId: id } })
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
	createImageViewer({
		urlList: [imgUrl]
	})
}

onMounted(async () => {
	await getList()
	// 设置 statuses 过滤
	for (const dict of getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)) {
		// console.log(dict)
		statusTabs.value.push({
			label: dict.label,
			value: dict.value
		})
	}
	statusTabs.value.push({
		label: '全部',
		value: ''
	})
})
</script>
<style src="@/styles/SearchIndex.css"  lang="scss" scoped></style>
<style lang="scss" scoped>
.setting {
	display: none !important;
}

.card:hover {
	.setting {
		display: block !important;

		.el-icon {
			margin-top: 5px;
		}
	}
}
.parent-tabs ::v-deep .van-tabs__nav--line.van-tabs__nav--shrink,
.parent-tabs ::v-deep .van-tabs__nav--line.van-tabs__nav--complete {
  padding-left:0;
  padding-right:0;
}
</style>