<template>
	<el-drawer
		v-model="visible"
		title="选择盘点范围"
		direction="rtl"
		size="500px"
		:close-on-click-modal="false"
	>
		<div class="scope-select-container">
			<!-- 盘点范围类型选择 -->
			<div class="scope-type-section">
				<div class="section-title">盘点范围类型</div>
				<el-radio-group v-model="scopeType" @change="onScopeTypeChange">
					<el-radio :value="1">按仓库盘点</el-radio>
					<el-radio :value="2">按库区盘点</el-radio>
					<el-radio :value="3">按库位盘点</el-radio>
					<el-radio :value="4">按SKU盘点</el-radio>
					<el-radio :value="5">按资产盘点</el-radio>
				</el-radio-group>
			</div>

			<!-- 仓库选择 - 仅当盘点范围<=3时显示 -->
			<div v-if="scopeType <= 3" class="select-section">
				<div class="section-title">
					选择仓库
					<span class="required">*</span>
				</div>
				<el-select
					v-model="selectedWarehouseIds"
					placeholder="请选择仓库"
					style="width: 100%"
					multiple
					collapse-tags
					collapse-tags-tooltip
					@change="onWarehouseChange"
				>
					<el-option v-for="item in warehouseOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</div>

			<!-- 库区选择 - 仅当盘点范围为2或3时显示 -->
			<div v-if="scopeType === 2 || scopeType === 3" class="select-section">
				<div class="section-title">
					选择库区
					<span v-if="scopeType >= 2" class="required">*</span>
				</div>
				<el-select
					v-model="selectedZoneIds"
					placeholder="请先选择仓库"
					style="width: 100%"
					multiple
					collapse-tags
					collapse-tags-tooltip
					:disabled="selectedWarehouseIds.length === 0"
					@change="onZoneChange"
				>
					<el-option v-for="item in zoneOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</div>

			<!-- 库位选择 - 仅当盘点范围为3时显示 -->
			<div v-if="scopeType === 3" class="select-section">
				<div class="section-title">
					选择库位
					<span v-if="scopeType >= 3" class="required">*</span>
				</div>
				<el-select
					v-model="selectedLocationIds"
					placeholder="请先选择库区"
					style="width: 100%"
					multiple
					collapse-tags
					collapse-tags-tooltip
					:disabled="selectedZoneIds.length === 0"
				>
					<el-option v-for="item in locationOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</div>

			<!-- 已选择的摘要 -->
			<div class="selected-summary">
				<div class="section-title">已选择</div>
				<div class="summary-content">
					<div v-if="scopeType <= 3 && selectedWarehouseIds.length > 0" class="summary-item">
						<span class="label">仓库：</span>
						<el-tag v-for="id in selectedWarehouseIds" :key="id" size="small" style="margin: 2px;">
							{{ getWarehouseName(id) }}
						</el-tag>
					</div>
					<div v-if="(scopeType === 2 || scopeType === 3) && selectedZoneIds.length > 0" class="summary-item">
						<span class="label">库区：</span>
						<el-tag v-for="id in selectedZoneIds" :key="id" size="small" type="success" style="margin: 2px;">
							{{ getZoneName(id) }}
						</el-tag>
					</div>
					<div v-if="scopeType === 3 && selectedLocationIds.length > 0" class="summary-item">
						<span class="label">库位：</span>
						<el-tag v-for="id in selectedLocationIds" :key="id" size="small" type="warning" style="margin: 2px;">
							{{ getLocationName(id) }}
						</el-tag>
					</div>
					<div v-if="scopeType <= 3 && selectedWarehouseIds.length === 0" class="empty-tip">暂未选择</div>
					<div v-if="scopeType >= 4" class="empty-tip">无需选择仓库</div>
				</div>
			</div>
		</div>

		<template #footer>
			<el-button style="margin-bottom: 10px;" @click="handleClose">取消</el-button>
			<el-button style="margin-bottom: 10px; margin-right: 10px; " type="primary" @click="handleConfirm">确定</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { listWarehouses } from '/@/api/assets/warehouse';
import { listZones } from '/@/api/assets/zone';
import { listLocations } from '/@/api/assets/location';

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

const visible = ref(false);
const scopeType = ref(1);
const selectedWarehouseIds = ref<string[]>([]);
const selectedZoneIds = ref<string[]>([]);
const selectedLocationIds = ref<string[]>([]);

const warehouseOptions = ref<any[]>([]);
const zoneOptions = ref<any[]>([]);
const locationOptions = ref<any[]>([]);

// 打开抽屉
const openDrawer = async (data?: { scope: number; warehouseIds: string[]; zoneIds: string[]; locationIds: string[] }) => {
	// 重置
	scopeType.value = data?.scope || 1;
	selectedWarehouseIds.value = data?.warehouseIds || [];
	selectedZoneIds.value = data?.zoneIds || [];
	selectedLocationIds.value = data?.locationIds || [];
	
	// 加载仓库列表
	await loadWarehouses();
	
	// 如果有已选仓库，加载库区
	if (selectedWarehouseIds.value.length > 0 && scopeType.value >= 2) {
		await loadZones();
	}
	
	// 如果有已选库区，加载库位
	if (selectedZoneIds.value.length > 0 && scopeType.value >= 3) {
		await loadLocations();
	}
	
	visible.value = true;
};

// 加载仓库列表
const loadWarehouses = async () => {
	try {
		const res: any = await listWarehouses({ pageNum: 1, pageSize: 100 });
		warehouseOptions.value = (res.data?.list || []).map((item: any) => ({
			id: item.id,
			name: item.warehouseName,
		}));
	} catch (error) {
		console.error('加载仓库列表失败:', error);
	}
};

// 加载库区列表
const loadZones = async () => {
	if (selectedWarehouseIds.value.length === 0) {
		zoneOptions.value = [];
		return;
	}
	
	try {
		const allZones: any[] = [];
		for (const warehouseId of selectedWarehouseIds.value) {
			const res: any = await listZones({ warehouseId, pageNum: 1, pageSize: 100 });
			const list = res.data?.list || res.data?.items || res.data || [];
			const zones = (Array.isArray(list) ? list : []).map((item: any) => ({
				id: item.id || item._id,
				name: item.zoneName || item.name,
				warehouseId: item.warehouseId,
			}));
			allZones.push(...zones);
		}
		zoneOptions.value = allZones;
	} catch (error) {
		console.error('加载库区列表失败:', error);
	}
};

// 加载库位列表
const loadLocations = async () => {
	if (selectedZoneIds.value.length === 0) {
		locationOptions.value = [];
		return;
	}
	
	try {
		const allLocations: any[] = [];
		for (const zoneId of selectedZoneIds.value) {
			const res: any = await listLocations({ zoneId, pageNum: 1, pageSize: 100 });
			const list = res.data?.list || res.data?.items || res.data || [];
			const locations = (Array.isArray(list) ? list : []).map((item: any) => ({
				id: item.id || item._id,
				name: item.locationName || item.name,
				zoneId: item.zoneId,
			}));
			allLocations.push(...locations);
		}
		locationOptions.value = allLocations;
	} catch (error) {
		console.error('加载库位列表失败:', error);
	}
};

// 盘点范围类型变化
const onScopeTypeChange = () => {
	// 清空下级选择
	if (scopeType.value < 2) {
		selectedZoneIds.value = [];
		zoneOptions.value = [];
	}
	if (scopeType.value < 3) {
		selectedLocationIds.value = [];
		locationOptions.value = [];
	}
};

// 仓库变化
const onWarehouseChange = async () => {
	selectedZoneIds.value = [];
	selectedLocationIds.value = [];
	zoneOptions.value = [];
	locationOptions.value = [];
	
	if (scopeType.value >= 2) {
		await loadZones();
	}
};

// 库区变化
const onZoneChange = async () => {
	selectedLocationIds.value = [];
	locationOptions.value = [];
	
	if (scopeType.value >= 3) {
		await loadLocations();
	}
};

// 获取仓库名称
const getWarehouseName = (id: string) => {
	return warehouseOptions.value.find(item => item.id === id)?.name || id;
};

// 获取库区名称
const getZoneName = (id: string) => {
	return zoneOptions.value.find(item => item.id === id)?.name || id;
};

// 获取库位名称
const getLocationName = (id: string) => {
	return locationOptions.value.find(item => item.id === id)?.name || id;
};

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

// 确认选择
const handleConfirm = () => {
	// 验证 - 按SKU盘点(4)和按资产盘点(5)不需要选择仓库
	if (scopeType.value <= 3 && selectedWarehouseIds.value.length === 0) {
		ElMessage.warning('请选择仓库');
		return;
	}
	
	if ((scopeType.value === 2 || scopeType.value === 3) && selectedZoneIds.value.length === 0) {
		ElMessage.warning('请选择库区');
		return;
	}
	
	if (scopeType.value === 3 && selectedLocationIds.value.length === 0) {
		ElMessage.warning('请选择库位');
		return;
	}
	
	emit('confirm', {
		scope: scopeType.value,
		warehouseIds: selectedWarehouseIds.value,
		zoneIds: selectedZoneIds.value,
		locationIds: selectedLocationIds.value,
		// 用于显示的名称
		warehouseNames: selectedWarehouseIds.value.map(id => getWarehouseName(id)),
		zoneNames: selectedZoneIds.value.map(id => getZoneName(id)),
		locationNames: selectedLocationIds.value.map(id => getLocationName(id)),
	});
	
	handleClose();
};

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

<style scoped>
.scope-select-container {
	padding: 0 10px;
}

.scope-type-section {
	margin-bottom: 24px;
	padding-bottom: 16px;
	border-bottom: 1px solid #ebeef5;
}

.section-title {
	font-size: 14px;
	font-weight: 500;
	color: #303133;
	margin-bottom: 12px;
}

.section-title .required {
	color: #f56c6c;
	margin-left: 4px;
}

.select-section {
	margin-bottom: 20px;
}

.selected-summary {
	margin-top: 24px;
	padding-top: 16px;
	border-top: 1px solid #ebeef5;
}

.summary-content {
	background: #f5f7fa;
	border-radius: 4px;
	padding: 12px;
	min-height: 60px;
}

.summary-item {
	margin-bottom: 8px;
}

.summary-item:last-child {
	margin-bottom: 0;
}

.summary-item .label {
	font-size: 13px;
	color: #606266;
	margin-right: 8px;
}

.empty-tip {
	color: #909399;
	font-size: 13px;
	text-align: center;
	padding: 10px 0;
}
</style>
