var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/devicePlanning/index.tsx
var devicePlanning_exports = {};
__export(devicePlanning_exports, {
  default: () => devicePlanning_default
});
module.exports = __toCommonJS(devicePlanning_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_antd = require("antd");
var import_sortable = require("@dnd-kit/sortable");
var import_ahooks = require("ahooks");
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_useLocale = __toESM(require("../../../hooks/useLocale"));
var import_utils2 = require("../../../utils");
var import_serve = require("./serve");
var import_hooks = require("./hooks");
var import_locales = __toESM(require("./locales"));
var import_constants = require("./constants");
var import_WorkAreaList = __toESM(require("./components/WorkAreaList"));
var import_DeviceTable = __toESM(require("./components/DeviceTable"));
var import_AddDeviceModal = __toESM(require("./components/AddDeviceModal"));
var import_DeviceDetailDrawer = __toESM(require("./components/DeviceDetailDrawer"));
var import_EditDeviceModal = __toESM(require("./components/EditDeviceModal"));
var import_DeleteDeviceModal = __toESM(require("./components/DeleteDeviceModal"));
var import_WorkAreaModal = __toESM(require("./components/WorkAreaModal"));
var import_DeleteWorkAreaModal = __toESM(require("./components/DeleteWorkAreaModal"));
var import_types = require("./types");
var import_index = require("./index.less");
var EMPTY_DEVICES = [];
var isSameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
var SaasDevicePlanning = ({
  className,
  style
}) => {
  var _a;
  const context = (0, import_useEngineContext.default)();
  const locale = (0, import_useLocale.default)();
  import_utils.locales.init(import_locales.default, locale || "en");
  const getText = import_utils.locales.getText;
  const translation = (0, import_hooks.useTranslation)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  const [workAreas, setWorkAreas] = (0, import_react.useState)([]);
  const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, import_react.useState)();
  const [activeKind, setActiveKind] = (0, import_react.useState)("smart");
  const [search, setSearch] = (0, import_react.useState)("");
  const [typeFilter, setTypeFilter] = (0, import_react.useState)(void 0);
  const [modelCacheByKind, setModelCacheByKind] = (0, import_react.useState)({});
  const modelCacheByKindRef = (0, import_react.useRef)({});
  const [deviceOrderIds, setDeviceOrderIds] = (0, import_react.useState)([]);
  const requestedModelKindsRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const [page, setPage] = (0, import_react.useState)(1);
  const [pageSize, setPageSize] = (0, import_react.useState)(import_constants.DEFAULT_PAGE_SIZE);
  const [addDeviceOpen, setAddDeviceOpen] = (0, import_react.useState)(false);
  const [detailOpen, setDetailOpen] = (0, import_react.useState)(false);
  const [selectedDevice, setSelectedDevice] = (0, import_react.useState)();
  const [editDeviceOpen, setEditDeviceOpen] = (0, import_react.useState)(false);
  const [deleteDeviceOpen, setDeleteDeviceOpen] = (0, import_react.useState)(false);
  const [workAreaModalOpen, setWorkAreaModalOpen] = (0, import_react.useState)(false);
  const [workAreaModalMode, setWorkAreaModalMode] = (0, import_react.useState)("create");
  const [editingWorkArea, setEditingWorkArea] = (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)({
    smart: 0,
    dumb: 0,
    integrated: 0
  });
  (0, import_react.useEffect)(() => {
    if (utils == null ? void 0 : utils.request) {
      import_utils2.request.setRequest(utils.request);
    }
  }, [utils == null ? void 0 : utils.request]);
  const workAreaRequest = (0, import_ahooks.useRequest)(import_serve.getWorkAreas, {
    onSuccess: (list) => {
      setWorkAreas((0, import_constants.sortWorkAreaList)(list));
    }
  });
  const saveRequest = (0, import_ahooks.useRequest)(
    (payload) => workAreaModalMode === "create" ? (0, import_serve.createWorkArea)(payload) : (0, import_serve.updateWorkArea)((editingWorkArea == null ? void 0 : editingWorkArea.id) || "", payload),
    { manual: true }
  );
  const sortRequest = (0, import_ahooks.useRequest)(import_serve.sortWorkAreas, { manual: true });
  const deviceRequest = (0, import_ahooks.useRequest)(import_serve.getDevices, { manual: true });
  const createDeviceRequest = (0, import_ahooks.useRequest)(import_serve.createDevice, { manual: true });
  const updateDeviceRequest = (0, import_ahooks.useRequest)(
    (params) => (0, import_serve.updateDevice)(params.id, params.payload),
    { manual: true }
  );
  const removeDeviceRequest = (0, import_ahooks.useRequest)(import_serve.deleteDevice, { manual: true });
  const sortDeviceRequest = (0, import_ahooks.useRequest)(import_serve.sortDevices, { manual: true });
  const getWorkAreaDetailRequest = (0, import_ahooks.useRequest)(import_serve.getWorkAreaDetail, {
    manual: true
  });
  const deleteRequest = (0, import_ahooks.useRequest)(import_serve.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]);
  (0, import_react.useEffect)(() => {
    if (!selectedWorkAreaId) return;
    deviceRequest.run({
      workarea_id: selectedWorkAreaId,
      type_kind: activeKind,
      with: ["type", "model", "workarea"]
    });
  }, [selectedWorkAreaId, activeKind]);
  (0, import_react.useEffect)(() => {
    if (!selectedWorkAreaId) return;
    if (modelCacheByKindRef.current[activeKind]) return;
    if (requestedModelKindsRef.current.has(activeKind)) return;
    requestedModelKindsRef.current.add(activeKind);
    (0, import_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, { ...model, type });
          }
        });
      });
      const models = Array.from(modelMap.values());
      modelCacheByKindRef.current = {
        ...modelCacheByKindRef.current,
        [activeKind]: models
      };
      setModelCacheByKind(modelCacheByKindRef.current);
    }).catch(() => {
      modelCacheByKindRef.current = {
        ...modelCacheByKindRef.current,
        [activeKind]: []
      };
      setModelCacheByKind(modelCacheByKindRef.current);
    });
  }, [activeKind, selectedWorkAreaId]);
  const selectedWorkArea = (0, import_react.useMemo)(
    () => workAreas.find((item) => item.id === selectedWorkAreaId),
    [selectedWorkAreaId, workAreas]
  );
  const devices = deviceRequest.data || EMPTY_DEVICES;
  (0, import_react.useEffect)(() => {
    const nextIds = devices.map((item) => item.id);
    setDeviceOrderIds((prev) => isSameIds(prev, nextIds) ? prev : nextIds);
  }, [devices]);
  const typeOptions = (0, import_react.useMemo)(() => {
    const models = modelCacheByKind[activeKind] || [];
    return models.map((model) => ({
      label: translation(model.name) || model.code,
      value: model.code
    }));
  }, [activeKind, modelCacheByKind, translation]);
  const profileNameMap = (0, import_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 _a2;
      if ((_a2 = device.profile) == null ? void 0 : _a2.id) {
        map.set(
          device.profile.id,
          translation(device.profile.name) || String(device.profile.id)
        );
      }
    });
    return map;
  }, [devices, modelCacheByKind, translation]);
  const tableData = (0, import_react.useMemo)(() => {
    const keyword = (0, import_constants.normalizeText)(search);
    const orderMap = new Map(deviceOrderIds.map((id, index) => [id, index]));
    return [...devices].sort(
      (a, b) => (orderMap.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (orderMap.get(b.id) ?? Number.MAX_SAFE_INTEGER)
    ).map((item) => {
      var _a2, _b, _c;
      const name = translation(item.name);
      const typeName = translation((_a2 = item.type) == null ? void 0 : _a2.name) || item.type_code;
      const modelName = translation((_b = item.model) == null ? void 0 : _b.name) || item.model_code;
      const link = item.link || "unlinked";
      const profileName = translation((_c = item.profile) == null ? void 0 : _c.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 ? (0, import_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 = async (selectedId) => {
    const list = await workAreaRequest.runAsync();
    const sorted = (0, import_constants.sortWorkAreaList)(list);
    setWorkAreas(sorted);
    if (selectedId) {
      setSelectedWorkAreaId(selectedId);
    }
    return sorted;
  };
  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 = 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 openCreateModal = () => {
    setWorkAreaModalMode("create");
    setEditingWorkArea(void 0);
    setWorkAreaModalOpen(true);
  };
  const openEditModal = (record) => {
    setWorkAreaModalMode("edit");
    setEditingWorkArea(record);
    setWorkAreaModalOpen(true);
  };
  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
      });
      setWorkAreaModalOpen(false);
      setEditingWorkArea(void 0);
      await reloadWorkAreas((saved == null ? void 0 : saved.id) || (editingWorkArea == null ? void 0 : editingWorkArea.id));
    } catch (e) {
    }
  };
  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 _a2;
      console.log("xue_detail", res);
      const _workArea = (_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2[0];
      setDeleteCounts({
        smart: (_workArea == null ? void 0 : _workArea.smart_devices_count) || 0,
        dumb: (_workArea == null ? void 0 : _workArea.dumb_devices_count) || 0,
        integrated: (_workArea == null ? void 0 : _workArea.integrated_devices_count) || 0
      });
    }).catch(() => setDeleteCounts({ smart: 0, dumb: 0, integrated: 0 }));
  };
  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
      });
      setDeleteModalOpen(false);
      setDeleteRecord(void 0);
      await reloadWorkAreas();
    } catch (e) {
    }
  };
  const handleCreateDevice = async (payload) => {
    try {
      await createDeviceRequest.runAsync(payload);
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.add.create-success"),
        duration: 2
      });
      setAddDeviceOpen(false);
      setPage(1);
      reloadDevices();
    } catch (e) {
    }
  };
  const handleDeviceSort = async (orderedRows) => {
    const ids = orderedRows.map((item) => item.id);
    setDeviceOrderIds(ids);
    try {
      await sortDeviceRequest.runAsync(ids);
      reloadDevices();
    } catch (e) {
      reloadDevices();
    }
  };
  const handleUpdateDevice = async (id, payload) => {
    try {
      await updateDeviceRequest.runAsync({ id, payload });
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.edit.success"),
        duration: 2
      });
      setEditDeviceOpen(false);
      setDetailOpen(false);
      setSelectedDevice(void 0);
      reloadDevices();
    } catch (e) {
    }
  };
  const handleDeleteDevice = async () => {
    if (!selectedDevice) return;
    try {
      await removeDeviceRequest.runAsync(selectedDevice.id);
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.delete-device.success"),
        duration: 2
      });
      setDeleteDeviceOpen(false);
      setDetailOpen(false);
      setSelectedDevice(void 0);
      reloadDevices();
    } catch (e) {
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("saas-device-planning", className),
      style
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_WorkAreaList.default,
      {
        loading: workAreaRequest.loading,
        workAreas,
        selectedWorkAreaId,
        getText,
        translation,
        onCreate: openCreateModal,
        onSelect: (id) => {
          setSelectedWorkAreaId(id);
          resetDeviceView();
        },
        onEdit: openEditModal,
        onDelete: openDeleteModal,
        onSortEnd: handleDragEnd
      }
    ),
    /* @__PURE__ */ import_react.default.createElement("main", { className: "saas-device-planning__content" }, showWorkAreaLoading ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, null)) : showEmptyWorkArea ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-planning__empty-workarea" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Empty,
      {
        image: import_materials.Empty.PRESENTED_IMAGE_SIMPLE,
        description: getText(
          "pisell2.saas.device-planning.empty.workarea-first"
        )
      }
    )) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-planning__page-header" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-planning__title" }, selectedWorkArea ? translation(selectedWorkArea.name) : "-"), (selectedWorkArea == null ? void 0 : selectedWorkArea.description) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-planning__subtitle" }, translation(selectedWorkArea.description)) : null)), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Tabs,
      {
        activeKey: activeKind,
        onChange: (key) => {
          setActiveKind(key);
          resetDeviceView();
        },
        items: import_types.DEVICE_KIND_OPTIONS.map((kind) => ({
          key: kind,
          label: getText(import_constants.DEVICE_KIND_LABEL_KEY[kind])
        }))
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_DeviceTable.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__ */ import_react.default.createElement(
      import_DeviceDetailDrawer.default,
      {
        open: detailOpen,
        record: selectedDevice,
        getText,
        translation,
        onClose: () => setDetailOpen(false),
        onEdit: () => setEditDeviceOpen(true),
        onDelete: () => setDeleteDeviceOpen(true)
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_EditDeviceModal.default,
      {
        open: editDeviceOpen,
        record: selectedDevice,
        workAreas,
        models: modelCacheByKind[activeKind] || [],
        submitting: updateDeviceRequest.loading,
        getText,
        translation,
        onCancel: () => setEditDeviceOpen(false),
        onSubmit: handleUpdateDevice
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_DeleteDeviceModal.default,
      {
        open: deleteDeviceOpen,
        record: selectedDevice,
        submitting: removeDeviceRequest.loading,
        getText,
        onCancel: () => setDeleteDeviceOpen(false),
        onConfirm: handleDeleteDevice
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_AddDeviceModal.default,
      {
        open: addDeviceOpen,
        activeKind,
        models: modelCacheByKind[activeKind] || [],
        workAreaId: selectedWorkAreaId,
        submitting: createDeviceRequest.loading,
        getText,
        translation,
        onClose: () => setAddDeviceOpen(false),
        onSubmit: handleCreateDevice
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_WorkAreaModal.default,
      {
        open: workAreaModalOpen,
        mode: workAreaModalMode,
        record: editingWorkArea,
        submitting: saveRequest.loading,
        getText,
        onCancel: () => {
          setWorkAreaModalOpen(false);
          setEditingWorkArea(void 0);
        },
        onSubmit: handleSaveWorkArea
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_DeleteWorkAreaModal.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
      }
    )
  );
};
var devicePlanning_default = SaasDevicePlanning;
