const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_useLocale = require("../../../hooks/useLocale.js");
const require_index = require("../../../utils/index.js");
const require_serve = require("./serve.js");
const require_hooks = require("./hooks.js");
const require_locales = require("./locales.js");
const require_constants = require("./constants.js");
const require_index$1 = require("./components/WorkAreaList/index.js");
const require_index$2 = require("./components/DeviceTable/index.js");
const require_types = require("./types.js");
const require_index$3 = require("./components/AddDeviceModal/index.js");
const require_index$4 = require("./components/DeviceDetailDrawer/index.js");
const require_index$5 = require("./components/EditDeviceModal/index.js");
const require_index$6 = require("./components/DeleteDeviceModal/index.js");
const require_index$7 = require("./components/WorkAreaModal/index.js");
const require_index$8 = require("./components/DeleteWorkAreaModal/index.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
let _dnd_kit_sortable = require("@dnd-kit/sortable");
require("./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 = require_useEngineContext.default();
	const locale = require_useLocale.default();
	_pisell_utils.locales.init(require_locales.default, locale || "en");
	const getText = _pisell_utils.locales.getText;
	const translation = require_hooks.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] = (0, react.useState)([]);
	const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, react.useState)();
	const [activeKind, setActiveKind] = (0, react.useState)("smart");
	const [search, setSearch] = (0, react.useState)("");
	const [typeFilter, setTypeFilter] = (0, react.useState)(void 0);
	const [modelCacheByKind, setModelCacheByKind] = (0, react.useState)({});
	const modelCacheByKindRef = (0, react.useRef)({});
	const [deviceOrderIds, setDeviceOrderIds] = (0, react.useState)([]);
	const requestedModelKindsRef = (0, react.useRef)(/* @__PURE__ */ new Set());
	const [page, setPage] = (0, react.useState)(1);
	const [pageSize, setPageSize] = (0, react.useState)(10);
	const [addDeviceOpen, setAddDeviceOpen] = (0, react.useState)(false);
	const [detailOpen, setDetailOpen] = (0, react.useState)(false);
	const [selectedDevice, setSelectedDevice] = (0, react.useState)();
	const [editDeviceOpen, setEditDeviceOpen] = (0, react.useState)(false);
	const [deleteDeviceOpen, setDeleteDeviceOpen] = (0, react.useState)(false);
	const [workAreaModalOpen, setWorkAreaModalOpen] = (0, react.useState)(false);
	const [workAreaModalMode, setWorkAreaModalMode] = (0, react.useState)("create");
	const [editingWorkArea, setEditingWorkArea] = (0, react.useState)();
	const [deleteModalOpen, setDeleteModalOpen] = (0, react.useState)(false);
	const [deleteRecord, setDeleteRecord] = (0, react.useState)();
	const [deleteCounts, setDeleteCounts] = (0, react.useState)({
		smart: 0,
		dumb: 0,
		integrated: 0
	});
	(0, react.useEffect)(() => {
		if (utils === null || utils === void 0 ? void 0 : utils.request) require_index.request.setRequest(utils.request);
	}, [utils === null || utils === void 0 ? void 0 : utils.request]);
	const workAreaRequest = (0, ahooks.useRequest)(require_serve.getWorkAreas, { onSuccess: (list) => {
		setWorkAreas(require_constants.sortWorkAreaList(list));
	} });
	const saveRequest = (0, ahooks.useRequest)((payload) => workAreaModalMode === "create" ? require_serve.createWorkArea(payload) : require_serve.updateWorkArea((editingWorkArea === null || editingWorkArea === void 0 ? void 0 : editingWorkArea.id) || "", payload), { manual: true });
	const sortRequest = (0, ahooks.useRequest)(require_serve.sortWorkAreas, { manual: true });
	const deviceRequest = (0, ahooks.useRequest)(require_serve.getDevices, { manual: true });
	const createDeviceRequest = (0, ahooks.useRequest)(require_serve.createDevice, { manual: true });
	const updateDeviceRequest = (0, ahooks.useRequest)((params) => require_serve.updateDevice(params.id, params.payload), { manual: true });
	const removeDeviceRequest = (0, ahooks.useRequest)(require_serve.deleteDevice, { manual: true });
	const sortDeviceRequest = (0, ahooks.useRequest)(require_serve.sortDevices, { manual: true });
	const getWorkAreaDetailRequest = (0, ahooks.useRequest)(require_serve.getWorkAreaDetail, { manual: true });
	const deleteRequest = (0, ahooks.useRequest)(require_serve.deleteWorkArea, { manual: true });
	(0, react.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]);
	(0, react.useEffect)(() => {
		if (!selectedWorkAreaId) return;
		deviceRequest.run({
			workarea_id: selectedWorkAreaId,
			type_kind: activeKind,
			with: [
				"type",
				"model",
				"workarea"
			]
		});
	}, [selectedWorkAreaId, activeKind]);
	(0, react.useEffect)(() => {
		if (!selectedWorkAreaId) return;
		if (modelCacheByKindRef.current[activeKind]) return;
		if (requestedModelKindsRef.current.has(activeKind)) return;
		requestedModelKindsRef.current.add(activeKind);
		require_serve.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, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, model), {}, { type }));
				});
			});
			const models = Array.from(modelMap.values());
			modelCacheByKindRef.current = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, modelCacheByKindRef.current), {}, { [activeKind]: models });
			setModelCacheByKind(modelCacheByKindRef.current);
		}).catch(() => {
			modelCacheByKindRef.current = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, modelCacheByKindRef.current), {}, { [activeKind]: [] });
			setModelCacheByKind(modelCacheByKindRef.current);
		});
	}, [activeKind, selectedWorkAreaId]);
	const selectedWorkArea = (0, react.useMemo)(() => workAreas.find((item) => item.id === selectedWorkAreaId), [selectedWorkAreaId, workAreas]);
	const devices = deviceRequest.data || EMPTY_DEVICES;
	(0, react.useEffect)(() => {
		const nextIds = devices.map((item) => item.id);
		setDeviceOrderIds((prev) => isSameIds(prev, nextIds) ? prev : nextIds);
	}, [devices]);
	const typeOptions = (0, react.useMemo)(() => {
		return (modelCacheByKind[activeKind] || []).map((model) => ({
			label: translation(model.name) || model.code,
			value: model.code
		}));
	}, [
		activeKind,
		modelCacheByKind,
		translation
	]);
	const profileNameMap = (0, react.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 = (0, react.useMemo)(() => {
		const keyword = require_constants.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 ? require_constants.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 = require_asyncToGenerator._asyncToGenerator(function* (selectedId) {
			const sorted = require_constants.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 = require_asyncToGenerator._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 = (0, _dnd_kit_sortable.arrayMove)(workAreas, oldIndex, newIndex).map((item, index) => require_objectSpread2._objectSpread2(require_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 = require_asyncToGenerator._asyncToGenerator(function* (payload) {
			try {
				const saved = yield saveRequest.runAsync(payload);
				(0, _pisell_materials.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 = require_asyncToGenerator._asyncToGenerator(function* () {
			if (!deleteRecord) return;
			try {
				yield deleteRequest.runAsync(deleteRecord.id);
				(0, _pisell_materials.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 = require_asyncToGenerator._asyncToGenerator(function* (payload) {
			try {
				yield createDeviceRequest.runAsync(payload);
				(0, _pisell_materials.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 = require_asyncToGenerator._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 = require_asyncToGenerator._asyncToGenerator(function* (id, payload) {
			try {
				yield updateDeviceRequest.runAsync({
					id,
					payload
				});
				(0, _pisell_materials.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 = require_asyncToGenerator._asyncToGenerator(function* () {
			if (!selectedDevice) return;
			try {
				yield removeDeviceRequest.runAsync(selectedDevice.id);
				(0, _pisell_materials.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.default.createElement("div", {
		className: (0, classnames.default)("saas-device-planning", className),
		style
	}, /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		loading: workAreaRequest.loading,
		workAreas,
		selectedWorkAreaId,
		getText,
		translation,
		onCreate: openCreateModal,
		onSelect: (id) => {
			setSelectedWorkAreaId(id);
			resetDeviceView();
		},
		onEdit: openEditModal,
		onDelete: openDeleteModal,
		onSortEnd: handleDragEnd
	}), /* @__PURE__ */ react.default.createElement("main", { className: "saas-device-planning__content" }, showWorkAreaLoading ? /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ react.default.createElement(antd.Spin, null)) : showEmptyWorkArea ? /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Empty, {
		image: _pisell_materials.Empty.PRESENTED_IMAGE_SIMPLE,
		description: getText("pisell2.saas.device-planning.empty.workarea-first")
	})) : /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-planning__page-header" }, /* @__PURE__ */ react.default.createElement("div", null, /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-planning__title" }, selectedWorkArea ? translation(selectedWorkArea.name) : "-"), (selectedWorkArea === null || selectedWorkArea === void 0 ? void 0 : selectedWorkArea.description) ? /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-planning__subtitle" }, translation(selectedWorkArea.description)) : null)), /* @__PURE__ */ react.default.createElement(antd.Tabs, {
		activeKey: activeKind,
		onChange: (key) => {
			setActiveKind(key);
			resetDeviceView();
		},
		items: require_types.DEVICE_KIND_OPTIONS.map((kind) => ({
			key: kind,
			label: getText(require_constants.DEVICE_KIND_LABEL_KEY[kind])
		}))
	}), /* @__PURE__ */ react.default.createElement(require_index$2.default, {
		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.default.createElement(require_index$4.default, {
		open: detailOpen,
		record: selectedDevice,
		getText,
		translation,
		onClose: () => setDetailOpen(false),
		onEdit: () => setEditDeviceOpen(true),
		onDelete: () => setDeleteDeviceOpen(true)
	}), /* @__PURE__ */ react.default.createElement(require_index$5.default, {
		open: editDeviceOpen,
		record: selectedDevice,
		workAreas,
		models: modelCacheByKind[activeKind] || [],
		submitting: updateDeviceRequest.loading,
		getText,
		translation,
		onCancel: () => setEditDeviceOpen(false),
		onSubmit: handleUpdateDevice
	}), /* @__PURE__ */ react.default.createElement(require_index$6.default, {
		open: deleteDeviceOpen,
		record: selectedDevice,
		submitting: removeDeviceRequest.loading,
		getText,
		onCancel: () => setDeleteDeviceOpen(false),
		onConfirm: handleDeleteDevice
	}), /* @__PURE__ */ react.default.createElement(require_index$3.default, {
		open: addDeviceOpen,
		activeKind,
		models: modelCacheByKind[activeKind] || [],
		workAreaId: selectedWorkAreaId,
		submitting: createDeviceRequest.loading,
		getText,
		translation,
		onClose: () => setAddDeviceOpen(false),
		onSubmit: handleCreateDevice
	}), /* @__PURE__ */ react.default.createElement(require_index$7.default, {
		open: workAreaModalOpen,
		mode: workAreaModalMode,
		record: editingWorkArea,
		submitting: saveRequest.loading,
		getText,
		onCancel: () => {
			setWorkAreaModalOpen(false);
			setEditingWorkArea(void 0);
		},
		onSubmit: handleSaveWorkArea
	}), /* @__PURE__ */ react.default.createElement(require_index$8.default, {
		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
exports.default = SaasDevicePlanning;
