<template>
	<div>
		<vxe-table
			ref="tableRef"
			border
			show-overflow
			max-height="500"
			size="medium"
			:edit-config="{ trigger: 'manual', mode: 'cell' }"
			:data="tableData"
		>
			<vxe-column type="seq" width="70" />
			<vxe-column field="id" title="物料id" :visible="false" />
			<vxe-column field="name" title="物料名称" />
			<vxe-column field="assignRule" title="是否扫码">
				<template #default="{ row }">
					{{ row.assignRule ? '是' : '否' }}
				</template>
			</vxe-column>
			<vxe-column field="applyNum" title="申请数量" :edit-render="{ name: 'VxeInput', props: { type: 'integer' } }" />
			<vxe-column field="scanNum" title="扫码数量">
				<template #default="{ row }">
					{{ row.assignRule ? row.scanNum : '~' }}
				</template>
			</vxe-column>
			<vxe-column field="remark" title="备注" :edit-render="{ name: 'VxeInput' }" />

			<vxe-column title="操作">
				<template #default="{ row }">
					<template v-if="hasEditStatus(row)">
						<vxe-button @click="saveRowEvent(row)">保存</vxe-button>
						<vxe-button @click="cancelRowEvent()">取消</vxe-button>
					</template>
					<template v-else>
						<vxe-button @click="editRowEvent(row)">编辑</vxe-button>
					</template>
				</template>
			</vxe-column>
		</vxe-table>
	</div>
</template>

<script lang="ts" setup>
	import { ref } from 'vue'
	import { VxeUI, VxeTableInstance } from 'vxe-table'

	// 和父组件的数据交互
	defineProps({
		tableData: {
			type: Array as PropType<Array<object>>,
			default: () => [],
		},
	})
	const getTableData = () => {
		const $table = tableRef.value
		if ($table) {
			return $table.getTableData().fullData.map((row) => {
				return {
					materialId: row.id,
					assignRule: row.assignRule,
					quantity: row.applyNum,
					confirmQuantity: row.scanNum,
					exceptionRemark: row.remark,
				}
			})
		}
		return []
	}

	defineExpose({ getTableData })

	interface RowVO {
		id: number
		name: string
		assignRule: string
		applyNum: number
		scanNum: number
		remark: string
	}

	const tableRef = ref<VxeTableInstance<RowVO>>()

	const loading = ref(false)

	const hasEditStatus = (row: RowVO) => {
		const $table = tableRef.value
		if ($table) {
			return $table.isEditByRow(row)
		}
	}

	const editRowEvent = (row: RowVO) => {
		const $table = tableRef.value
		if ($table) {
			$table.setEditRow(row)
		}
	}

	const saveRowEvent = (row: RowVO) => {
		const $table = tableRef.value
		if ($table) {
			$table.clearEdit().then(() => {
				loading.value = true
				setTimeout(() => {
					loading.value = false
					VxeUI.modal.message({ content: `保存成功！name=${row.name}`, status: 'success' })
				}, 300)
			})
		}
	}

	const cancelRowEvent = () => {
		const $table = tableRef.value
		if ($table) {
			$table.clearEdit()
		}
	}
</script>
