<template>
	<div class="assets-location-page">
		<div class="assets-location-container">
			<el-card shadow="hover">
				<div class="assets-location-search mb15">
					<el-form :inline="true" :model="tableData.param">
						<el-form-item label="库位名称">
							<el-input size="default" v-model="tableData.param.keyword" placeholder="请输入库位名称" clearable style="width: 200px" />
						</el-form-item>
						<el-form-item label="所属仓库">
							<el-select size="default" v-model="tableData.param.warehouseId" placeholder="请选择仓库" clearable style="width: 180px" @change="onWarehouseChange">
								<el-option v-for="item in warehouseOptions" :key="item.id" :label="item.warehouseName" :value="item.id" />
							</el-select>
						</el-form-item>
						<el-form-item label="所属库区">
							<el-select size="default" v-model="tableData.param.zoneId" placeholder="请选择库区" clearable style="width: 180px">
								<el-option v-for="item in filteredZoneOptions" :key="item.id" :label="item.zoneName" :value="item.id" />
							</el-select>
						</el-form-item>
						<el-form-item label="状态">
							<el-select size="default" v-model="tableData.param.status" placeholder="请选择状态" clearable style="width: 120px">
								<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-form-item>
							<el-button size="default" type="primary" @click="getLocationList">
								<el-icon><ele-Search /></el-icon>
								查询
							</el-button>
							<el-button size="default" @click="onResetQuery">
								<el-icon><ele-Refresh /></el-icon>
								重置
							</el-button>
							<el-button size="default" type="success" @click="onOpenAdd">
								<el-icon><ele-Plus /></el-icon>
								新增
							</el-button>
						</el-form-item>
					</el-form>
				</div>
				<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading" border>
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="locationName" label="库位名称" min-width="150" show-overflow-tooltip />
					<el-table-column prop="locationCode" label="库位编码" width="120" show-overflow-tooltip />
					<el-table-column prop="locationType" label="库位类型" width="100" show-overflow-tooltip />
					<el-table-column prop="warehouseName" label="所属仓库" width="150" show-overflow-tooltip />
					<el-table-column prop="zoneName" label="所属库区" width="150" show-overflow-tooltip />
					<el-table-column prop="maxCapacity" label="最大容量" width="100" align="center" />
					<el-table-column prop="status" label="状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="170" show-overflow-tooltip />
					<el-table-column prop="updatedAt" label="修改时间" width="170" show-overflow-tooltip />
					<el-table-column label="操作" width="180" fixed="right" align="center">
						<template #default="scope">
							<el-button size="small" text type="primary" @click="onEdit(scope.row)">修改</el-button>
							<el-button size="small" text type="info" @click="onViewLog(scope.row)">日志</el-button>
							<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<div class="mt15" style="text-align: right">
					<el-pagination
						v-model:current-page="tableData.param.pageNum"
						v-model:page-size="tableData.param.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="tableData.total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="onSizeChange"
						@current-change="onCurrentChange"
					/>
				</div>
			</el-card>
		</div>
		<EditLocation ref="editLocationRef" :warehouseOptions="warehouseOptions" :zoneOptions="zoneOptions" @getLocationList="getLocationList" />
		<OperationLogDialog ref="operationLogRef" />
	</div>
</template>

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

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listLocations, deleteLocation } from '/@/api/assets/location';
import { listWarehouses } from '/@/api/assets/warehouse';
import { listZones } from '/@/api/assets/zone';
import EditLocation from './component/editLocation.vue';
import OperationLogDialog from '/@/views/assets/component/operationLogDialog.vue';

// 表格数据
const tableData = reactive({
	data: [] as any[],
	total: 0,
	loading: false,
	param: {
		keyword: '',
		warehouseId: '',
		zoneId: '',
		status: undefined as string | undefined,
		pageNum: 1,
		pageSize: 10,
	},
});

// 仓库选项
const warehouseOptions = ref<any[]>([]);
// 库区选项
const zoneOptions = ref<any[]>([]);

// 根据选中的仓库过滤库区选项
const filteredZoneOptions = computed(() => {
	if (!tableData.param.warehouseId) {
		return zoneOptions.value;
	}
	return zoneOptions.value.filter((z: any) => z.warehouseId === tableData.param.warehouseId);
});

// 编辑弹窗ref
const editLocationRef = ref();
// 日志弹窗ref
const operationLogRef = ref();

// 获取仓库列表
const getWarehouseOptions = async () => {
	try {
		const res: any = await listWarehouses({ pageNum: 1, pageSize: 1000 });
		warehouseOptions.value = res.data?.list || [];
	} catch (error) {
		console.error('获取仓库列表失败:', error);
	}
};

// 获取库区列表
const getZoneOptions = async () => {
	try {
		const res: any = await listZones({ pageNum: 1, pageSize: 1000 });
		zoneOptions.value = res.data?.list || [];
	} catch (error) {
		console.error('获取库区列表失败:', error);
	}
};

// 仓库选择变化时清空库区选择
const onWarehouseChange = () => {
	tableData.param.zoneId = '';
};

// 获取库位列表
const getLocationList = async () => {
	tableData.loading = true;
	try {
		const res: any = await listLocations(tableData.param);
		const list = res.data?.list || [];
		// 回填仓库名称和库区名称
		const warehouseMap = new Map(warehouseOptions.value.map((w: any) => [w.id, w.warehouseName]));
		const zoneMap = new Map(zoneOptions.value.map((z: any) => [z.id, z.zoneName]));
		tableData.data = list.map((item: any) => ({
			...item,
			warehouseName: item.warehouseName || warehouseMap.get(item.warehouseId) || '',
			zoneName: item.zoneName || zoneMap.get(item.zoneId) || '',
					}));
		tableData.total = res.data?.total || 0;
	} catch (error) {
		console.error('获取库位列表失败:', error);
	} finally {
		tableData.loading = false;
	}
};

// 重置查询
const onResetQuery = () => {
	tableData.param.keyword = '';
	tableData.param.warehouseId = '';
	tableData.param.zoneId = '';
	tableData.param.status = undefined;
	tableData.param.pageNum = 1;
	getLocationList();
};

// 打开新增弹窗
const onOpenAdd = () => {
	editLocationRef.value.openDialog();
};

// 打开编辑弹窗
const onEdit = (row: any) => {
	editLocationRef.value.openDialog(row);
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
	switch (status) {
		case 'idle':
			return 'success';
		case 'occupied':
			return 'warning';
		case 'disable':
			return 'danger';
		case 'reserved':
			return 'info';
		default:
			return 'info';
	}
};

// 获取状态文本
const getStatusText = (status: string) => {
	switch (status) {
		case 'idle':
			return '空闲';
		case 'occupied':
			return '占用';
		case 'disable':
			return '禁用';
		case 'reserved':
			return '预留';
		default:
			return status;
	}
};

// 查看日志
const onViewLog = (row: any) => {
	operationLogRef.value?.openDialog(row.id);
};

// 删除库位
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`确定要删除库位【${row.locationName}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			await deleteLocation(row.id);
			ElMessage.success('删除成功');
			getLocationList();
		} catch (error) {
			console.error('删除失败:', error);
		}
	}).catch(() => {});
};

// 分页大小改变
const onSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	getLocationList();
};

// 当前页改变
const onCurrentChange = (page: number) => {
	tableData.param.pageNum = page;
	getLocationList();
};

// 页面加载时获取数据
onMounted(async () => {
	await Promise.all([getWarehouseOptions(), getZoneOptions()]);
	getLocationList();
});
</script>

<style scoped lang="scss">
.assets-location-page {
	padding: 15px;
	.assets-location-container {
		.assets-location-search {
			.el-form-item {
				margin-bottom: 10px;
				margin-right: 16px;
			}
		}
	}
}
</style>
