import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import useLocale from "../../../hooks/useLocale.js";
import { request } from "../../../utils/index.js";
import { createDevice, createWorkArea, deleteDevice, deleteWorkArea, getDeviceTypes, getDevices, getWorkAreaDetail, getWorkAreas, sortDevices, sortWorkAreas, updateDevice, updateWorkArea } from "./serve.js";
import { useTranslation } from "./hooks.js";
import locales_default from "./locales.js";
import { DEVICE_KIND_LABEL_KEY, normalizeText, sortWorkAreaList } from "./constants.js";
import WorkAreaList from "./components/WorkAreaList/index.js";
import DeviceTable from "./components/DeviceTable/index.js";
import { DEVICE_KIND_OPTIONS } from "./types.js";
import AddDeviceModal from "./components/AddDeviceModal/index.js";
import DeviceDetailDrawer from "./components/DeviceDetailDrawer/index.js";
import EditDeviceModal from "./components/EditDeviceModal/index.js";
import DeleteDeviceModal from "./components/DeleteDeviceModal/index.js";
import WorkAreaModal from "./components/WorkAreaModal/index.js";
import DeleteWorkAreaModal from "./components/DeleteWorkAreaModal/index.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Spin, Tabs } from "antd";
import { locales } from "@pisell/utils";
import { Empty as Empty$1, PisellToast } from "@pisell/materials";
import classNames from "classnames";
import { useRequest } from "ahooks";
import { arrayMove } from "@dnd-kit/sortable";
import "./index.less";
//#region src/plus/saasDevice/devicePlanning/index.tsx
const EMPTY_DEVICES = [];
const isSameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
const SaasDevicePlanning = ({ className, style }) => {
	var _context$appHelper;
	const context = useEngineContext();
	const locale = useLocale();
	locales.init(locales_default, locale || "en");
	const getText = locales.getText;
	const translation = useTranslation();
	const utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const [workAreas, setWorkAreas] = useState([]);
	const [selectedWorkAreaId, setSelectedWorkAreaId] = useState();
	const [activeKind, setActiveKind] = useState("smart");
	const [search, setSearch] = useState("");
	const [typeFilter, setTypeFilter] = useState(void 0);
	const [modelCacheByKind, setModelCacheByKind] = useState({});
	const modelCacheByKindRef = useRef({});
	const [deviceOrderIds, setDeviceOrderIds] = useState([]);
	const requestedModelKindsRef = useRef(/* @__PURE__ */ new Set());
	const [page, setPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [addDeviceOpen, setAddDeviceOpen] = useState(false);
	const [detailOpen, setDetailOpen] = useState(false);
	const [selectedDevice, setSelectedDevice] = useState();
	const [editDeviceOpen, setEditDeviceOpen] = useState(false);
	const [deleteDeviceOpen, setDeleteDeviceOpen] = useState(false);
	const [workAreaModalOpen, setWorkAreaModalOpen] = useState(false);
	const [workAreaModalMode, setWorkAreaModalMode] = useState("create");
	const [editingWorkArea, setEditingWorkArea] = useState();
	const [deleteModalOpen, setDeleteModalOpen] = useState(false);
	const [deleteRecord, setDeleteRecord] = useState();
	const [deleteCounts, setDeleteCounts] = useState({
		smart: 0,
		dumb: 0,
		integrated: 0
	});
	useEffect(() => {
		if (utils === null || utils === void 0 ? void 0 : utils.request) request.setRequest(utils.request);
	}, [utils === null || utils === void 0 ? void 0 : utils.request]);
	const workAreaRequest = useRequest(getWorkAreas, { onSuccess: (list) => {
		setWorkAreas(sortWorkAreaList(list));
	} });
	const saveRequest = useRequest((payload) => workAreaModalMode === "create" ? createWorkArea(payload) : updateWorkArea((editingWorkArea === null || editingWorkArea === void 0 ? void 0 : editingWorkArea.id) || "", payload), { manual: true });
	const sortRequest = useRequest(sortWorkAreas, { manual: true });
	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 getWorkAreaDetailRequest = useRequest(getWorkAreaDetail, { manual: true });
	const deleteRequest = useRequest(deleteWorkArea, { manual: true });
	useEffect(() => {
		if (!workAreas.length) {
			setSelectedWorkAreaId(void 0);
			return;
		}
		const exists = workAreas.some((item) => item.id === selectedWorkAreaId);
		if (!selectedWorkAreaId || !exists) setSelectedWorkAreaId(workAreas[0].id);
	}, [selectedWorkAreaId, workAreas]);
	useEffect(() => {
		if (!selectedWorkAreaId) return;
		deviceRequest.run({
			workarea_id: selectedWorkAreaId,
			type_kind: activeKind,
			with: [
				"type",
				"model",
				"workarea"
			]
		});
	}, [selectedWorkAreaId, activeKind]);
	useEffect(() => {
		if (!selectedWorkAreaId) return;
		if (modelCacheByKindRef.current[activeKind]) return;
		if (requestedModelKindsRef.current.has(activeKind)) return;
		requestedModelKindsRef.current.add(activeKind);
		getDeviceTypes({
			kind: activeKind,
			with: ["activeModels", "activeModels.activeProfiles"]
		}).then((types) => {
			const modelMap = /* @__PURE__ */ new Map();
			types.forEach((type) => {
				(type.active_models || []).forEach((model) => {
					if (!modelMap.has(model.code)) modelMap.set(model.code, _objectSpread2(_objectSpread2({}, model), {}, { type }));
				});
			});
			const models = Array.from(modelMap.values());
			modelCacheByKindRef.current = _objectSpread2(_objectSpread2({}, modelCacheByKindRef.current), {}, { [activeKind]: models });
			setModelCacheByKind(modelCacheByKindRef.current);
		}).catch(() => {
			modelCacheByKindRef.current = _objectSpread2(_objectSpread2({}, modelCacheByKindRef.current), {}, { [activeKind]: [] });
			setModelCacheByKind(modelCacheByKindRef.current);
		});
	}, [activeKind, selectedWorkAreaId]);
	const selectedWorkArea = useMemo(() => workAreas.find((item) => item.id === selectedWorkAreaId), [selectedWorkAreaId, workAreas]);
	const devices = deviceRequest.data || EMPTY_DEVICES;
	useEffect(() => {
		const nextIds = devices.map((item) => item.id);
		setDeviceOrderIds((prev) => isSameIds(prev, nextIds) ? prev : nextIds);
	}, [devices]);
	const typeOptions = useMemo(() => {
		return (modelCacheByKind[activeKind] || []).map((model) => ({
			label: translation(model.name) || model.code,
			value: model.code
		}));
	}, [
		activeKind,
		modelCacheByKind,
		translation
	]);
	const profileNameMap = useMemo(() => {
		const map = /* @__PURE__ */ new Map();
		Object.values(modelCacheByKind).forEach((models) => {
			(models || []).forEach((model) => {
				(model.active_profiles || []).forEach((profile) => {
					map.set(profile.id, translation(profile.name) || String(profile.id));
				});
			});
		});
		devices.forEach((device) => {
			var _device$profile;
			if ((_device$profile = device.profile) === null || _device$profile === void 0 ? void 0 : _device$profile.id) map.set(device.profile.id, translation(device.profile.name) || String(device.profile.id));
		});
		return map;
	}, [
		devices,
		modelCacheByKind,
		translation
	]);
	const tableData = useMemo(() => {
		const keyword = normalizeText(search);
		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((item) => {
			var _item$type, _item$model, _item$profile;
			const name = translation(item.name);
			const typeName = translation((_item$type = item.type) === null || _item$type === void 0 ? void 0 : _item$type.name) || item.type_code;
			const modelName = translation((_item$model = item.model) === null || _item$model === void 0 ? void 0 : _item$model.name) || item.model_code;
			const link = item.link || "unlinked";
			const profileName = translation((_item$profile = item.profile) === null || _item$profile === void 0 ? void 0 : _item$profile.name) || (item.profile_id ? profileNameMap.get(item.profile_id) : "") || (item.profile_id ? String(item.profile_id) : "-");
			return {
				id: item.id,
				name,
				typeName,
				modelName,
				profileName,
				link,
				status: link === "linked" ? item.status || "offline" : "unknown",
				typeCode: item.type_code,
				modelCode: item.model_code,
				_raw: item
			};
		}).filter((item) => {
			const matchesKeyword = keyword ? normalizeText(item.name).includes(keyword) : true;
			const matchesType = typeFilter ? item.modelCode === typeFilter : true;
			return matchesKeyword && matchesType;
		});
	}, [
		deviceOrderIds,
		devices,
		profileNameMap,
		search,
		translation,
		typeFilter
	]);
	const showWorkAreaLoading = workAreaRequest.loading && workAreas.length === 0;
	const showEmptyWorkArea = !workAreaRequest.loading && workAreas.length === 0;
	const reloadWorkAreas = function() {
		var _ref = _asyncToGenerator(function* (selectedId) {
			const sorted = sortWorkAreaList(yield workAreaRequest.runAsync());
			setWorkAreas(sorted);
			if (selectedId) setSelectedWorkAreaId(selectedId);
			return sorted;
		});
		return function reloadWorkAreas(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const resetDeviceView = () => {
		setSearch("");
		setTypeFilter(void 0);
		setPage(1);
	};
	const reloadDevices = () => {
		if (!selectedWorkAreaId) return;
		deviceRequest.run({
			workarea_id: selectedWorkAreaId,
			type_kind: activeKind,
			with: [
				"type",
				"model",
				"workarea"
			]
		});
	};
	const handleDragEnd = function() {
		var _ref2 = _asyncToGenerator(function* (event) {
			const { active, over } = event;
			if (!over || active.id === over.id) return;
			const oldIndex = workAreas.findIndex((item) => item.id === active.id);
			const newIndex = workAreas.findIndex((item) => item.id === over.id);
			if (oldIndex < 0 || newIndex < 0) return;
			const next = arrayMove(workAreas, oldIndex, newIndex).map((item, index) => _objectSpread2(_objectSpread2({}, item), {}, { sort: index }));
			setWorkAreas(next);
			try {
				yield sortRequest.runAsync(next.map((item) => item.id));
			} catch (e) {
				reloadWorkAreas();
			}
		});
		return function handleDragEnd(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const openCreateModal = () => {
		setWorkAreaModalMode("create");
		setEditingWorkArea(void 0);
		setWorkAreaModalOpen(true);
	};
	const openEditModal = (record) => {
		setWorkAreaModalMode("edit");
		setEditingWorkArea(record);
		setWorkAreaModalOpen(true);
	};
	const handleSaveWorkArea = function() {
		var _ref3 = _asyncToGenerator(function* (payload) {
			try {
				const saved = yield saveRequest.runAsync(payload);
				PisellToast({
					content: getText(workAreaModalMode === "create" ? "pisell2.saas.device-planning.message.create-success" : "pisell2.saas.device-planning.message.update-success"),
					duration: 2
				});
				setWorkAreaModalOpen(false);
				setEditingWorkArea(void 0);
				yield reloadWorkAreas((saved === null || saved === void 0 ? void 0 : saved.id) || (editingWorkArea === null || editingWorkArea === void 0 ? void 0 : editingWorkArea.id));
			} catch (e) {}
		});
		return function handleSaveWorkArea(_x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	const openDeleteModal = (record) => {
		setDeleteRecord(record);
		setDeleteCounts({
			smart: 0,
			dumb: 0,
			integrated: 0
		});
		setDeleteModalOpen(true);
		getWorkAreaDetailRequest.runAsync({
			id: record.id,
			relation_count: [
				"smartDevices",
				"dumbDevices",
				"integratedDevices"
			]
		}).then((res) => {
			var _res$data;
			console.log("xue_detail", res);
			const _workArea = res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data[0];
			setDeleteCounts({
				smart: (_workArea === null || _workArea === void 0 ? void 0 : _workArea.smart_devices_count) || 0,
				dumb: (_workArea === null || _workArea === void 0 ? void 0 : _workArea.dumb_devices_count) || 0,
				integrated: (_workArea === null || _workArea === void 0 ? void 0 : _workArea.integrated_devices_count) || 0
			});
		}).catch(() => setDeleteCounts({
			smart: 0,
			dumb: 0,
			integrated: 0
		}));
	};
	const handleConfirmDelete = function() {
		var _ref4 = _asyncToGenerator(function* () {
			if (!deleteRecord) return;
			try {
				yield deleteRequest.runAsync(deleteRecord.id);
				PisellToast({
					content: getText("pisell2.saas.device-planning.message.delete-success"),
					duration: 2
				});
				setDeleteModalOpen(false);
				setDeleteRecord(void 0);
				yield reloadWorkAreas();
			} catch (e) {}
		});
		return function handleConfirmDelete() {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleCreateDevice = function() {
		var _ref5 = _asyncToGenerator(function* (payload) {
			try {
				yield createDeviceRequest.runAsync(payload);
				PisellToast({
					content: getText("pisell2.saas.device-planning.add.create-success"),
					duration: 2
				});
				setAddDeviceOpen(false);
				setPage(1);
				reloadDevices();
			} catch (e) {}
		});
		return function handleCreateDevice(_x4) {
			return _ref5.apply(this, arguments);
		};
	}();
	const handleDeviceSort = function() {
		var _ref6 = _asyncToGenerator(function* (orderedRows) {
			const ids = orderedRows.map((item) => item.id);
			setDeviceOrderIds(ids);
			try {
				yield sortDeviceRequest.runAsync(ids);
				reloadDevices();
			} catch (e) {
				reloadDevices();
			}
		});
		return function handleDeviceSort(_x5) {
			return _ref6.apply(this, arguments);
		};
	}();
	const handleUpdateDevice = function() {
		var _ref7 = _asyncToGenerator(function* (id, payload) {
			try {
				yield updateDeviceRequest.runAsync({
					id,
					payload
				});
				PisellToast({
					content: getText("pisell2.saas.device-planning.edit.success"),
					duration: 2
				});
				setEditDeviceOpen(false);
				setDetailOpen(false);
				setSelectedDevice(void 0);
				reloadDevices();
			} catch (e) {}
		});
		return function handleUpdateDevice(_x6, _x7) {
			return _ref7.apply(this, arguments);
		};
	}();
	const handleDeleteDevice = function() {
		var _ref8 = _asyncToGenerator(function* () {
			if (!selectedDevice) return;
			try {
				yield removeDeviceRequest.runAsync(selectedDevice.id);
				PisellToast({
					content: getText("pisell2.saas.device-planning.delete-device.success"),
					duration: 2
				});
				setDeleteDeviceOpen(false);
				setDetailOpen(false);
				setSelectedDevice(void 0);
				reloadDevices();
			} catch (e) {}
		});
		return function handleDeleteDevice() {
			return _ref8.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ React.createElement("div", {
		className: classNames("saas-device-planning", className),
		style
	}, /* @__PURE__ */ React.createElement(WorkAreaList, {
		loading: workAreaRequest.loading,
		workAreas,
		selectedWorkAreaId,
		getText,
		translation,
		onCreate: openCreateModal,
		onSelect: (id) => {
			setSelectedWorkAreaId(id);
			resetDeviceView();
		},
		onEdit: openEditModal,
		onDelete: openDeleteModal,
		onSortEnd: handleDragEnd
	}), /* @__PURE__ */ React.createElement("main", { className: "saas-device-planning__content" }, showWorkAreaLoading ? /* @__PURE__ */ React.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ React.createElement(Spin, null)) : showEmptyWorkArea ? /* @__PURE__ */ React.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ React.createElement(Empty$1, {
		image: Empty$1.PRESENTED_IMAGE_SIMPLE,
		description: getText("pisell2.saas.device-planning.empty.workarea-first")
	})) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "saas-device-planning__page-header" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "saas-device-planning__title" }, selectedWorkArea ? translation(selectedWorkArea.name) : "-"), (selectedWorkArea === null || selectedWorkArea === void 0 ? void 0 : selectedWorkArea.description) ? /* @__PURE__ */ React.createElement("div", { className: "saas-device-planning__subtitle" }, translation(selectedWorkArea.description)) : null)), /* @__PURE__ */ React.createElement(Tabs, {
		activeKey: activeKind,
		onChange: (key) => {
			setActiveKind(key);
			resetDeviceView();
		},
		items: DEVICE_KIND_OPTIONS.map((kind) => ({
			key: kind,
			label: getText(DEVICE_KIND_LABEL_KEY[kind])
		}))
	}), /* @__PURE__ */ React.createElement(DeviceTable, {
		activeKind,
		data: tableData,
		loading: deviceRequest.loading,
		search,
		typeFilter,
		typeOptions,
		page,
		pageSize,
		getText,
		onSearchChange: (value) => {
			setSearch(value);
			setPage(1);
		},
		onTypeFilterChange: (value) => {
			setTypeFilter(value);
			setPage(1);
		},
		onPageChange: (nextPage, nextPageSize) => {
			setPage(nextPage);
			setPageSize(nextPageSize);
		},
		onAdd: () => setAddDeviceOpen(true),
		onSortChange: handleDeviceSort,
		onRowClick: (record) => {
			setSelectedDevice(record);
			setDetailOpen(true);
		}
	}))), /* @__PURE__ */ React.createElement(DeviceDetailDrawer, {
		open: detailOpen,
		record: selectedDevice,
		getText,
		translation,
		onClose: () => setDetailOpen(false),
		onEdit: () => setEditDeviceOpen(true),
		onDelete: () => setDeleteDeviceOpen(true)
	}), /* @__PURE__ */ React.createElement(EditDeviceModal, {
		open: editDeviceOpen,
		record: selectedDevice,
		workAreas,
		models: modelCacheByKind[activeKind] || [],
		submitting: updateDeviceRequest.loading,
		getText,
		translation,
		onCancel: () => setEditDeviceOpen(false),
		onSubmit: handleUpdateDevice
	}), /* @__PURE__ */ React.createElement(DeleteDeviceModal, {
		open: deleteDeviceOpen,
		record: selectedDevice,
		submitting: removeDeviceRequest.loading,
		getText,
		onCancel: () => setDeleteDeviceOpen(false),
		onConfirm: handleDeleteDevice
	}), /* @__PURE__ */ React.createElement(AddDeviceModal, {
		open: addDeviceOpen,
		activeKind,
		models: modelCacheByKind[activeKind] || [],
		workAreaId: selectedWorkAreaId,
		submitting: createDeviceRequest.loading,
		getText,
		translation,
		onClose: () => setAddDeviceOpen(false),
		onSubmit: handleCreateDevice
	}), /* @__PURE__ */ React.createElement(WorkAreaModal, {
		open: workAreaModalOpen,
		mode: workAreaModalMode,
		record: editingWorkArea,
		submitting: saveRequest.loading,
		getText,
		onCancel: () => {
			setWorkAreaModalOpen(false);
			setEditingWorkArea(void 0);
		},
		onSubmit: handleSaveWorkArea
	}), /* @__PURE__ */ React.createElement(DeleteWorkAreaModal, {
		open: deleteModalOpen,
		loading: getWorkAreaDetailRequest.loading,
		submitting: deleteRequest.loading,
		record: deleteRecord,
		counts: deleteCounts,
		translation,
		getText,
		onClose: () => {
			setDeleteModalOpen(false);
			setDeleteRecord(void 0);
			setDeleteCounts({
				smart: 0,
				dumb: 0,
				integrated: 0
			});
		},
		onConfirm: handleConfirmDelete
	}));
};
//#endregion
export { SaasDevicePlanning as default };
