import { _asyncToGenerator } from "../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { normalizeText } from "../../../model/constants.js";
import { createDeviceRow } from "../../../model/adapters.js";
import { createDevice, deleteDevice, getDevices, sortDevices, updateDevice } from "../../../api/devices.js";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRequest } from "ahooks";
//#region src/plus/saasDevice/devicePlanning/modules/devices/hooks/useDeviceList.ts
const EMPTY_DEVICES = [];
const isSameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
/** 管理当前工作区和设备种类下的设备列表、筛选、分页、排序与 CRUD 请求。 */
const useDeviceList = ({ activeKind, selectedWorkAreaId, translation, profileNameMap }) => {
	const [search, setSearch] = useState("");
	const [typeFilter, setTypeFilter] = useState(void 0);
	const [structureFilter, setStructureFilter] = useState(void 0);
	const [deviceOrderIds, setDeviceOrderIds] = useState([]);
	const [page, setPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const deviceRequest = useRequest(getDevices, { manual: true });
	const createDeviceRequest = useRequest(createDevice, { manual: true });
	const updateDeviceRequest = useRequest((params) => updateDevice(params.id, params.payload), { manual: true });
	const removeDeviceRequest = useRequest(deleteDevice, { manual: true });
	const sortDeviceRequest = useRequest(sortDevices, { manual: true });
	/** 设备列表请求参数统一在这里生成，保证刷新和首次加载一致。 */
	const getDeviceListParams = useCallback(() => ({
		workarea_id: selectedWorkAreaId,
		type_kind: activeKind,
		with: [
			"type",
			"model",
			"workarea"
		]
	}), [activeKind, selectedWorkAreaId]);
	useEffect(() => {
		if (!selectedWorkAreaId) return;
		deviceRequest.run(getDeviceListParams());
	}, [getDeviceListParams, selectedWorkAreaId]);
	useEffect(() => {
		setSearch("");
		setTypeFilter(void 0);
		setStructureFilter(void 0);
		setPage(1);
	}, [activeKind, selectedWorkAreaId]);
	const devices = deviceRequest.data || EMPTY_DEVICES;
	useEffect(() => {
		const nextIds = devices.map((item) => item.id);
		setDeviceOrderIds((prev) => isSameIds(prev, nextIds) ? prev : nextIds);
	}, [devices]);
	const toDeviceRow = useCallback((item) => createDeviceRow(item, translation, profileNameMap), [profileNameMap, translation]);
	const orderedRows = useMemo(() => {
		const orderMap = new Map(deviceOrderIds.map((id, index) => [id, index]));
		return [...devices].sort((a, b) => {
			var _orderMap$get, _orderMap$get2;
			return ((_orderMap$get = orderMap.get(a.id)) !== null && _orderMap$get !== void 0 ? _orderMap$get : Number.MAX_SAFE_INTEGER) - ((_orderMap$get2 = orderMap.get(b.id)) !== null && _orderMap$get2 !== void 0 ? _orderMap$get2 : Number.MAX_SAFE_INTEGER);
		}).map(toDeviceRow);
	}, [
		deviceOrderIds,
		devices,
		toDeviceRow
	]);
	const structureOptions = useMemo(() => {
		const structures = /* @__PURE__ */ new Set();
		orderedRows.forEach((item) => {
			if (item.structure) structures.add(item.structure);
		});
		return Array.from(structures).map((structure) => ({
			labelKey: `pisell2.saas.device-planning.structure.${structure}`,
			value: structure
		}));
	}, [orderedRows]);
	/** 表格数据是客户端排序、搜索、型号和结构筛选后的 DeviceRow 列表。 */
	const tableData = useMemo(() => {
		const keyword = normalizeText(search);
		return orderedRows.filter((item) => {
			const matchesKeyword = keyword ? normalizeText(item.name).includes(keyword) : true;
			const matchesType = typeFilter ? item.modelCode === typeFilter : true;
			const matchesStructure = structureFilter ? item.structure === structureFilter : true;
			return matchesKeyword && matchesType && matchesStructure;
		});
	}, [
		orderedRows,
		search,
		structureFilter,
		typeFilter
	]);
	/** 切换工作区或设备种类时重置筛选和页码。 */
	const resetDeviceView = () => {
		setSearch("");
		setTypeFilter(void 0);
		setStructureFilter(void 0);
		setPage(1);
	};
	/** 刷新当前工作区 + 当前 kind 的设备列表。 */
	const reloadDevices = () => {
		if (!selectedWorkAreaId) return;
		deviceRequest.run(getDeviceListParams());
	};
	/** 刷新设备列表并返回最新设备数组，创建后打开详情时会用到。 */
	const reloadDevicesAsync = () => {
		if (!selectedWorkAreaId) return Promise.resolve(EMPTY_DEVICES);
		return deviceRequest.runAsync(getDeviceListParams());
	};
	return {
		search,
		typeFilter,
		structureFilter,
		page,
		pageSize,
		devices,
		tableData,
		structureOptions,
		deviceRequest,
		createDeviceRequest,
		updateDeviceRequest,
		removeDeviceRequest,
		setSearch,
		setTypeFilter,
		setStructureFilter,
		setPage,
		setPageSize,
		resetDeviceView,
		reloadDevices,
		reloadDevicesAsync,
		toDeviceRow,
		handleDeviceSort: function() {
			var _ref = _asyncToGenerator(function* (orderedRows) {
				const ids = orderedRows.map((item) => item.id);
				setDeviceOrderIds(ids);
				try {
					yield sortDeviceRequest.runAsync(ids);
					reloadDevices();
				} catch (e) {
					reloadDevices();
				}
			});
			return function handleDeviceSort(_x) {
				return _ref.apply(this, arguments);
			};
		}()
	};
};
//#endregion
export { useDeviceList };
