<template>
	<el-dialog v-model="visible" title="选择设备分类" width="800px" :close-on-click-modal="false" @close="onCancel">
		<div style="margin-bottom: 12px">
			<el-input v-model="search" placeholder="输入关键字搜索" style="width: 240px; margin-right: 8px" @keyup.enter="fetchData(true)" />
			<el-button type="primary" @click="fetchData(true)">搜索</el-button>
		</div>
		<el-table :data="tableData" border style="width: 100%" @selection-change="onSelectionChange" ref="tableRef" row-key="id">
			<el-table-column type="selection" width="50" :reserve-selection="true" />
			<el-table-column type="index" label="序号" width="60" />
            <!-- <el-table-column prop="code" label="分类编号" /> -->
			<el-table-column prop="name" label="设备分类" />
			<el-table-column prop="description" label="描述" min-width="160" />
		<!-- 	<el-table-column prop="category_name" label="设备分类" /> 
			<el-table-column prop="warehouse" label="存放仓库" />-->
		</el-table>
		<el-pagination
			style="margin-top: 12px; text-align: right"
			:current-page="page"
			:page-size="pageSize"
			:total="total"
			@current-change="onPageChange"
		/>
		<template #footer>
			<el-button @click="onCancel">取消</el-button>
			<el-button type="primary" @click="onConfirm">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, nextTick } from 'vue';
import * as deviceApi from '../../../deviceclass/api';
import * as storeapi from '../../../storelist/api';
import { status } from 'nprogress';

const props = defineProps<{ visible: boolean }>();
const emit = defineEmits(['update:visible', 'confirm']);

const visible = ref(props.visible);
watch(
	() => props.visible,
	(v) => (visible.value = v)
);

const search = ref('');
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const warehouseMap = ref<Record<number, string>>({});
// 用于存储所有已选中的项（跨页）
const selectedMap = ref<Map<number | string, any>>(new Map());
const tableRef = ref();
// 标志位：是否正在恢复选中状态（避免触发 onSelectionChange 时误删数据）
const isRestoring = ref(false);


function fetchWarehouseMap() {
    storeapi.GetPermission().then((res: any) => {
        const map: Record<number, string> = {};
        res.data.forEach((item: any) => {
            map[item.id] = item.name;
        });
        warehouseMap.value = map;
    });
}


async function fetchData(resetPage = false) {
	if (resetPage) page.value = 1;
	await fetchWarehouseMap(); 
	deviceApi.GetList({ page: page.value, limit: pageSize.value, code: search.value,status:1 })
	.then((res: any) => {
		const devices = res.data
		/* .filter(device => device.available_quantity > 0)
		.map((device) => ({
            ...device,
            warehouse: `${warehouseMap.value[device.warehouse] || `ID:${device.warehouse}`} (${device.available_quantity})`
        })); */
		tableData.value = devices;
		// tableData.value = [...res.data];
		total.value = res.total;
		// 数据加载完成后，回显当前页的选中状态
		nextTick(() => {
			restoreSelection();
		});
	});
}
// 恢复当前页的选中状态
function restoreSelection() {
	if (!tableRef.value) return;
	// 设置标志位，避免 onSelectionChange 误删数据
	isRestoring.value = true;
	
	// 先清空当前页的所有选中
	tableData.value.forEach((row: any) => {
		tableRef.value.toggleRowSelection(row, false);
	});
	// 根据 selectedMap 设置当前页的选中状态
	tableData.value.forEach((row: any) => {
		if (selectedMap.value.has(row.id)) {
			tableRef.value.toggleRowSelection(row, true);
		}
	});
	
	// 恢复标志位
	isRestoring.value = false;
	// 更新当前页的选中数组
	updateSelectedRows();
}

// 更新当前页的选中数组
function updateSelectedRows() {
	selectedRows.value = tableData.value.filter((row: any) => selectedMap.value.has(row.id));
}

function onSelectionChange(val: any[]) {
	// 如果正在恢复选中状态，不更新 selectedMap（避免误删数据）
	if (isRestoring.value) {
		return;
	}
	
	// 获取当前页所有行的 id
	const currentPageIds = new Set(tableData.value.map((row: any) => row.id));
	
	// 移除当前页中未选中的项
	currentPageIds.forEach((id) => {
		const isSelected = val.some((item: any) => item.id === id);
		if (!isSelected) {
			selectedMap.value.delete(id);
		}
	});
	
	// 添加当前页中新选中的项
	val.forEach((item: any) => {
		if (!selectedMap.value.has(item.id)) {
			selectedMap.value.set(item.id, item);
		} else {
			// 如果已存在，更新数据（防止数据过期）
			selectedMap.value.set(item.id, item);
		}
	});
	
	// 更新当前页的选中数组
	selectedRows.value = val;
}
function onPageChange(val: number) {
	page.value = val;
	fetchData();
}
function onConfirm() {
	// 返回所有选中的项（跨页）
	const allSelected = Array.from(selectedMap.value.values());
	emit('confirm', allSelected);
	emit('update:visible', false);
}
function onCancel() {
	// 取消时清空选中状态
	selectedMap.value.clear();
	selectedRows.value = [];
	emit('update:visible', false);
}
watch([visible, page], (v) => {
	if (visible.value) {
		fetchData();
	} else {
		// 对话框关闭时不清空选中状态，以便下次打开时保留
		// 如果需要关闭时清空，可以在这里调用 selectedMap.value.clear()
	}
});
</script>
