<template>
	<page-container>
		<!-- 页面操作栏 -->
		<template #ops>
			<a-row>
				<a-col :span="6" style="width: 280px">
					<a-date-picker
						v-model:value="startDate"
						:format="'YYYY-MM-DD HH:mm:ss'"
						placeholder="开始日期大于"
						style="width: 100%"
					/>
				</a-col>
				<a-col :span="6" style="width: 180px">
					<a-select
						v-model:value="status"
						placeholder="盘点状态"
						:max-tag-count="1"
						mode="multiple"
						style="width: 100%"
					>
						<a-select-option value="WAIT_SCAN">待扫码</a-select-option>
						<a-select-option value="WAIT_SUBMIT">待提交</a-select-option>
						<a-select-option value="WAIT_REVIEW">待审核</a-select-option>
						<a-select-option value="PASS">审核通过</a-select-option>
						<a-select-option value="REJECT">退回</a-select-option>
					</a-select>
				</a-col>

				<a-col :span="6" style="width: 180px">
					<a-select v-model:value="auditType" :allow-clear="true" placeholder="盘点类型" style="width: 100%">
						<a-select-option value="SCAN">扫码盘点</a-select-option>
						<a-select-option value="MANUAL">人工盘点</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="6" style="width: 180px">
					<a-input-search v-model:value="taker" :placeholder="`盘点人`" allow-clear enter-button @search="loadData()" />
				</a-col>
			</a-row>
			<a-button type="primary" @click="downloadData()">导出</a-button>
		</template>
		<!-- 页面表格内容 -->
		<div style="min-height: calc(100vh - 305px)">
			<!-- 表格行 -->
			<a-table
				:columns="columns"
				:data-source="auditPage?.records"
				bordered
				:pagination="pagination"
				:loading="loading"
				row-key="key"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'auditType'">
						{{ record.auditType === 'SCAN' ? '扫码盘点' : '人工盘点' }}
					</template>
					<template v-if="column.dataIndex === 'reviewResult'">
						<!-- 不同状态不同颜色 -->
						<template v-if="record.reviewResult === 'WAIT_SCAN'"><span style="color: #faad14">待扫码</span></template>
						<template v-if="record.reviewResult === 'WAIT_SUBMIT'"><span style="color: #1890ff">待提交</span></template>
						<template v-if="record.reviewResult === 'WAIT_REVIEW'"><span style="color: #722ed1">待审核</span></template>
						<template v-if="record.reviewResult === 'PASS'"><span style="color: #52c41a">审核通过</span></template>
						<template v-if="record.reviewResult === 'REJECT'"><span style="color: #f5222d">退回</span></template>
					</template>
					<template v-if="column.dataIndex === 'operation'">
						<a-button
							v-if="record.reviewResult === 'WAIT_REVIEW'"
							type="link"
							style="margin-left: 10px"
							@click="showResultModal(record.id, record.auditType, true)"
						>
							审核
						</a-button>
						<a-button
							type="link"
							style="margin-left: 10px"
							@click="showResultModal(record.id, record.auditType, false)"
						>
							查看
						</a-button>
					</template>
				</template>
			</a-table>
		</div>
	</page-container>

	<!-- 审核弹窗 -->
	<a-modal v-model:open="openResult" title="盘点异常数据：" width="80%" :confirm-loading="confirmLoading" @ok="submit">
		<result-form v-if="auditTypeRef === 'SCAN'" :apply-id="applyIdRef" />
		<vxe-table
			v-if="auditTypeRef === 'MANUAL'"
			v-model:data="manualData"
			border
			show-overflow
			max-height="500"
			size="medium"
		>
			<vxe-column type="seq" title="序号" width="60" />
			<vxe-column field="id" title="物料id" :visible="false" />
			<vxe-column field="name" title="物料名称" />
			<vxe-column field="code" title="编码" />
			<vxe-column field="spec" title="规格" />
			<vxe-column field="price" title="价格" />
			<vxe-column field="typeName" title="类型" />
			<vxe-column field="stock" title="库存数量" />
			<vxe-column field="manualStock" title="手动核实数量" />
			<vxe-column field="msg" title="异常原因" />
		</vxe-table>
		<a-form v-if="flag" layout="vertical" style="margin-top: 20px">
			<a-form-item label="审核意见">
				<a-textarea v-model:value="remark" placeholder="请输入审核意见" :row="3" :maxlength="1000" />
			</a-form-item>

			<a-form-item label="审核结果">
				<a-radio-group v-model:value="reviewResult" button-style="solid">
					<a-radio-button value="PASS">审核通过</a-radio-button>
					<a-radio-button value="REJECT" style="margin-left: 20px">退回重盘</a-radio-button>
				</a-radio-group>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup lang="ts">
	import api from '@/api'
	import { IPage } from '@/api/api'
	import resultForm from '../stocktaking/result-form.vue'
	import { Dayjs } from 'dayjs'
	import { http } from '@/settings/http'

	const applyIdRef = ref()
	const auditPage = ref<IPage<material.ApplyForm>>()
	const loading = ref(false)
	const confirmLoading = ref(false)
	const reviewResult = ref<'PASS' | 'REJECT'>('PASS')
	const remark = ref('')
	// 搜索条件
	const startDate = ref<Dayjs>()
	const taker = ref('')
	const status = ref<Array<'PASS' | 'REJECT' | 'WAIT_SCAN' | 'WAIT_SUBMIT' | 'WAIT_REVIEW'>>()
	const auditType = ref<'SCAN' | 'MANUAL'>()

	// 加载数据的方法
	const loadData = async (page = 1, size = 10) => {
		loading.value = true
		api.materialApi.apply.searchAuditPage(
			{
				page: page,
				size: size,
				auditType: auditType.value,
				//ISO 8601 的完整日期时间格式为：YYYY-MM-DDTHH:mm:ss，其中 T 是日期和时间之间的分隔符。
				// 对于 LocalDateTime，不需要时区信息（即不包含 Z 或者 +/-HH:mm），因为 LocalDateTime 本身没有时区概念。
				// 获取 ISO 8601 格式的字符串，但需要去掉 'Z' 和时区部分
				createDate: startDate.value?.toISOString().replace('Z', '').slice(0, -1),
				taker: taker.value,
				reviewResults: status.value,
			},
			(data) => {
				auditPage.value = data
				loading.value = false
			},
		)
	}
	//初始加载
	loadData()

	//导出数据
	const downloadData = () => {
		// 创建 URLSearchParams 对象
		const params = new URLSearchParams()

		// 动态添加参数
		if (auditType.value) {
			params.append('auditType', auditType.value)
		}
		if (startDate.value) {
			// 格式化日期并移除 'Z' 和毫秒部分
			const formattedDate = startDate.value.toISOString().replace('Z', '').slice(0, -4)
			params.append('createDate', formattedDate)
		}
		if (taker.value) {
			params.append('taker', taker.value)
		}
		if (status.value && status.value.length > 0) {
			// 为数组中的每个值单独添加参数
			status.value.forEach((value) => {
				params.append('reviewResults', value)
			})
		}

		// 构建完整的 URL
		const url = `${http.prefix}/apply/audit/download-excel?${params.toString()}`

		// 打开下载链接
		window.open(url)
	}
	//表格列
	const columns = [
		{
			title: '序号',
			dataIndex: 'key',
			customRender: ({ index }: { index: number }) => `${index + 1}`,
		},
		{
			title: '盘点类型',
			dataIndex: 'auditType',
		},
		{
			title: '申请人',
			dataIndex: 'applicant',
		},
		{
			title: '盘点人',
			dataIndex: 'taker',
		},
		{
			title: '盘点审核人',
			dataIndex: 'reviewer',
		},
		{
			title: '申请日期',
			dataIndex: 'applyDate',
		},
		{
			title: '审核意见',
			dataIndex: 'reviewRemark',
		},
		{
			title: '审核结果',
			dataIndex: 'reviewResult',
		},
		{
			title: '操作',
			dataIndex: 'operation',
		},
	]

	//分页信息
	const pagination = computed(() => {
		return {
			current: auditPage.value?.current,
			pageSize: auditPage.value?.size,
			total: auditPage.value?.total,
			onChange: (page: number, pageSize: number) => {
				loadData(page, pageSize)
			},
		}
	})

	// 定义一个标记，用于控制是查看还是审核 flag=true审核，flag=false查看
	const flag = ref(false)
	const openResult = ref<boolean>(false)
	const auditTypeRef = ref<'SCAN' | 'MANUAL'>()

	// 点击 审核或者查看 按钮
	const showResultModal = (applyId: number, auditType: 'SCAN' | 'MANUAL', select: boolean) => {
		flag.value = select
		auditTypeRef.value = auditType
		applyIdRef.value = applyId
		openResult.value = true
		if (auditType === 'MANUAL') {
			getManualData(applyId)
		}
	}

	// 查询人工盘点数据
	const manualData = ref<Array<material.ManualStockDTO>>()
	const getManualData = (applyId: number) => {
		api.materialApi.apply.getManualStock(applyId, (data) => {
			manualData.value = data
		})
	}

	//提交审核结果
	const submit = () => {
		confirmLoading.value = true
		if (!flag.value) {
			confirmLoading.value = false
			openResult.value = false
			return
		}
		api.materialApi.apply.submitReview(
			{
				applyId: applyIdRef.value,
				reviewResult: reviewResult.value,
				remark: remark.value,
			},
			() => {
				confirmLoading.value = false
				openResult.value = false
				loadData()
			},
		)
	}
</script>
