<template>
	<page-container>
		<!-- 页面操作栏 -->
		<template #ops>
			<a-row>
				<a-col :span="18">
					<a-input-search
						v-model:value="searchKey"
						:placeholder="`请输入`"
						allow-clear
						enter-button
						@search="loadData()"
					></a-input-search>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" style="margin-left: 10px" @click="formDrawer?.show()">
						<template #icon>
							<icon-font type="icon-plus" />
						</template>
						新增盘点
					</a-button>
				</a-col>
			</a-row>
		</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_SCAN' || record.reviewResult === 'REJECT'"
							type="link"
							@click="showModal(record.id, record.auditType)"
						>
							<template #icon>
								<icon-font type="icon-edit" />
							</template>
							开始盘点
						</a-button>
						<a-button
							v-if="record.reviewResult === 'WAIT_SUBMIT'"
							type="link"
							style="margin-left: 10px"
							@click="showResultModal(record.id)"
						>
							<template #icon>
								<icon-font type="icon-plus" />
							</template>
							生成结果
						</a-button>
					</template>
				</template>
			</a-table>
		</div>
	</page-container>

	<!-- 新增申请抽屉 -->
	<form-drawer
		ref="formDrawer"
		v-model="applyForm"
		:form-items="items"
		:config="formConfig"
		title="扫码盘点"
		@ok="doSave"
	/>
	<!-- 盘点作业弹窗 -->
	<a-modal
		v-model:open="open"
		title="盘点作业"
		width="100%"
		wrap-class-name="full-modal"
		:confirm-loading="confirmLoading"
		@ok="handleOk"
		@cancel="cancel"
	>
		<scan-form ref="scanFormRef" :apply-id="applyIdRef" :total-value="totalValue">
			<p>
				{{ msg }}
			</p>
		</scan-form>
	</a-modal>
	<!-- 盘点结果弹窗 -->
	<a-modal
		v-model:open="openResult"
		title="盘点异常数据："
		ok-text="提交审核"
		width="80%"
		:confirm-loading="confirmLoading"
		@ok="submitHandle"
	>
		<result-form ref="handleResultRef" :apply-id="applyIdRef"></result-form>
	</a-modal>
	<!-- 手动盘点弹窗 -->
	<a-modal v-model:open="openManual" title="手动盘点" width="80%" :confirm-loading="confirmLoading" @ok="manualHandle">
		<manual-form ref="manualFormRef" :apply-id="applyIdRef"></manual-form>
	</a-modal>
</template>

<script setup lang="ts">
	import api from '@/api'
	import { IPage } from '@/api/api'
	import FormDrawer from '@/components/form-render/form-drawer.vue'
	import { config, formItems } from './form'
	import { notification } from 'ant-design-vue'
	import dayjs from 'dayjs'
	import { useUserStore } from '@/stores/user'
	import scanForm from '../component/scan-form.vue'
	import resultForm from './result-form.vue'
	import { TreeDataNode } from 'ant-design-vue/es/vc-tree-select/interface'
	import manualForm from '../component/manual-form.vue'

	const searchKey = ref('')
	const userStore = useUserStore()
	const scanFormRef = ref() // 盘点作业弹窗组件
	const handleResultRef = ref() // 盘点结果弹窗组件
	const confirmLoading = ref(false) // 盘点作业弹窗提交按钮loading
	const manualFormRef = ref() // 手动盘点弹窗组件
	// 新增申请表单对象
	const applyForm = ref<Partial<material.AuditApplyInfo>>({
		auditType: 'SCAN',
		applicant: userStore.fullName,
		type: 'AUDIT',
		applyDate: dayjs() + '',
		confirm: false,
		reviewResult: 'WAIT_SCAN',
		types: [],
	})
	const msg = ref()
	const totalValue = ref(0) // 盘点总值

	//列表数据
	const auditPage = ref<IPage<material.ApplyForm>>()
	const loading = ref(false)

	//新增申请的下拉框选择对象
	const materialList = ref<Array<{ value: string | undefined; label: string | undefined }>>([])
	const personList = ref<Array<{ value: string | undefined; label: string | undefined }>>([])
	const required = ref(true)
	api.aclApi.user.all((data) => {
		personList.value = data.map((item) => {
			return {
				value: item?.fullName,
				label: item?.fullName,
			}
		})
	})

	// //是否必填
	// const disabledFields = computed(() => {
	// 	return applyForm.value?.auditType === 'ALL' ? ['ids'] : []
	// })

	// 监听选择类型后查询物料
	watch(
		applyForm,
		() => {
			if (applyForm.value && applyForm.value.types && applyForm.value.types.length > 0) {
				api.materialApi.material.all({ type: applyForm.value.types.join(',') }, (data) => {
					materialList.value = data.map((item) => {
						return {
							value: item?.id + '',
							label: item?.name,
						}
					})
				})
			}
		},
		{
			immediate: true,
			deep: true,
		},
	)

	// 物料类型树
	const types = ref<Array<TreeDataNode>>([])
	api.materialApi.type.trees((data) => {
		types.value = children(data)
	})
	const children = (res: Array<material.TypeTree>): Array<TreeDataNode> => {
		return res.map((areaTree) => ({
			label: areaTree.label,
			value: areaTree.value,
			children: areaTree.children ? children(areaTree.children) : [],
			key: areaTree.value,
		}))
	}

	//抽屉组件
	const formDrawer = ref<typeof FormDrawer>()
	const formConfig = computed(() => {
		return config
	})
	//表单配置
	const items = computed(() => {
		//required 参数未生效
		return formItems(materialList.value, required.value, personList.value, types.value)
	})
	// 加载数据的方法
	const loadData = async (page = 1, size = 10) => {
		loading.value = true
		api.materialApi.apply.searchAuditPage(
			{
				page: page,
				size: size,
				reviewResults: ['WAIT_SUBMIT', 'WAIT_SCAN', 'WAIT_REVIEW', 'REJECT'],
			},
			(data) => {
				auditPage.value = data
				loading.value = false
			},
		)
	}
	//初始加载
	loadData()

	//表格列
	const columns = [
		{
			title: '序号',
			dataIndex: 'key',
			customRender: ({ index }: { index: number }) => `${index + 1}`,
		},
		{
			title: '盘点类型',
			dataIndex: 'auditType',
		},
		{
			title: '申请人',
			dataIndex: 'applicant',
		},
		{
			title: '盘点人',
			dataIndex: 'taker',
		},
		{
			title: '任务状态',
			dataIndex: 'reviewResult',
		},
		{
			title: '审核意见',
			dataIndex: 'reviewRemark',
		},
		{
			title: '盘点审核人',
			dataIndex: 'reviewer',
		},

		{
			title: '创建时间',
			dataIndex: 'createdTime',
		},
		{
			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)
			},
		}
	})

	// 新增申请保存
	const doSave = (_data: material.AuditApplyInfo) => {
		api.materialApi.apply.auditApply(_data, () => {
			formDrawer.value?.close()
			notification.success({
				message: '操作成功',
				description: '盘点申请保存成功,页面将自动刷新!',
				onClose: () => {
					loadData(1)
				},
			})
		})
	}

	// 盘点作业弹窗相关
	const open = ref<boolean>(false)
	const applyIdRef = ref()
	const showModal = (applyId: number, auditType: string) => {
		if (auditType === 'SCAN') {
			showScanModal(applyId)
		} else {
			showManualModal(applyId)
		}
	}

	// 人工盘点
	const openManual = ref<boolean>(false)
	const showManualModal = (applyId: number) => {
		applyIdRef.value = applyId
		openManual.value = true
	}
	const manualHandle = () => {
		//提交数据
		if (manualFormRef.value) {
			const res: Array<material.ManualStockDetail> = manualFormRef.value.getTableData()
			api.materialApi.apply.submitManualStock(res, () => {
				openManual.value = false
				loadData(1)
			})
		}
	}

	// 扫码弹窗
	const showScanModal = (applyId: number) => {
		open.value = true
		applyIdRef.value = applyId
		let m = '需要扫码的物料: '
		//请求获取数据
		api.materialApi.apply.getWaitScanData(applyId, (data) => {
			const m = `需要扫码的物料: ${data.map((item) => item.materialName).join(', ') || '无'}`
			data.forEach((item) => (totalValue.value += item.count || 0))
			msg.value = m
		})
		msg.value = m
	}

	// 盘点作业提交数据

	//关闭弹窗 提交数据
	const handleOk = () => {
		confirmLoading.value = true
		if (scanFormRef.value) {
			const data = scanFormRef.value.getApplyData()
			api.materialApi.apply.saveScanData(applyIdRef.value, data, () => {
				open.value = false
				confirmLoading.value = false
				loadData(1)
			})
		}
	}
	// 关闭弹窗事件
	const cancel = () => {
		totalValue.value = 0
		msg.value = ''
	}

	// 盘点结果弹窗相关
	const openResult = ref<boolean>(false)
	const showResultModal = (applyId: number) => {
		window.console.log('点击传参' + applyId)
		openResult.value = true
		applyIdRef.value = applyId
	}

	// 盘点结果提交数据
	const submitHandle = () => {
		confirmLoading.value = true
		const handleData = handleResultRef.value.getTableData()
		api.materialApi.apply.updateReviewResult(applyIdRef.value, handleData, () => {
			openResult.value = false
			loadData(1)
		})
		confirmLoading.value = false
	}
</script>

<style lang="less">
	.full-modal {
		.ant-modal {
			max-width: 100%;
			top: 0;
			padding-bottom: 0;
			margin: 0;
		}

		.ant-modal-content {
			display: flex;
			flex-direction: column;
			height: calc(100vh);
		}

		.ant-modal-body {
			flex: 1;
		}
	}
</style>
