<template>
	<el-dialog
		:title="isEdit ? '修改库位' : '新增库位'"
		v-model="isShowDialog"
		width="600px"
		:close-on-click-modal="false"
		@close="onCancel"
	>
		<el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="100px">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="库位名称" prop="locationName">
						<el-input v-model="ruleForm.locationName" placeholder="请输入库位名称" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="库位编码" prop="locationCode">
						<el-input v-model="ruleForm.locationCode" placeholder="请输入库位编码" clearable />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="所属仓库" prop="warehouseId">
						<el-input v-model="warehouseDisplayName" placeholder="请选择仓库" readonly style="width: 100%" @click="onSelectWarehouse">
							<template #append>
								<el-button :icon="Search" @click="onSelectWarehouse" />
							</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="所属库区" prop="zoneId">
						<el-input v-model="zoneDisplayName" placeholder="请先选择仓库" readonly :disabled="!ruleForm.warehouseId" style="width: 100%" @click="onSelectZone">
							<template #append>
								<el-button :icon="Search" @click="onSelectZone" />
							</template>
						</el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="库位类型" prop="locationType">
						<el-select v-model="ruleForm.locationType" placeholder="请选择库位类型" clearable style="width: 100%">
							<el-option label="货架位" value="货架位" />
							<el-option label="地面位" value="地面位" />
							<el-option label="托盘位" value="托盘位" />
							<el-option label="悬挂位" value="悬挂位" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="状态" prop="status">
						<el-select v-model="ruleForm.status" placeholder="请选择状态" clearable style="width: 100%">
							<el-option label="空闲" value="idle" />
							<el-option label="占用" value="occupied" />
							<el-option label="禁用" value="disable" />
							<el-option label="预留" value="reserved" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="单位类型" prop="capacityUnitType">
						<el-select v-model="ruleForm.capacityUnitType" placeholder="请选择单位类型" clearable style="width: 100%">
							<el-option v-for="item in capacityUnitTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="容量单位" prop="capacityUnit">
						<el-input v-model="ruleForm.capacityUnit" placeholder="请输入容量单位" clearable />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="最大容量" prop="maxCapacity">
						<el-input-number v-model="ruleForm.maxCapacity" :min="0" placeholder="请输入最大容量" style="width: 100%" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="备注" prop="remark">
						<el-input v-model="ruleForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="submitLoading">{{ isEdit ? '修 改' : '添 加' }}</el-button>
			</span>
		</template>
	</el-dialog>
	<SelectWarehouseDialog ref="selectWarehouseRef" @confirm="onWarehouseSelected" />
	<SelectZoneDialog ref="selectZoneRef" @confirm="onZoneSelected" />
</template>

<script lang="ts">
export default {
	name: 'editLocation',
};
</script>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { createLocation, updateLocation, getLocation, getCapacityUnitType } from '/@/api/assets/location';
import SelectWarehouseDialog from '/@/views/assets/component/selectWarehouseDialog.vue';
import SelectZoneDialog from '/@/views/assets/component/selectZoneDialog.vue';

// 定义props
const props = defineProps<{
	warehouseOptions: any[];
	zoneOptions: any[];
}>();

// 定义事件
const emit = defineEmits(['getLocationList']);

// 表单ref
const formRef = ref<FormInstance>();

// 弹窗状态
const isShowDialog = ref(false);
const isEdit = ref(false);
const submitLoading = ref(false);

// 容量单位类型选项
const capacityUnitTypeOptions = ref<{ label: string; value: string }[]>([]);

// 仓库选择弹窗ref
const selectWarehouseRef = ref();
// 库区选择弹窗ref
const selectZoneRef = ref();
// 仓库显示名称
const warehouseDisplayName = ref('');
// 库区显示名称
const zoneDisplayName = ref('');

// 打开仓库选择弹窗
const onSelectWarehouse = () => {
	selectWarehouseRef.value?.openDialog();
};

// 打开库区选择弹窗
const onSelectZone = () => {
	if (!ruleForm.warehouseId) {
		ElMessage.warning('请先选择仓库');
		return;
	}
	selectZoneRef.value?.openDialog(ruleForm.warehouseId);
};

// 仓库选择确认
const onWarehouseSelected = (row: any) => {
	ruleForm.warehouseId = row.id;
	warehouseDisplayName.value = row.warehouseName;
	// 清空库区选择
	ruleForm.zoneId = '';
	zoneDisplayName.value = '';
};

// 库区选择确认
const onZoneSelected = (row: any) => {
	ruleForm.zoneId = row.id;
	zoneDisplayName.value = row.zoneName;
};

// 表单数据
const ruleForm = reactive({
	id: '',
	locationName: '',
	locationCode: '',
	locationType: '',
	warehouseId: '',
	zoneId: '',
	status: 'idle',
	capacityUnitType: '',
	capacityUnit: '',
	maxCapacity: 0,
	remark: '',
});

// 表单验证规则
const rules = reactive<FormRules>({
	locationName: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
	locationCode: [{ required: true, message: '请输入库位编码', trigger: 'blur' }],
	locationType: [{ required: true, message: '请选择库位类型', trigger: 'change' }],
	warehouseId: [{ required: true, message: '请选择所属仓库', trigger: 'change' }],
	zoneId: [{ required: true, message: '请选择所属库区', trigger: 'change' }],
	capacityUnitType: [{ required: true, message: '请选择容量单位类型', trigger: 'change' }],
	capacityUnit: [{ required: true, message: '请输入容量单位', trigger: 'blur' }],
	maxCapacity: [{ required: true, message: '请输入最大容量', trigger: 'blur' }],
});

// 重置表单
const resetForm = () => {
	ruleForm.id = '';
	ruleForm.locationName = '';
	ruleForm.locationCode = '';
	ruleForm.locationType = '';
	ruleForm.warehouseId = '';
	ruleForm.zoneId = '';
	ruleForm.status = 'idle';
	ruleForm.capacityUnitType = '';
	ruleForm.capacityUnit = '';
	ruleForm.maxCapacity = 0;
	ruleForm.remark = '';
	warehouseDisplayName.value = '';
	zoneDisplayName.value = '';
};

// 加载容量单位类型选项
const loadCapacityUnitTypeOptions = async () => {
	try {
		const res: any = await getCapacityUnitType();
		if (res.data?.options && Array.isArray(res.data.options)) {
			capacityUnitTypeOptions.value = res.data.options.map((item: any) => ({
				label: item.value,
				value: item.key,
			}));
		}
	} catch (error) {
		console.error('获取容量单位类型失败:', error);
	}
};

// 打开弹窗
const openDialog = async (row?: any) => {
	resetForm();
	isEdit.value = !!row;
	
	// 加载容量单位类型选项
	await loadCapacityUnitTypeOptions();
	
	if (row) {
		try {
			const res: any = await getLocation(row.id);
			const data = res.data;
			ruleForm.id = data.id || '';
			ruleForm.locationName = data.locationName || '';
			ruleForm.locationCode = data.locationCode || '';
			ruleForm.locationType = data.locationType || '';
			ruleForm.warehouseId = data.warehouseId || '';
			ruleForm.zoneId = data.zoneId || '';
			warehouseDisplayName.value = data.warehouseName || '';
			zoneDisplayName.value = data.zoneName || '';
			ruleForm.status = data.status || 'idle';
			ruleForm.capacityUnitType = data.capacityUnitType || '';
			ruleForm.capacityUnit = data.capacityUnit || '';
			ruleForm.maxCapacity = data.maxCapacity || 0;
			ruleForm.remark = data.remark || '';
		} catch (error) {
			console.error('获取库位详情失败:', error);
		}
	}
	
	isShowDialog.value = true;
};

// 取消
const onCancel = () => {
	isShowDialog.value = false;
	formRef.value?.resetFields();
};

// 提交
const onSubmit = async () => {
	const form = formRef.value;
	if (!form) return;
	
	form.validate(async (valid: boolean) => {
		if (valid) {
			submitLoading.value = true;
			try {
				const data = {
					id: ruleForm.id || undefined,
					locationName: ruleForm.locationName,
					locationCode: ruleForm.locationCode,
					locationType: ruleForm.locationType,
					warehouseId: ruleForm.warehouseId,
					zoneId: ruleForm.zoneId,
					status: ruleForm.status,
					capacityUnitType: ruleForm.capacityUnitType,
					capacityUnit: ruleForm.capacityUnit,
					maxCapacity: ruleForm.maxCapacity,
					remark: ruleForm.remark,
				};
				
				if (isEdit.value) {
					await updateLocation(data);
					ElMessage.success('修改成功');
				} else {
					await createLocation(data);
					ElMessage.success('添加成功');
				}
				
				isShowDialog.value = false;
				emit('getLocationList');
			} catch (error) {
				console.error('提交失败:', error);
			} finally {
				submitLoading.value = false;
			}
		}
	});
};

// 暴露方法
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
</style>
