<template>
	<a-form name="basic" layout="horizontal" label-wrap>
		<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="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>

	<!-- 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="stock" title="库存数量" />

			<vxe-column
				field="manualStock"
				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.manualStock" type="integer"></vxe-number-input>
				</template>
			</vxe-column>
			<vxe-column
				field="msg"
				title="异常原因"
				:edit-render="{ name: 'input', autoSelect: true }"
				keyboard-config="{edit: true, del: true}"
				cell-type="string"
			>
				<template #edit="{ row }">
					<vxe-input v-model="row.msg" placeholder="请输入异常原因" type="text"></vxe-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 lang="ts" setup>
	import api from '@/api'
	import { TreeDataNode } from 'ant-design-vue/es/vc-tree-select/interface'
	import dayjs, { Dayjs } from 'dayjs'
	import { VxeTableInstance } from 'vxe-table'
	import { LabeledValue, DefaultOptionType } from 'ant-design-vue/es/select'
	import { SelectHandler } from 'ant-design-vue/es/vc-select/Select'

	//组件交互

	const props = defineProps({
		applyId: {
			type: Number,
			required: false,
			default: 0,
		},
	})
	const getTableData = (): Array<material.ManualStockDetail> => {
		const $table = tableRef.value
		if (!$table) {
			return []
		}
		return $table?.getTableData().fullData.map((item) => {
			// 只需要保存哪一个物料id,库存数量，手动核实数量
			return {
				materialId: item.id,
				stock: item.stock,
				manualStock: item.manualStock,
				msg: item.msg,
				applyId: props.applyId,
			}
		})
	}
	defineExpose({ getTableData })

	const typeVal = ref('')
	const slectedList = ref<number[]>([])

	// 物料选择器
	const options = ref<{ label: string; value: number }[]>([])
	const materialList = ref<material.Material[]>([])
	const getMaterialList = async () => {
		await api.materialApi.material.all({ type: typeVal.value, assignRule: false }, (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 },
	)
	// 物料类型树
	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 filterOption = (input: string, option: { label: string; value: number }) => {
		return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}

	// vxe-table相关的设置
	export interface RowVO {
		id: number
		name: string
		code: string
		spec: string
		type: string
		typeName: string
		stock: number
		manualStock: number
		disabled: boolean
		checked: boolean
		price: number
		assignRule: boolean
		msg: string
	}
	// vxe引用
	const tableRef = ref<VxeTableInstance<RowVO>>()

	// vxe-table 数据结果
	const tableData = ref<Array<RowVO>>([])

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

	// 手动删除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)
		}
	}
	// 取消选中时，删除table中的行
	type Insert = SelectHandler<LabeledValue, DefaultOptionType> | undefined
	const removeEvent = (value: Insert) => {
		const $table = tableRef.value
		// 根据value找到对应的行
		if ($table) {
			$table.getTableData().fullData.forEach((item) => {
				if (item.id === value) {
					$table.remove(item)
				}
			})
		}
	}
	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,
				stock: m.stock ? m.stock : 0,
				manualStock: 0,
				assignRule: m.assignRule ? m.assignRule : false,
				disabled: false,
				checked: false,
				msg: '',
			}
			const $table = tableRef.value
			if ($table) {
				$table.insertAt(row, -1)
			}
		}
	}
</script>
