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 { sortWorkAreaList } from "../constants.js";
import { createWorkArea, deleteWorkArea, getWorkAreaDetail, getWorkAreas, sortWorkAreas, updateWorkArea } from "../serve.js";
import { getDeleteWorkAreaCounts } from "../utils.js";
import { useEffect, useState } from "react";
import { PisellToast } from "@pisell/materials";
import { useRequest } from "ahooks";
import { arrayMove } from "@dnd-kit/sortable";
//#region src/plus/saasDevice/devicePlanning/hooks/useWorkAreas.ts
const EMPTY_COUNTS = {
	smart: 0,
	dumb: 0,
	integrated: 0
};
/** 管理工作区列表、选中工作区、工作区增删改和拖拽排序。 */
const useWorkAreas = ({ getText, workAreaModalMode, editingWorkArea, closeWorkAreaModal }) => {
	const [workAreas, setWorkAreas] = useState([]);
	const [selectedWorkAreaId, setSelectedWorkAreaId] = useState();
	const [deleteModalOpen, setDeleteModalOpen] = useState(false);
	const [deleteRecord, setDeleteRecord] = useState();
	const [deleteCounts, setDeleteCounts] = useState(EMPTY_COUNTS);
	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 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]);
	const showWorkAreaLoading = workAreaRequest.loading && workAreas.length === 0;
	const showEmptyWorkArea = !workAreaRequest.loading && workAreas.length === 0;
	const selectedWorkArea = workAreas.find((item) => item.id === selectedWorkAreaId);
	/** 重新加载工作区，并可在刷新后指定选中的工作区。 */
	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 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 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
				});
				closeWorkAreaModal();
				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(EMPTY_COUNTS);
		setDeleteModalOpen(true);
		getWorkAreaDetailRequest.runAsync({
			id: record.id,
			relation_count: [
				"smartDevices",
				"dumbDevices",
				"integratedDevices"
			]
		}).then((res) => setDeleteCounts(getDeleteWorkAreaCounts(res))).catch(() => setDeleteCounts(EMPTY_COUNTS));
	};
	/** 关闭删除工作区弹窗并清理计数，避免下次打开闪现旧数据。 */
	const closeDeleteModal = () => {
		setDeleteModalOpen(false);
		setDeleteRecord(void 0);
		setDeleteCounts(EMPTY_COUNTS);
	};
	return {
		workAreas,
		selectedWorkArea,
		selectedWorkAreaId,
		showWorkAreaLoading,
		showEmptyWorkArea,
		deleteModalOpen,
		deleteRecord,
		deleteCounts,
		workAreaRequest,
		saveRequest,
		getWorkAreaDetailRequest,
		deleteRequest,
		setSelectedWorkAreaId,
		reloadWorkAreas,
		handleDragEnd,
		handleSaveWorkArea,
		openDeleteModal,
		closeDeleteModal,
		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
					});
					closeDeleteModal();
					yield reloadWorkAreas();
				} catch (e) {}
			});
			return function handleConfirmDelete() {
				return _ref4.apply(this, arguments);
			};
		}()
	};
};
//#endregion
export { useWorkAreas };
