<template>
	<ContentWrap class="container">
		<!-- 搜索 -->
		<div class="search">
			<el-tabs v-model="queryParams.status" @tab-click="handleTabClick" class="parent-tabs" v-if="!mobile">
				<el-tab-pane
v-for="item in tabsData" :key="item.type" :label="item.name + '(' + item.count + ')'"
					:name="item.type" />
			</el-tabs>
			<div style="text-align: right;" class="search-input">
				<el-input v-model="queryParams['userNickname']" 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">
			<el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
				<el-form-item label="订单状态" prop="status">
					<el-select v-model="queryParams.status" clearable placeholder="全部">
						<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)" :key="dict.value"
							:label="dict.label" :value="dict.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="支付方式" prop="payChannelCode">
					<el-select v-model="queryParams.payChannelCode" clearable placeholder="全部">
						<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.PAY_CHANNEL_CODE)" :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')]" end-placeholder="自定义时间"
						start-placeholder="自定义时间" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" style="width: auto;" />
				</el-form-item>
				<el-form-item label="订单来源" prop="terminal">
					<el-select v-model="queryParams.terminal" clearable placeholder="全部">
						<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)" :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" clearable placeholder="全部">
						<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_TYPE)" :key="dict.value" :label="dict.label"
							:value="dict.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="配送方式" prop="deliveryType">
					<el-select v-model="queryParams.deliveryType" clearable placeholder="全部">
						<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)" :key="dict.value"
							:label="dict.label" :value="dict.value" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="queryParams.deliveryType === DeliveryTypeEnum.EXPRESS.type" label="快递公司" prop="logisticsId">
					<el-select v-model="queryParams.logisticsId" clearable placeholder="全部">
						<el-option v-for="item in deliveryExpressList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="queryParams.deliveryType === DeliveryTypeEnum.PICK_UP.type" label="自提门店" prop="pickUpStoreId">
					<el-select v-model="queryParams.pickUpStoreId" clearable multiple placeholder="全部">
						<el-option v-for="item in pickUpStoreList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<!-- <el-form-item v-if="queryParams.deliveryType === DeliveryTypeEnum.PICK_UP.type" label="核销码"
				prop="pickUpVerifyCode">
				<el-input v-model="queryParams.pickUpVerifyCode"  clearable placeholder="请输入自提核销码"
					@keyup.enter="handleQuery" />
			</el-form-item> -->
				<el-form-item label="聚合搜索">
					<el-input
v-show="true" v-model="queryParams[queryType.queryParam]"
						:type="queryType.queryParam === 'userId' ? 'number' : 'text'" clearable placeholder="请输入">

						<template #prepend>
							<el-select
v-model="queryType.queryParam" class="!w-110px" clearable placeholder="全部"
								@change="inputChangeSelect">
								<el-option v-for="dict in dynamicSearchList" :key="dict.value" :label="dict.label" :value="dict.value" />
							</el-select>
						</template>
					</el-input>
				</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>
		<el-row>
			<el-col
v-for="(o, index) in list" class="card" :key="index" :span="7" :xl="7" :lg="7" :md="24" :sm="24" :xs="24"
				@mouseover="handleMouseOver(index)" @mouseout="handleMouseOut(index)">
				<el-card @click="openDetail('view', o, o.no)">
					<div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 5px;">
						<p
style="width: 95%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;font-size: 16px;color:#000"
							title=""><span v-for="(item, index) in o.items" :key="item.id">{{ item.spuName }}<span
									v-if="index < o.items.length - 1 && o.items.length > 1">+</span>
							</span>

						</p>
						<div class="setting" @click.stop="" v-hasPermi="['trade:order:update']">
							<el-dropdown v-hasPermi="['trade:order:update']" @command="(command) => handleCommand(command, row)">
								<span>
									<el-icon size="20" color="rgb(220 223 231)" v-show="o.showSetting">
										<Operation />
									</el-icon>

								</span>
								
								<template #dropdown>
									<el-dropdown-menu @mouseover="handleMouseOver(index)" @mouseout="handleMouseOut(index)">
										<el-dropdown-item
@click="handleDelivery(o.id, o.spuType)"
											v-if="o.deliveryType === DeliveryTypeEnum.EXPRESS.type  && o.status === TradeOrderStatusEnum.UNDELIVERED.status  || o.deliveryType === DeliveryTypeEnum.VIRTUAL_PRODUCT.type && o.status === TradeOrderStatusEnum.UNDELIVERED.status"> 发货</el-dropdown-item>
										<el-dropdown-item @click="handleRemark(o.id, o.remark)">备注</el-dropdown-item>
										<el-dropdown-item
@click="handleInvoice"
											v-if="o.status === TradeOrderStatusEnum.COMPLETED.status">开发票</el-dropdown-item>
										<el-dropdown-item
											v-if="o.deliveryType === DeliveryTypeEnum.EXPRESS.type && o.status === TradeOrderStatusEnum.UNDELIVERED.status"
											@click="updateAddress(o.id, o.receiverAreaName, o.receiverMobile, o.receiverAreaId, o.receiverDetailAddress)">修改地址</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>
					<div style="display:flex;align-items: center;">
						<div
							style="width: 206px; height: 116px; 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.items && o?.items[0]?.picUrl"
								style="width: 100%; height: 100%; object-fit: cover; object-position: center;" />
						</div>
						<div style='line-height: 25px;'>
					
							<p>¥{{ fenToYuan(o.payPrice) }}</p>
							<p>{{ o.no }}</p>
							<p>{{ getDictObj(DICT_TYPE.TRADE_ORDER_STATUS, o.status)?.label }}</p>
							<p>{{ o?.user?.nickname }}</p>
							<p><span class="year">{{ timestampToY(o.createTime) }}</span>{{ timestampToMDHM(o.createTime) }}</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" />
	</ContentWrap>

	<!-- 各种操作的弹窗 -->
	<OrderDeliveryForm ref="deliveryFormRef" @success="getList" />
	<OrderUpdateRemarkForm ref="updateRemarkForm" @success="getList" />
	<OrderUpdateAddressForm ref="updateAddressFormRef" @success="getList" />
	<OrderIndex ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import OrderDeliveryForm from '@/views/mall/trade/order/form/OrderDeliveryForm.vue'
import OrderUpdateRemarkForm from '@/views/mall/trade/order/form/OrderUpdateRemarkForm.vue'
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getDictObj } from '@/utils/dict'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { Setting, Search, Operation } from '@element-plus/icons-vue'
import { OrderTableColumn } from './components'
import { formatDate } from '@/utils/formatTime'
import { fenToYuan } from '@/utils'
import { useRoute } from 'vue-router';
const route = useRoute();
import OrderIndex from "./components/OrderIndex.vue"
import OrderUpdateAddressForm from '@/views/mall/trade/order/form/OrderUpdateAddressForm.vue'
// 从路由中引入store中的app仓库
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
//时间戳转换为yyyy/mm/dd
function timestampToMDHM(timestamp) {
	var date = new Date(timestamp);
	var month = ("0" + (date.getMonth() + 1)).slice(-2); // 补零操作
	var day = ("0" + date.getDate()).slice(-2);
	var hour = ("0" + date.getHours()).slice(-2);
	var min = ("0" + date.getMinutes()).slice(-2);
	return month + "/" + day + " " + hour + ":" + min;
}
function timestampToY(timestamp) {
	var date = new Date(timestamp);
	var year = date.getFullYear();
	return year + "/";
}
const searchMoreShow = ref(false)
// 鼠标移入显示变动图标
function handleMouseOver(index) {
	list.value[index].showSetting = true;
}
// 鼠标移出不显示图标
function handleMouseOut(index) {
	list.value[index].showSetting = false;
}
// 打开更多搜索条件
const showSearchMore = () => {
	searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
	searchMoreShow.value = false
}
// 从商户选项卡中传过来的id 如果有的话即证明是从商户中传过来的
const props = defineProps({
	merchantId: {
		type: Number,
		default: 0
	},
	isDetail: {
		type: Boolean,
		default: false
	},
	openType: {
		type: String,
		default: ''
	}
});
const formRef = ref()
const openDetail = (type: string, row: {}, no: string) => {
	const id = row.id
	const spuType = row.spuType
	if (mobile.value) {
		if (props.openType == 'tobedone' || route.query.openType == 'tobedone' || row.status == TradeOrderStatusEnum.UNDELIVERED.status) {
			push({ name: 'OrderMobileDeliveryForm', params: { id, spuType } })
		} else {
			push({ name: 'TradeOrderMobileDetail', params: { id  } })
		}


	} else {
		formRef.value.open(type, row, no)
	}

}

defineOptions({ name: 'TradeOrder' })
const { currentRoute, push } = useRouter() // 路由跳转
const loading = ref(true) // 列表的加载中
const total = ref(2) // 列表的总页数
const list = ref<TradeOrderApi.OrderVO[]>([]) // 列表的数据
const queryFormRef = ref<FormInstance>() // 搜索的表单
// 表单搜索
const queryParams = ref({
	pageNo: 1, // 页数
	pageSize: 10, // 每页显示数量
	status: '', // 订单状态
	payChannelCode: undefined, // 支付方式
	createTime: undefined, // 创建时间
	terminal: undefined, // 订单来源
	type: undefined, // 订单类型
	deliveryType: undefined, // 配送方式
	logisticsId: undefined, // 快递公司
	pickUpStoreId: undefined, // 自提门店
	pickUpVerifyCode: undefined, // 自提核销码
})
const queryType = reactive({ queryParam: '' }) // 订单搜索类型 queryParam

// 订单聚合搜索 select 类型配置（动态搜索）
const dynamicSearchList = ref([
	{ value: 'no', label: '订单号' },
	{ value: 'userId', label: '用户UID' },
	{ value: 'userNickname', label: '用户昵称' },
	{ value: 'userMobile', label: '用户电话' }
])
/**
 * 聚合搜索切换查询对象时触发
 * @param val
 */
const inputChangeSelect = (val: string) => {
	dynamicSearchList.value
		.filter((item) => item.value !== val)
		?.forEach((item1) => {
			// 清除集合搜索无用属性
			if (queryParams.value.hasOwnProperty(item1.value)) {

				delete queryParams.value[item1.value]
			}
		})
}

/** 查询列表 */
const getList = async () => {
	loading.value = true
	if (props.merchantId) {
		queryParams.value.merchantId = props.merchantId
	}
	try {
		const data = await TradeOrderApi.getOrderPage(unref(queryParams))
		data.list.forEach(obj => {
			obj.showSetting = false;
		});
		list.value = data.list
		total.value = data.total
	} finally {
		loading.value = false
		searchMoreShow.value = false
		getTabsCount()
	}
}

/** 搜索按钮操作 */
const handleQuery = async () => {
	queryParams.value.pageNo = 1
	await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
	queryFormRef.value?.resetFields()
	queryParams.value = {
		pageNo: 1, // 页数
		pageSize: 10, // 每页显示数量
		status: '', // 订单状态
		payChannelCode: undefined, // 支付方式
		createTime: undefined, // 创建时间
		terminal: undefined, // 订单来源
		type: undefined, // 订单类型
		deliveryType: undefined, // 配送方式
		logisticsId: undefined, // 快递公司
		pickUpStoreId: undefined, // 自提门店
		pickUpVerifyCode: undefined // 自提核销码
	}
	handleQuery()
}

// /** 查看订单详情 */
// const openDetail = (id : number) => {
// }

/** 操作分发 */
const deliveryFormRef = ref()
const updateRemarkForm = ref()
const updateAddressFormRef = ref() // 收货地址表单 Ref
const updateAddress = (id, receiverName, receiverMobile, receiverAreaId, receiverDetailAddress) => {
	updateAddressFormRef.value.open(id, receiverName, receiverMobile, receiverAreaId, receiverDetailAddress)
}
const handleDelivery = (id, spuType) => {
	deliveryFormRef.value?.open("订单列表", id, spuType)
}
const handleRemark = (id) => {
	updateRemarkForm.value?.open(id)
}

/** 订单状态 */
import { TabsPaneContext } from 'element-plus'
// tabs 数据
const tabsData = ref([
	{
		name: '全部',
		type: '',
		count: 0
	},
	{
		name: '待支付',
		type: 0,
		count: 0
	},
	{
		name: '待发货',
		type: 10,
		count: 0
	},
	{
		name: '已发货',
		type: 20,
		count: 0
	},
	{
		name: '已完成',
		type: 30,
		count: 0
	},
	{
		name: '已取消',
		type: 40,
		count: 0
	}
])
/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
	console.log(tab.paneName)
	queryParams.value.status = tab.paneName as number
	getList()
}
/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
	const obj = ref({ ...queryParams.value })
	if (props.merchantId) {
		obj.value.merId = props.merchantId
	}
	const res = await TradeOrderApi.getOrderCount(obj.value)
	for (let i in tabsData.value) {
		for (let objName in res) {
			try {
				if (tabsData.value[i].type == objName) {
					tabsData.value[i].count = res[objName]
				}
				if (tabsData.value[i].type === '') {
					tabsData.value[i].count = res[-1]
				}
			} finally {
				continue
			}
		}
	}

}
const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 自提门店精简列表
const deliveryExpressList = ref<DeliveryExpressApi.DeliveryExpressVO[]>([]) // 物流公司
/** 初始化 **/
onMounted(async () => {
	// 从待办来的 默认看待发货的订单
	if (props.openType == 'tobedone' || route.query.openType == 'tobedone') {
		queryParams.value.status = 10;

		await getList()
	} else {
		await getList()
	}

	await getTabsCount()
	pickUpStoreList.value = await PickUpStoreApi.getListAllSimple()
	deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()

})

</script>
<style src="@/styles/SearchIndex.css"  lang="scss" scoped></style>
