<template>
	<div>
		<el-card>
			<template #header>
				<div class="card-header">
					<span>手动设置</span>
				</div>
			</template>
			<!-- 搜索表单 -->
			<el-form :model="searchForm" :inline="true" style="margin-bottom: 20px;">
				<el-form-item label="托盘号">
					<el-input v-model="searchForm.palletNo" placeholder="请输入托盘号" clearable />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
					<el-button @click="handleReset">重置</el-button>
				</el-form-item>
			</el-form>

			<!-- 工具栏 -->
			<div class="head-container" style="margin-bottom: 20px;">
				<el-button type="primary" @click="handleAdd">
					<el-icon>
						<Plus />
					</el-icon>
					新增托盘
				</el-button>
			</div>

			<!-- 托盘列表 -->
			<el-collapse v-model="activeCollapse" accordion>
				<el-collapse-item v-for="pallet in palletList" :key="pallet.palletNo" :name="pallet.palletNo">
					<template #title>
						<div class="collapse-title">
							<span class="pallet-no">托盘号：{{ pallet.palletNo }}</span>
							<span class="goods-count">绑定物资数：{{ pallet.goodsList.length }}</span>
							<el-button type="primary" size="small" @click.stop="handleAddGoods(pallet)">
								添加物资
							</el-button>
							<el-popconfirm title="确定要删除整个托盘吗？" @confirm="handleDeletePallet(pallet)">
								<template #reference>
									<el-button type="danger" size="small" @click.stop>删除托盘</el-button>
								</template>
							</el-popconfirm>
						</div>
					</template>

					<!-- 托盘绑定的物资表格 -->
					<el-table :data="pallet.goodsList" border style="width: 100%">
						<el-table-column type="index" label="序号" width="60" align="center" />
						<el-table-column prop="goodsCode" label="品名编码" align="center" min-width="120" />
						<el-table-column prop="goodsName" label="品名名称" align="center" min-width="150" />
						<el-table-column prop="modelCode" label="号型编码" align="center" min-width="120" />
						<el-table-column prop="modelName" label="号型名称" align="center" min-width="120" />
						<el-table-column prop="skuCode" label="SKU编码" align="center" min-width="140" />
						<el-table-column prop="jldw" label="计量单位" align="center" width="100" />
						<el-table-column prop="qty" label="数量" align="center" width="100">
							<template #default="scope">
								<el-input-number v-model="scope.row.qty" :min="1" size="small"
									@change="handleQtyChange(pallet, scope.row)" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="100" align="center">
							<template #default="scope">
								<el-popconfirm title="确定要解绑该物资吗？" @confirm="handleDeleteGoods(pallet, scope.row)">
									<template #reference>
										<el-button type="danger" size="small">解绑</el-button>
									</template>
								</el-popconfirm>
							</template>
						</el-table-column>
					</el-table>
				</el-collapse-item>
			</el-collapse>

			<!-- 空状态 -->
			<el-empty v-if="palletList.length === 0" description="暂无托盘数据，请点击新增托盘" />

			<!-- 分页 -->
			<div style="margin-top: 20px; display: flex; justify-content: flex-end;">
				<el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
					:page-sizes="[5, 10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</el-card>

		<!-- 新增托盘对话框（包含物资绑定） -->
		<el-dialog v-model="dialogVisible" width="70%" title="新增托盘" @close="handleDialogClose">
			<el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
				<el-form-item label="托盘号" prop="palletNo">
					<el-input v-model="form.palletNo" placeholder="请输入托盘号" clearable style="width: 300px" />
				</el-form-item>

				<el-divider content-position="left">绑定物资</el-divider>

				<!-- 物资选择行 -->
				<div class="goods-select-row">
					<el-select v-model="currentGoodsId" placeholder="请选择物资" clearable filterable style="width: 300px"
						@change="handleSelectGoods">
						<el-option v-for="item in availableGoodsList" :key="item.id"
							:label="`${item.goodsCode} - ${item.goodsName} - ${item.modelName}`" :value="item.id" />
					</el-select>

					<el-input-number v-model="currentGoodsQty" :min="1" :max="999999" placeholder="数量"
						style="width: 150px; margin: 0 10px" />

					<el-button type="primary" @click="handleAddGoodsToForm" :disabled="!currentGoodsId || currentGoodsQty < 1">
						添加物资
					</el-button>
				</div>

				<!-- 已选物资表格 -->
				<el-table :data="form.goodsList" border style="width: 100%; margin-top: 15px">
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="goodsCode" label="品名编码" align="center" min-width="120" />
					<el-table-column prop="goodsName" label="品名名称" align="center" min-width="150" />
					<el-table-column prop="modelCode" label="号型编码" align="center" min-width="120" />
					<el-table-column prop="modelName" label="号型名称" align="center" min-width="120" />
					<el-table-column prop="skuCode" label="SKU编码" align="center" min-width="140" />
					<el-table-column prop="jldw" label="计量单位" align="center" width="100" />
					<el-table-column prop="qty" label="数量" align="center" width="120">
						<template #default="scope">
							<el-input-number v-model="scope.row.qty" :min="1" size="small" />
						</template>
					</el-table-column>
					<el-table-column label="操作" width="80" align="center">
						<template #default="scope">
							<el-button type="danger" size="small" @click="handleRemoveGoodsFromForm(scope.$index)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmitPallet" :loading="submitLoading">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 添加物资对话框（用于已有托盘添加物资） -->
		<el-dialog v-model="goodsDialogVisible" width="60%" title="添加物资" @close="handleGoodsDialogClose">
			<el-form :model="goodsForm" :rules="goodsFormRules" ref="goodsFormRef" label-width="100px">
				<el-form-item label="选择物资" prop="goodsInfo">
					<el-select v-model="goodsForm.goodsInfo" placeholder="请选择物资" clearable filterable style="width: 100%"
						@change="handleGoodsChange">
						<el-option v-for="item in goodsList" :key="item.id"
							:label="`${item.goodsCode} - ${item.goodsName} - ${item.modelName}`" :value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="数量" prop="qty">
					<el-input-number v-model="goodsForm.qty" :min="1" :max="999999" style="width: 100%" />
				</el-form-item>

				<!-- 选中物资的详细信息展示 -->
				<el-divider content-position="left">物资详细信息</el-divider>
				<el-descriptions :column="2" border>
					<el-descriptions-item label="品名编码">{{ selectedGoods.goodsCode || '-' }}</el-descriptions-item>
					<el-descriptions-item label="品名名称">{{ selectedGoods.goodsName || '-' }}</el-descriptions-item>
					<el-descriptions-item label="号型编码">{{ selectedGoods.modelCode || '-' }}</el-descriptions-item>
					<el-descriptions-item label="号型名称">{{ selectedGoods.modelName || '-' }}</el-descriptions-item>
					<el-descriptions-item label="SKU编码">{{ selectedGoods.skuCode || '-' }}</el-descriptions-item>
					<el-descriptions-item label="计量单位">{{ selectedGoods.jldw || '-' }}</el-descriptions-item>
					<el-descriptions-item label="箱规">{{ selectedGoods.boxNum || '-' }}</el-descriptions-item>
				</el-descriptions>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="goodsDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmitGoods" :loading="submitLoading">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue'
import { getAction } from '@/api/manage'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default defineComponent({
	name: 'PalletBinding',
	components: {
		Plus
	},
	setup() {
		// 搜索表单
		const searchForm = reactive({
			palletNo: ''
		})

		// 托盘列表数据（假数据）
		const palletList = ref([])

		// 展开的折叠面板
		const activeCollapse = ref('')

		// 物资列表（从接口获取）
		const goodsList = ref([])

		// 分页配置
		const pagination = reactive({
			current: 1,
			size: 10,
			total: 0
		})

		// 所有托盘数据（用于分页）
		const allPalletData = ref([])

		// 新增托盘对话框相关
		const dialogVisible = ref(false)
		const formRef = ref()
		const submitLoading = ref(false)

		const form = reactive({
			palletNo: '',
			goodsList: []
		})

		const formRules = reactive({
			palletNo: [
				{ required: true, message: '请输入托盘号', trigger: 'blur' },
				{
					validator: (rule, value, callback) => {
						const exists = allPalletData.value.some(p => p.palletNo === value)
						if (exists) {
							callback(new Error('托盘号已存在'))
						} else {
							callback()
						}
					}, trigger: 'blur'
				}
			]
		})

		// 新增托盘弹窗中的物资选择
		const currentGoodsId = ref('')
		const currentGoodsQty = ref(1)

		// 可用物资列表（排除已选的）
		const availableGoodsList = computed(() => {
			const selectedIds = form.goodsList.map(g => g.id)
			return goodsList.value.filter(g => !selectedIds.includes(g.id))
		})

		// 添加物资对话框相关（用于已有托盘添加物资）
		const goodsDialogVisible = ref(false)
		const goodsFormRef = ref()
		const currentPallet = ref(null)
		const goodsForm = reactive({
			goodsInfo: '',
			qty: 1
		})
		const goodsFormRules = reactive({
			goodsInfo: [
				{ required: true, message: '请选择物资', trigger: 'change' }
			],
			qty: [
				{ required: true, message: '请输入数量', trigger: 'blur' }
			]
		})

		// 选中的物资信息
		const selectedGoods = reactive({
			id: '',
			goodsCode: '',
			goodsName: '',
			modelCode: '',
			modelName: '',
			skuCode: '',
			jldw: '',
			boxNum: ''
		})

		// API URL配置
		const apiUrl = reactive({
			goodsList: '/goodsInfo/goodsInfo/list'
		})

		// 加载物资列表
		const loadGoodsList = () => {
			getAction(apiUrl.goodsList).then(res => {
				if (res.code !== 99200) {
					console.error('加载物资列表失败:', res.message)
					return
				}
				goodsList.value = res.data || []
			}).catch(error => {
				console.error('Load goods list error:', error)
				// 假数据
				goodsList.value = [
					{ id: '1', goodsCode: '123456', goodsName: '鞋子', modelCode: '1234560101', modelName: 'XL', skuCode: '123456789', jldw: '件', boxNum: 10 },
					{ id: '2', goodsCode: '123457', goodsName: '手套', modelCode: '1234570202', modelName: 'XXL', skuCode: '123456782', jldw: '双', boxNum: 10 },
					{ id: '3', goodsCode: '400001', goodsName: '20靴', modelCode: '4000010109', modelName: '290', skuCode: '889000004', jldw: '件', boxNum: 10 },
					{ id: '4', goodsCode: '400001', goodsName: '20靴', modelCode: '4000010309', modelName: '280', skuCode: '889000006', jldw: '件', boxNum: 10 },
					{ id: '5', goodsCode: '400002', goodsName: '运动鞋', modelCode: '4000020101', modelName: '42', skuCode: '889000007', jldw: '双', boxNum: 20 }
				]
			})
		}

		// 加载托盘数据（假数据）
		const loadPalletData = () => {
			const mockData = [
				{
					palletNo: 'PALLET001',
					goodsList: [
						{ id: '1', goodsCode: '123456', goodsName: '鞋子', modelCode: '1234560101', modelName: 'XL', skuCode: '123456789', jldw: '件', boxNum: 10, qty: 50 },
						{ id: '2', goodsCode: '123457', goodsName: '手套', modelCode: '1234570202', modelName: 'XXL', skuCode: '123456782', jldw: '双', boxNum: 10, qty: 100 }
					]
				},
				{
					palletNo: 'PALLET002',
					goodsList: [
						{ id: '3', goodsCode: '400001', goodsName: '20靴', modelCode: '4000010109', modelName: '290', skuCode: '889000004', jldw: '件', boxNum: 10, qty: 30 }
					]
				}
			]
			allPalletData.value = mockData
			updatePageData()
		}

		// 更新分页数据
		const updatePageData = () => {
			const start = (pagination.current - 1) * pagination.size
			const end = start + pagination.size
			let filteredData = [...allPalletData.value]

			if (searchForm.palletNo) {
				filteredData = filteredData.filter(p => p.palletNo.includes(searchForm.palletNo))
			}

			pagination.total = filteredData.length
			palletList.value = filteredData.slice(start, end)

			if (palletList.value.length > 0 && !activeCollapse.value) {
				activeCollapse.value = palletList.value[0].palletNo
			}
		}

		// 搜索
		const handleSearch = () => {
			pagination.current = 1
			updatePageData()
		}

		// 重置搜索
		const handleReset = () => {
			searchForm.palletNo = ''
			handleSearch()
		}

		// 分页大小改变
		const handleSizeChange = (val) => {
			pagination.size = val
			pagination.current = 1
			updatePageData()
		}

		// 页码改变
		const handleCurrentChange = (val) => {
			pagination.current = val
			updatePageData()
		}

		// 新增托盘
		const handleAdd = () => {
			dialogVisible.value = true
		}

		// 选择物资添加到表单列表
		const handleSelectGoods = (value) => {
			// 只是选中，不自动添加
		}

		// 添加物资到表单
		const handleAddGoodsToForm = () => {
			const goods = goodsList.value.find(g => g.id === currentGoodsId.value)
			if (!goods) return

			// 检查是否已存在
			if (form.goodsList.some(g => g.id === goods.id)) {
				ElMessage.warning('该物资已添加')
				return
			}

			form.goodsList.push({
				id: goods.id,
				goodsCode: goods.goodsCode,
				goodsName: goods.goodsName,
				modelCode: goods.modelCode,
				modelName: goods.modelName,
				skuCode: goods.skuCode,
				jldw: goods.jldw,
				boxNum: goods.boxNum,
				qty: currentGoodsQty.value
			})

			// 重置选择
			currentGoodsId.value = ''
			currentGoodsQty.value = 1
			ElMessage.success('物资添加成功，请继续添加或提交托盘')
		}

		// 从表单中删除物资
		const handleRemoveGoodsFromForm = (index) => {
			form.goodsList.splice(index, 1)
		}

		// 提交新增托盘
		const handleSubmitPallet = () => {
			formRef.value.validate((valid) => {
				if (!valid) return

				const newPallet = {
					palletNo: form.palletNo,
					goodsList: [...form.goodsList]
				}
				allPalletData.value.unshift(newPallet)
				updatePageData()
				ElMessage.success(`新增托盘成功，共绑定 ${form.goodsList.length} 种物资`)
				dialogVisible.value = false
				handleDialogClose()
			})
		}

		// 删除托盘
		const handleDeletePallet = (pallet) => {
			const index = allPalletData.value.findIndex(p => p.palletNo === pallet.palletNo)
			if (index !== -1) {
				allPalletData.value.splice(index, 1)
				updatePageData()
				ElMessage.success('删除托盘成功')
			}
		}

		// 添加物资（已有托盘）
		const handleAddGoods = (pallet) => {
			currentPallet.value = pallet
			goodsDialogVisible.value = true
		}

		// 物资选择变化
		const handleGoodsChange = (value) => {
			const goods = goodsList.value.find(item => item.id == value)
			if (goods) {
				Object.assign(selectedGoods, {
					id: goods.id,
					goodsCode: goods.goodsCode,
					goodsName: goods.goodsName,
					modelCode: goods.modelCode,
					modelName: goods.modelName,
					skuCode: goods.skuCode,
					jldw: goods.jldw,
					boxNum: goods.boxNum
				})
			} else {
				Object.assign(selectedGoods, {
					id: '',
					goodsCode: '',
					goodsName: '',
					modelCode: '',
					modelName: '',
					skuCode: '',
					jldw: '',
					boxNum: ''
				})
			}
		}

		// 提交添加物资（已有托盘）
		const handleSubmitGoods = () => {
			goodsFormRef.value.validate((valid) => {
				if (!valid) return

				const selected = goodsList.value.find(item => item.id == goodsForm.goodsInfo)
				if (!selected) {
					ElMessage.warning('请选择有效的物资')
					return
				}

				if (currentPallet.value.goodsList.some(g => g.id === selected.id)) {
					ElMessage.warning('该物资已绑定在当前托盘上')
					return
				}

				const newGoods = {
					id: selected.id,
					goodsCode: selected.goodsCode,
					goodsName: selected.goodsName,
					modelCode: selected.modelCode,
					modelName: selected.modelName,
					skuCode: selected.skuCode,
					jldw: selected.jldw,
					boxNum: selected.boxNum,
					qty: goodsForm.qty
				}

				currentPallet.value.goodsList.push(newGoods)
				updatePageData()
				ElMessage.success('添加物资成功')
				goodsDialogVisible.value = false
				handleGoodsDialogClose()
			})
		}

		// 删除物资
		const handleDeleteGoods = (pallet, goods) => {
			const index = pallet.goodsList.findIndex(g => g.id === goods.id)
			if (index !== -1) {
				pallet.goodsList.splice(index, 1)
				updatePageData()
				ElMessage.success('解绑成功')
			}
		}

		// 数量变更
		const handleQtyChange = (pallet, goods) => {
			console.log('数量变更:', pallet.palletNo, goods.goodsCode, goods.qty)
		}

		// 关闭新增托盘对话框
		const handleDialogClose = () => {
			form.palletNo = ''
			form.goodsList = []
			currentGoodsId.value = ''
			currentGoodsQty.value = 1
			formRef.value?.resetFields()
		}

		// 关闭添加物资对话框
		const handleGoodsDialogClose = () => {
			goodsForm.goodsInfo = ''
			goodsForm.qty = 1
			Object.assign(selectedGoods, {
				id: '',
				goodsCode: '',
				goodsName: '',
				modelCode: '',
				modelName: '',
				skuCode: '',
				jldw: '',
				boxNum: ''
			})
			goodsFormRef.value?.resetFields()
			currentPallet.value = null
		}

		// 初始化
		onMounted(() => {
			loadGoodsList()
			loadPalletData()
		})

		return {
			searchForm,
			palletList,
			goodsList,
			availableGoodsList,
			activeCollapse,
			pagination,
			dialogVisible,
			goodsDialogVisible,
			form,
			formRules,
			formRef,
			submitLoading,
			currentGoodsId,
			currentGoodsQty,
			goodsForm,
			goodsFormRules,
			goodsFormRef,
			selectedGoods,
			handleSearch,
			handleReset,
			handleSizeChange,
			handleCurrentChange,
			handleAdd,
			handleSelectGoods,
			handleAddGoodsToForm,
			handleRemoveGoodsFromForm,
			handleSubmitPallet,
			handleDeletePallet,
			handleAddGoods,
			handleGoodsChange,
			handleSubmitGoods,
			handleDeleteGoods,
			handleQtyChange,
			handleDialogClose,
			handleGoodsDialogClose
		}
	}
})
</script>

<style scoped>
.head-container {
	display: flex;
	justify-content: flex-end;
	align-items: center;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
}

.collapse-title {
	display: flex;
	align-items: center;
	gap: 20px;
	flex: 1;
}

.pallet-no {
	font-size: 16px;
	font-weight: bold;
	color: #303133;
}

.goods-count {
	font-size: 14px;
	color: #909399;
}

.goods-select-row {
	display: flex;
	align-items: center;
	padding: 10px 0;
}

:deep(.el-collapse-item__header) {
	padding: 0 16px;
}

:deep(.el-collapse-item__wrap) {
	padding: 16px;
}

:deep(.el-input-number .el-input__inner) {
	text-align: left;
}

.card-header {
	height: 26px;
	font-size: 20px;
	font-weight: bold;
	font-family: 'Times New Roman', Times, serif;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>