<template>
	<!-- 基本信息的表单 -->
	<div>
		<a-form :model="formData" name="basic" layout="horizontal" label-wrap>
			<a-form-item label="申请人" name="applicant">
				<a-input v-model:value="formData.applicant" style="width: 40%" />
			</a-form-item>

			<a-form-item label="申请类型" name="applyType">
				<a-radio-group v-model:value="formData.applyType" button-style="solid" style="width: 40%">
					<a-radio-button v-if="applyType === 'PURCHASE_RECEIPT'" value="PURCHASE_RECEIPT">采购入库</a-radio-button>
					<a-radio-button v-if="applyType === 'PURCHASE_RECEIPT'" value="RETURN_RECEIPT">归还入库</a-radio-button>
					<a-radio-button v-if="applyType === 'LOAN_OUT'" value="LOAN_OUT">出库外借</a-radio-button>
					<a-radio-button v-if="applyType === 'LOAN_OUT'" value="SCRAP_OUT">报废出库</a-radio-button>
				</a-radio-group>
			</a-form-item>
			<a-form-item v-if="formData.applyType === 'SCRAP_OUT'" label="审核人" name="reviewer">
				<a-select v-model:value="formData.reviewer" style="width: 40%" :options="personList"></a-select>
			</a-form-item>
			<a-form-item label="申请日期" name="applyDate" style="width: 40%">
				<a-date-picker v-model:value="formData.applyDate" />
			</a-form-item>
			<a-form-item label="选择物料" name="selected">
				<div style="display: flex; justify-content: space-between">
					<a-tree-select
						v-model:value="typeVal"
						show-search
						style="width: 49%"
						:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
						placeholder="请选择物料类型"
						allow-clear
						:tree-data="types"
						tree-node-filter-prop="label"
					/>
					<a-select
						v-model:value="formData.slectedList"
						mode="multiple"
						bordered
						placeholder="请选择物料"
						style="width: 49%"
						show-search
						:options="options"
						:filter-option="filterOption"
						@deselect="removeEvent($event)"
						@select="insertEvent($event)"
					></a-select>
				</div>
			</a-form-item>
		</a-form>
	</div>

	<!-- vxe-table -->
	<div>
		<vxe-table
			ref="tableRef"
			v-model:data="tableData"
			border
			show-overflow
			max-height="500"
			size="medium"
			empty-text="请先选择物料"
			:edit-config="{ trigger: 'click', mode: 'cell', autoFocus: true }"
		>
			<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="assignRule" title="是否赋码">
				<template #default="{ row }">
					{{ row.assignRule ? '是' : '否' }}
				</template>
			</vxe-column>
			<vxe-column
				field="quantity"
				title="申请数量(点击修改)"
				:edit-render="{ name: 'input', autoSelect: true }"
				keyboard-config="{edit: true, del: true}"
				cell-type="number"
			>
				<template #edit="{ row }">
					<vxe-number-input v-model="row.quantity" type="integer"></vxe-number-input>
				</template>
			</vxe-column>

			<vxe-column field="oprator" title="操作">
				<template #default="{ row }">
					<vxe-button mode="text" status="error" @click="removeRow(row)">删除</vxe-button>
				</template>
			</vxe-column>
		</vxe-table>
	</div>
</template>

<script setup lang="ts">
	import { VxeTableInstance } from 'vxe-table'
	import api from '@/api'
	import dayjs, { Dayjs } from 'dayjs'
	import { LabeledValue, DefaultOptionType } from 'ant-design-vue/es/select'
	import { SelectHandler } from 'ant-design-vue/es/vc-select/Select'
	import { TreeDataNode } from 'ant-design-vue/es/vc-tree-select/interface'

	// 和外层界面的数据交互
	const props = defineProps(
		{
			applyType: {
				type: String,
				default: '',
			},
		}, // 申请类型 applyType页面传值的使用1和2，1: 采购入库 和 归还入库 2: 出库外借
	)
	const getTableData = () => {
		const $table = tableRef.value
		return $table?.getTableData().fullData
	}
	const getApplyForm = () => {
		return {
			type: formData.value.applyType,
			applicant: formData.value.applicant,
			applyDate: formData.value.applyDate.format('YYYY-MM-DD HH:mm:ss'),
			isConfirm: true,
			result: '',
			reviewer: formData.value.reviewer,
		}
	}
	defineExpose({ getTableData, getApplyForm })

	interface FormData {
		applicant: string // 申请人
		applyDate: Dayjs // 申请日期
		applyType: string // 申请类型
		slectedList: number[] // 入库物料
		reviewer: string // 审核人
	}
	const formData = ref<FormData>({
		applicant: '',
		applyDate: dayjs(),
		applyType: props.applyType,
		slectedList: [],
		reviewer: '',
	})

	// 审核人
	const personList = ref<Array<{ value: string | undefined; label: string | undefined }>>([])
	api.aclApi.user.all((data) => {
		personList.value = data.map((item) => {
			return {
				value: item?.name,
				label: item?.fullName,
			}
		})
	})

	// 物料类型树
	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,
		}))
	}

	// vxe-table相关的设置
	export interface RowVO {
		id: number
		name: string
		code: string
		spec: string
		type: string
		typeName: string
		quantity: number
		disabled: boolean
		checked: boolean
		price: number
		assignRule: boolean
	}
	const tableRef = ref<VxeTableInstance<RowVO>>()
	// vxe-table 数据结果
	const tableData = ref<Array<RowVO>>([])

	// 物料选择器
	const typeVal = ref('')
	const options = ref<{ label: string; value: number }[]>([])
	const materialList = ref<material.Material[]>([])
	const getMaterialList = async () => {
		await api.materialApi.material.all({ type: typeVal.value }, (data) => {
			materialList.value = data
		})
		options.value = materialList.value.map((item) => {
			return { label: item.name ? item.name : '未知', value: item.id ? item.id : -1 }
		})
	}
	watch(
		typeVal,
		(newVal) => {
			if (newVal !== '') {
				getMaterialList()
			}
		},
		{ immediate: true, deep: true },
	)

	// 选中时在末尾新增一行
	// value: number, option: { label: string, value: number }
	type Insert = SelectHandler<LabeledValue, DefaultOptionType> | undefined
	const insertEvent = (value: Insert) => {
		// 根据value找到对应的物料信息
		const m = materialList.value.find((item) => item.id === value)
		if (m) {
			const row: RowVO = {
				id: m.id ? m.id : -1,
				name: m.name ? m.name : '',
				code: m.code ? m.code : '',
				spec: m.spec ? m.spec : '',
				typeName: m.typeName ? m.typeName : '',
				type: m.type ? m.type : '',
				price: m.price ? m.price : 0,
				quantity: 1,
				assignRule: m.assignRule ? m.assignRule : false,
				disabled: false,
				checked: false,
			}
			const $table = tableRef.value
			if ($table) {
				$table.insertAt(row, -1)
			}
		}
	}
	// 过滤选项
	const filterOption = (input: string, option: { label: string; value: number }) => {
		return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}

	// 取消选中时，删除table中的行
	const removeEvent = (value: Insert) => {
		const $table = tableRef.value
		// 根据value找到对应的行
		if ($table) {
			$table.getTableData().fullData.forEach((item) => {
				if (item.id === value) {
					$table.remove(item)
				}
			})
		}
	}

	// 手动删除table中的行
	const removeRow = async (row: RowVO) => {
		//打印tableData数组
		const $table = tableRef.value
		if ($table) {
			// 根据row.id找到对应选中列表中的数据
			formData.value.slectedList.forEach((item, index) => {
				if (item.toString() === row.id.toString()) {
					formData.value.slectedList.splice(index, 1)
				}
			})

			$table.remove(row)
		}
	}
</script>
