<template>
	<el-dialog
		v-model="visible"
		:title="form.id ? '编辑盘点任务' : '新增盘点任务'"
		width="700px"
		:close-on-click-modal="false"
		@close="handleClose"
	>
		<el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
			<el-form-item label="任务名称" prop="title">
				<el-input v-model="form.title" placeholder="请输入任务名称" maxlength="50" show-word-limit />
			</el-form-item>
			
			<el-form-item label="任务描述" prop="description">
				<el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入任务描述" maxlength="200" show-word-limit />
			</el-form-item>
			
			<el-form-item label="盘点类型" prop="countType">
				<el-select v-model="form.countType" placeholder="请选择盘点类型" style="width: 100%">
					<el-option label="明盘" :value="1" />
					<el-option label="盲盘" :value="2" />
				</el-select>
			</el-form-item>
			
			<el-form-item label="盘点范围类型" prop="scope">
				<el-select v-model="form.scope" placeholder="请选择盘点范围类型" style="width: 100%" @change="onScopeTypeChange">
					<el-option label="按仓库盘点" :value="1" />
					<el-option label="按库区盘点" :value="2" />
					<el-option label="按库位盘点" :value="3" />
					<el-option label="按SKU盘点" :value="4" />
					<el-option label="按资产盘点" :value="5" />
				</el-select>
			</el-form-item>
			
			<!-- 选择仓库（按仓库/库区/库位盘点都需要） -->
			<el-form-item label="选择仓库" prop="warehouseIds" v-if="form.scope >= 1 && form.scope <= 3">
				<div class="scope-select-box">
					<div class="scope-tags" v-if="form.warehouseIds.length > 0">
						<el-tag v-for="name in selectedWarehouseNames" :key="name" size="small" closable @close="removeWarehouse(name)">{{ name }}</el-tag>
					</div>
					<el-button type="primary" @click="openSelectDialog(1)">
						<el-icon><ele-Plus /></el-icon>
						{{ form.warehouseIds.length > 0 ? '继续选择' : '选择仓库' }}
					</el-button>
				</div>
			</el-form-item>
			
			<!-- 选择库区（按库区/库位盘点需要） -->
			<el-form-item label="选择库区" prop="zoneIds" v-if="form.scope >= 2 && form.scope <= 3">
				<div class="scope-select-box">
					<div class="scope-tags" v-if="form.zoneIds.length > 0">
						<el-tag v-for="name in selectedZoneNames" :key="name" size="small" type="success" closable @close="removeZone(name)">{{ name }}</el-tag>
					</div>
					<el-button type="primary" @click="openSelectDialog(2)" :disabled="form.warehouseIds.length === 0">
						<el-icon><ele-Plus /></el-icon>
						{{ form.zoneIds.length > 0 ? '继续选择' : '选择库区' }}
					</el-button>
					<span v-if="form.warehouseIds.length === 0" class="tip-text">请先选择仓库</span>
				</div>
			</el-form-item>
			
			<!-- 选择库位（按库位盘点需要） -->
			<el-form-item label="选择库位" prop="locationIds" v-if="form.scope === 3">
				<div class="scope-select-box">
					<div class="scope-tags" v-if="form.locationIds.length > 0">
						<el-tag v-for="name in selectedLocationNames" :key="name" size="small" type="warning" closable @close="removeLocation(name)">{{ name }}</el-tag>
					</div>
					<el-button type="primary" @click="openSelectDialog(3)" :disabled="form.zoneIds.length === 0">
						<el-icon><ele-Plus /></el-icon>
						{{ form.locationIds.length > 0 ? '继续选择' : '选择库位' }}
					</el-button>
					<span v-if="form.zoneIds.length === 0" class="tip-text">请先选择库区</span>
				</div>
			</el-form-item>
			
			<!-- 选择弹窗 -->
			<ScopeSelectDialog ref="scopeSelectDialogRef" @confirm="onSelectConfirm" />
			
			
			<el-form-item label="负责人" prop="assigneeId">
				<el-input v-model="form.assigneeId" placeholder="请输入负责人" />
			</el-form-item>
			
			<el-form-item label="参与人员" prop="participants">
				<el-input v-model="participantsInput" placeholder="请输入参与人员，多人用逗号分隔" />
			</el-form-item>
			
			<el-form-item label="备注" prop="remark">
				<el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" maxlength="500" show-word-limit />
			</el-form-item>
		</el-form>
		
		<template #footer>
			<el-button @click="handleClose">取消</el-button>
			<el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { createInventoryCount, updateInventoryCount, getInventoryCount } from '/@/api/assets/operation/count';
import ScopeSelectDialog from './scopeSelectDialog.vue';

const emit = defineEmits(['refresh']);

const visible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();
const scopeSelectDialogRef = ref();

// 表单数据
const form = reactive({
	id: '',
	title: '',
	description: '',
	warehouseIds: [] as string[],
	zoneIds: [] as string[],
	locationIds: [] as string[],
	countType: undefined as number | undefined,
	scope: 1 as number,
	assigneeId: '',
	participants: [] as string[],
	remark: '',
});

// 选中的名称（用于显示）
const selectedWarehouseNames = ref<string[]>([]);
const selectedZoneNames = ref<string[]>([]);
const selectedLocationNames = ref<string[]>([]);

// 参与人员输入框
const participantsInput = ref('');

// 当前选择的类型（1-仓库 2-库区 3-库位）
const currentSelectType = ref(1);

// 移除仓库
const removeWarehouse = (name: string) => {
	const idx = selectedWarehouseNames.value.indexOf(name);
	if (idx > -1) {
		selectedWarehouseNames.value.splice(idx, 1);
		form.warehouseIds.splice(idx, 1);
		// 清空下级选择
		form.zoneIds = [];
		form.locationIds = [];
		selectedZoneNames.value = [];
		selectedLocationNames.value = [];
	}
};

// 移除库区
const removeZone = (name: string) => {
	const idx = selectedZoneNames.value.indexOf(name);
	if (idx > -1) {
		selectedZoneNames.value.splice(idx, 1);
		form.zoneIds.splice(idx, 1);
		// 清空下级选择
		form.locationIds = [];
		selectedLocationNames.value = [];
	}
};

// 移除库位
const removeLocation = (name: string) => {
	const idx = selectedLocationNames.value.indexOf(name);
	if (idx > -1) {
		selectedLocationNames.value.splice(idx, 1);
		form.locationIds.splice(idx, 1);
	}
};

// 盘点范围类型变化
const onScopeTypeChange = () => {
	// 清空已选项
	form.warehouseIds = [];
	form.zoneIds = [];
	form.locationIds = [];
	selectedWarehouseNames.value = [];
	selectedZoneNames.value = [];
	selectedLocationNames.value = [];
};

// 表单校验规则
const rules = reactive<FormRules>({
	title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
	countType: [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
	assigneeId: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
	warehouseIds: [{ 
		required: true, 
		message: '请选择盘点范围', 
		trigger: 'change',
		validator: (_rule: any, _value: any, callback: any) => {
			// 按SKU盘点(4)和按资产盘点(5)不需要选择仓库
			if (form.scope >= 4) {
				callback();
			} else if (form.warehouseIds.length === 0) {
				callback(new Error('请选择盘点范围'));
			} else {
				callback();
			}
		}
	}],
});

// 打开弹窗
const openDialog = async (row?: any) => {
	resetForm();
	
	if (row?.id) {
		try {
			const res: any = await getInventoryCount(row.id);
			if (res.code === 0 && res.data) {
				const data = res.data;
				form.id = data.id || '';
				form.title = data.title || '';
				form.description = data.description || '';
				form.countType = data.countType;
				form.scope = data.scope || 1;
			
				form.assigneeId = data.assigneeId || '';
				form.remark = data.remark || '';
				// 处理仓库/库区/库位ID（后端返回warehouseIDs，前端使用warehouseIds）
				form.warehouseIds = Array.isArray(data.warehouseIDs) ? data.warehouseIDs : (data.warehouseIDs ? [data.warehouseIDs] : []);
				form.zoneIds = Array.isArray(data.zoneIDs) ? data.zoneIDs : (data.zoneIDs ? [data.zoneIDs] : []);
				form.locationIds = Array.isArray(data.locationIDs) ? data.locationIDs : (data.locationIDs ? [data.locationIDs] : []);
				// 回显参与人员
				if (data.participants && Array.isArray(data.participants)) {
					participantsInput.value = data.participants.join(',');
				}
			}
		} catch (error) {
			console.error('获取盘点任务详情失败:', error);
		}
	}
	
	visible.value = true;
};

// 重置表单
const resetForm = () => {
	form.id = '';
	form.title = '';
	form.description = '';
	form.warehouseIds = [];
	form.zoneIds = [];
	form.locationIds = [];
	form.countType = undefined;
	form.scope = 1;
	
	form.assigneeId = '';
	form.participants = [];
	form.remark = '';
	participantsInput.value = '';
	selectedWarehouseNames.value = [];
	selectedZoneNames.value = [];
	selectedLocationNames.value = [];
	formRef.value?.resetFields();
};

// 打开选择弹窗
const openSelectDialog = (type: number) => {
	currentSelectType.value = type;
	let selectedIds: string[] = [];
	let selectedNames: string[] = [];
	
	if (type === 1) {
		selectedIds = form.warehouseIds;
		selectedNames = selectedWarehouseNames.value;
	} else if (type === 2) {
		selectedIds = form.zoneIds;
		selectedNames = selectedZoneNames.value;
	} else if (type === 3) {
		selectedIds = form.locationIds;
		selectedNames = selectedLocationNames.value;
	}
	
	scopeSelectDialogRef.value?.open({
		scope: type,
		selectedIds,
		selectedNames,
		warehouseIds: form.warehouseIds,
		zoneIds: form.zoneIds,
	});
};

// 选择确认
const onSelectConfirm = (data: any) => {
	if (currentSelectType.value === 1) {
		form.warehouseIds = data.selectedIds;
		selectedWarehouseNames.value = data.selectedNames;
		// 清空下级选择
		form.zoneIds = [];
		form.locationIds = [];
		selectedZoneNames.value = [];
		selectedLocationNames.value = [];
	} else if (currentSelectType.value === 2) {
		form.zoneIds = data.selectedIds;
		selectedZoneNames.value = data.selectedNames;
		// 清空下级选择
		form.locationIds = [];
		selectedLocationNames.value = [];
	} else if (currentSelectType.value === 3) {
		form.locationIds = data.selectedIds;
		selectedLocationNames.value = data.selectedNames;
	}
};

// 关闭弹窗
const handleClose = () => {
	visible.value = false;
};

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return;
	
	await formRef.value.validate(async (valid) => {
		if (!valid) return;
		
		loading.value = true;
		try {
			// 构建提交数据
			const submitData: any = {
				title: form.title,
				description: form.description || undefined,
				countType: form.countType,
				scope: form.scope,
				participants: participantsInput.value ? participantsInput.value.split(',').map(s => s.trim()).filter(s => s) : undefined,
				remark: form.remark || undefined,
			};
			
			// 添加选中的仓库/库区/库位ID数组
			if (form.warehouseIds.length > 0) submitData.warehouseIDs = form.warehouseIds;
			if (form.zoneIds.length > 0) submitData.zoneIDs = form.zoneIds;
			if (form.locationIds.length > 0) submitData.locationIDs = form.locationIds;
			if (form.assigneeId) submitData.assigneeId = form.assigneeId;
			
			let res: any;
			if (form.id) {
				submitData.id = form.id;
				res = await updateInventoryCount(submitData);
			} else {
				res = await createInventoryCount(submitData);
			}
			
			if (res.code === 0) {
				ElMessage.success(form.id ? '修改成功' : '新增成功');
				emit('refresh');
				handleClose();
			} else {
				ElMessage.error(res.message || '操作失败');
			}
		} catch (error) {
			console.error('保存盘点任务失败:', error);
			ElMessage.error('操作失败');
		} finally {
			loading.value = false;
		}
	});
};

defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.scope-select-box {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 8px;
	
	.scope-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 4px;
	}
	
	.tip-text {
		font-size: 12px;
		color: #909399;
		margin-left: 8px;
	}
}
</style>
