var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/devicePlanning/modules/workAreas/hooks/useWorkAreas.ts
var useWorkAreas_exports = {};
__export(useWorkAreas_exports, {
  useWorkAreas: () => useWorkAreas
});
module.exports = __toCommonJS(useWorkAreas_exports);
var import_react = require("react");
var import_materials = require("@pisell/materials");
var import_sortable = require("@dnd-kit/sortable");
var import_ahooks = require("ahooks");
var import_model = require("../../../model");
var import_api = require("../../../api");
var import_model2 = require("../../../model");
var EMPTY_COUNTS = {
  smart: 0,
  dumb: 0,
  integrated: 0
};
var useWorkAreas = ({
  getText,
  workAreaModalMode,
  editingWorkArea,
  closeWorkAreaModal
}) => {
  const [workAreas, setWorkAreas] = (0, import_react.useState)([]);
  const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, import_react.useState)();
  const [deleteModalOpen, setDeleteModalOpen] = (0, import_react.useState)(false);
  const [deleteRecord, setDeleteRecord] = (0, import_react.useState)();
  const [deleteCounts, setDeleteCounts] = (0, import_react.useState)(EMPTY_COUNTS);
  const workAreaRequest = (0, import_ahooks.useRequest)(import_api.getWorkAreas, {
    onSuccess: (list) => {
      setWorkAreas((0, import_model.sortWorkAreaList)(list));
    }
  });
  const saveRequest = (0, import_ahooks.useRequest)(
    (payload) => workAreaModalMode === "create" ? (0, import_api.createWorkArea)(payload) : (0, import_api.updateWorkArea)((editingWorkArea == null ? void 0 : editingWorkArea.id) || "", payload),
    { manual: true }
  );
  const sortRequest = (0, import_ahooks.useRequest)(import_api.sortWorkAreas, { manual: true });
  const getWorkAreaDetailRequest = (0, import_ahooks.useRequest)(import_api.getWorkAreaDetail, {
    manual: true
  });
  const deleteRequest = (0, import_ahooks.useRequest)(import_api.deleteWorkArea, { manual: true });
  (0, import_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]);
  const showWorkAreaLoading = workAreaRequest.loading && workAreas.length === 0;
  const showEmptyWorkArea = !workAreaRequest.loading && workAreas.length === 0;
  const selectedWorkArea = workAreas.find((item) => item.id === selectedWorkAreaId);
  const reloadWorkAreas = async (selectedId) => {
    const list = await workAreaRequest.runAsync();
    const sorted = (0, import_model.sortWorkAreaList)(list);
    setWorkAreas(sorted);
    if (selectedId) {
      setSelectedWorkAreaId(selectedId);
    }
    return sorted;
  };
  const handleDragEnd = async (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, import_sortable.arrayMove)(workAreas, oldIndex, newIndex).map(
      (item, index) => ({
        ...item,
        sort: index
      })
    );
    setWorkAreas(next);
    try {
      await sortRequest.runAsync(next.map((item) => item.id));
    } catch (e) {
      reloadWorkAreas();
    }
  };
  const handleSaveWorkArea = async (payload) => {
    try {
      const saved = await saveRequest.runAsync(payload);
      (0, import_materials.PisellToast)({
        content: getText(
          workAreaModalMode === "create" ? "pisell2.saas.device-planning.message.create-success" : "pisell2.saas.device-planning.message.update-success"
        ),
        duration: 2
      });
      closeWorkAreaModal();
      await reloadWorkAreas((saved == null ? void 0 : saved.id) || (editingWorkArea == null ? void 0 : editingWorkArea.id));
    } catch (e) {
    }
  };
  const openDeleteModal = (record) => {
    setDeleteRecord(record);
    setDeleteCounts(EMPTY_COUNTS);
    setDeleteModalOpen(true);
    getWorkAreaDetailRequest.runAsync({
      id: record.id,
      relation_count: ["smartDevices", "dumbDevices", "integratedDevices"]
    }).then((res) => setDeleteCounts((0, import_model2.getDeleteWorkAreaCounts)(res))).catch(() => setDeleteCounts(EMPTY_COUNTS));
  };
  const closeDeleteModal = () => {
    setDeleteModalOpen(false);
    setDeleteRecord(void 0);
    setDeleteCounts(EMPTY_COUNTS);
  };
  const handleConfirmDelete = async () => {
    if (!deleteRecord) return;
    try {
      await deleteRequest.runAsync(deleteRecord.id);
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.message.delete-success"),
        duration: 2
      });
      closeDeleteModal();
      await reloadWorkAreas();
    } catch (e) {
    }
  };
  return {
    workAreas,
    selectedWorkArea,
    selectedWorkAreaId,
    showWorkAreaLoading,
    showEmptyWorkArea,
    deleteModalOpen,
    deleteRecord,
    deleteCounts,
    workAreaRequest,
    saveRequest,
    getWorkAreaDetailRequest,
    deleteRequest,
    setSelectedWorkAreaId,
    reloadWorkAreas,
    handleDragEnd,
    handleSaveWorkArea,
    openDeleteModal,
    closeDeleteModal,
    handleConfirmDelete
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useWorkAreas
});
