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/appDevicePlanning/index.tsx
var appDevicePlanning_exports = {};
__export(appDevicePlanning_exports, {
  default: () => appDevicePlanning_default
});
module.exports = __toCommonJS(appDevicePlanning_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
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_responsive = require("../../../responsive");
var import_utils2 = require("../../../utils");
var import_hooks = require("./hooks/index");
var import_locales = __toESM(require("./locales/index"));
var import_model = require("./model");
var import_modelSelection = require("./modules/modelSelection");
var import_devices = require("./modules/devices");
var import_workAreas = require("./modules/workAreas");
var import_index = require("./index.less");
var SaasAppDevicePlanning = ({
  className,
  style,
  kind = "smart",
  showBack = false,
  onLinked,
  onBack,
  variant,
  autoTakeoverLastUsed = false
}) => {
  var _a, _b, _c;
  const context = (0, import_useEngineContext.default)();
  const locale = (0, import_useLocale.default)();
  const currentVariant = variant || "desktop";
  const isPhoneVariant = currentVariant === "phone";
  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 iotEndpoint = ((_c = (_b = context == null ? void 0 : context.appHelper) == null ? void 0 : _b.constants) == null ? void 0 : _c.iotEndpoint) || "";
  const dialogs = (0, import_hooks.useAppDeviceDialogs)();
  (0, import_react.useEffect)(() => {
    if (utils == null ? void 0 : utils.request) {
      import_utils2.request.setRequest(utils.request);
    }
  }, [utils == null ? void 0 : utils.request]);
  const workArea = (0, import_hooks.useAppWorkAreas)({
    getText,
    workAreaModalMode: dialogs.workAreaModalMode,
    editingWorkArea: dialogs.editingWorkArea,
    closeWorkAreaModal: dialogs.closeWorkAreaModal
  });
  const modelState = (0, import_hooks.useAppDeviceModels)({
    kind,
    showBack,
    iotEndpoint,
    translation
  });
  const deviceList = (0, import_hooks.useAppDeviceList)({
    kind,
    typeCode: modelState.typeCode,
    modelCode: modelState.modelCode,
    selectedWorkAreaId: workArea.selectedWorkAreaId,
    modelDetail: modelState.modelDetail,
    deviceTypeName: modelState.deviceTypeName,
    modelName: modelState.modelName,
    utils,
    autoTakeoverLastUsed,
    isModelSelecting: modelState.isModelSelecting,
    translation,
    setInitCheckTakeoverDevice: dialogs.setInitCheckTakeoverDevice
  });
  const linking = (0, import_hooks.useDeviceLinking)({
    utils,
    onLinked,
    reloadDevices: deviceList.reloadDevices,
    setStoredIotDevice: deviceList.setStoredIotDevice,
    setTakeoverDevice: dialogs.setTakeoverDevice,
    setInitCheckTakeoverDevice: dialogs.setInitCheckTakeoverDevice
  });
  const selectedWorkAreaName = (0, import_react.useMemo)(() => {
    const selectedWorkArea = workArea.selectedWorkArea;
    return selectedWorkArea ? translation(selectedWorkArea.name) || getText("pisell2.saas.device-planning.all-work-areas") : getText("pisell2.saas.device-planning.all-work-areas");
  }, [getText, translation, workArea.selectedWorkArea]);
  const showInitialLoading = !modelState.isModelSelecting && (workArea.workAreaRequest.loading && workArea.workAreas.length === 0 || modelState.modelRequest.loading && !modelState.modelDetail);
  const handleBack = () => {
    var _a2, _b2, _c2, _d, _e;
    if (onBack) {
      onBack();
      return;
    }
    const getApp = (_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.getApp;
    const history = (_d = (_c2 = getApp == null ? void 0 : getApp()) == null ? void 0 : _c2.history) == null ? void 0 : _d.instance;
    (_e = history == null ? void 0 : history.goBack) == null ? void 0 : _e.call(history);
  };
  const handleSelectWorkArea = (id) => {
    workArea.setSelectedWorkAreaId(id);
    deviceList.resetDeviceView();
    dialogs.setWorkAreaDrawerOpen(false);
  };
  const handleSelectDeviceModel = (...args) => {
    modelState.handleSelectDeviceModel(...args);
    deviceList.resetDeviceView();
  };
  const handleSwitchDeviceModel = () => {
    modelState.clearDeviceModel();
    deviceList.resetDeviceView();
    dialogs.closeDeviceDialogs();
  };
  const handleCreateDevice = async (payload) => {
    try {
      await deviceList.createDeviceRequest.runAsync(payload);
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.add.create-success"),
        duration: 2
      });
      dialogs.setAddDeviceOpen(false);
      deviceList.setPage(1);
      deviceList.reloadDevices();
    } catch (e) {
      throw e;
    }
  };
  const handleUpdateDevice = async (id, payload) => {
    try {
      await deviceList.updateDeviceRequest.runAsync({ id, payload });
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.edit.success"),
        duration: 2
      });
      dialogs.setEditDeviceOpen(false);
      dialogs.setSelectedDevice(void 0);
      deviceList.reloadDevices();
    } catch (e) {
    }
  };
  const handleDeleteDevice = async () => {
    if (!dialogs.selectedDevice) return;
    try {
      await deviceList.removeDeviceRequest.runAsync(dialogs.selectedDevice.id);
      (0, import_materials.PisellToast)({
        content: getText("pisell2.saas.device-planning.delete-device.success"),
        duration: 2
      });
      dialogs.setDeleteDeviceOpen(false);
      dialogs.setSelectedDevice(void 0);
      deviceList.reloadDevices();
    } catch (e) {
    }
  };
  const closeDrawerAndCreateWorkArea = () => {
    dialogs.setWorkAreaDrawerOpen(false);
    dialogs.openCreateWorkArea();
  };
  const handleLinkDevice = async (record) => {
    var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
    const app = (_a2 = utils == null ? void 0 : utils.getApp) == null ? void 0 : _a2.call(utils);
    setLinkingDeviceId(record.id);
    try {
      const language = ((_b2 = app == null ? void 0 : app.locales) == null ? void 0 : _b2.getLocale()) || "en";
      const deviceDetail = await ((_e = (_d = (_c2 = app == null ? void 0 : app.plugins) == null ? void 0 : _c2.get("device")) == null ? void 0 : _d.getDeviceDetail) == null ? void 0 : _e.call(_d, { language }));
      const linkedDevice = await linkDevice(
        record.id,
        (deviceDetail == null ? void 0 : deviceDetail.data) || {}
      );
      const linkedDeviceSimpleInfo = {
        id: linkedDevice == null ? void 0 : linkedDevice.id,
        // 设备id
        number: linkedDevice == null ? void 0 : linkedDevice.number
        // iot设备编号
      };
      (_f = app == null ? void 0 : app.storage) == null ? void 0 : _f.setStorage(
        "iotDevice",
        JSON.stringify(linkedDeviceSimpleInfo || {})
      );
      (_g = app == null ? void 0 : app.storage) == null ? void 0 : _g.setStorage(
        "iotDeviceLastUsed",
        JSON.stringify(linkedDeviceSimpleInfo || {})
      );
      try {
        await ((_j = (_i = (_h = app == null ? void 0 : app.plugins) == null ? void 0 : _h.get("nativeStorage")) == null ? void 0 : _i.set) == null ? void 0 : _j.call(_i, { key: "iotDeviceFullInfo", value: linkedDevice || {} }));
      } catch (error) {
        (_k = app == null ? void 0 : app.logger) == null ? void 0 : _k.addLog({
          type: "error",
          title: "将完整信息存入 nativeStorage 失败",
          metadata: { error }
        });
      }
      setStoredIotDevice({
        id: typeof (linkedDevice == null ? void 0 : linkedDevice.id) === "number" ? linkedDevice.id : void 0,
        number: (linkedDevice == null ? void 0 : linkedDevice.number) ? String(linkedDevice.number) : ""
      });
      persistDeviceModel(record.typeCode, record.modelCode);
      const setting = await getDeviceSetting(record.id, ["general.channel"]);
      const channel = (setting == null ? void 0 : setting["general.channel"]) ? String(setting["general.channel"]) : "system";
      (_l = localStorage == null ? void 0 : localStorage.setItem) == null ? void 0 : _l.call(localStorage, "pisell_app_channel", channel);
      try {
        await ((_o = (_n = (_m = app == null ? void 0 : app.plugins) == null ? void 0 : _m.get("nativeStorage")) == null ? void 0 : _n.set) == null ? void 0 : _o.call(_n, { key: "pisell_app_channel", value: channel }));
      } catch (error) {
        (_p = app == null ? void 0 : app.logger) == null ? void 0 : _p.addLog({
          type: "error",
          title: "将渠道信息存入 nativeStorage 失败",
          metadata: { error }
        });
      }
      setTakeoverDevice(void 0);
      reloadDevices();
      await (onLinked == null ? void 0 : onLinked({ device: linkedDevice, channel }));
    } catch (e) {
    } finally {
      setLinkingDeviceId(void 0);
    }
  };
  const closeDrawerAndEditWorkArea = (record) => {
    dialogs.setWorkAreaDrawerOpen(false);
    dialogs.openEditWorkArea(record);
  };
  const closeDrawerAndDeleteWorkArea = (record) => {
    dialogs.setWorkAreaDrawerOpen(false);
    workArea.openDeleteModal(record);
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)(
        "saas-app-device-planning",
        `saas-app-device-planning--${currentVariant}`,
        className
      ),
      style
    },
    /* @__PURE__ */ import_react.default.createElement(
      "header",
      {
        className: (0, import_classnames.default)("saas-app-device-planning__global-header", {
          "saas-app-device-planning__global-header--with-back": showBack
        })
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__global-header-left" }, showBack ? /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "text",
          icon: /* @__PURE__ */ import_react.default.createElement(import_icons.ArrowLeftOutlined, null),
          onClick: handleBack
        }
      ) : null, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__global-title" }, getText(
        modelState.isModelSelecting ? "pisell2.saas.device-planning.select-model-title" : "pisell2.saas.device-planning.page-title"
      )), modelState.isModelSelecting ? null : /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__global-subtitle" }, getText("pisell2.saas.device-planning.page-subtitle")))),
      modelState.isModelSelecting ? null : /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__global-actions" }, /* @__PURE__ */ import_react.default.createElement(import_materials.Tag, { color: "green" }, modelState.deviceTypeName), (0, import_model.isUniversalApp)() ? /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "default",
          className: "saas-app-device-planning__switch-model-button",
          icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "SwapOutlined" }),
          onClick: handleSwitchDeviceModel
        },
        getText("pisell2.saas.device-planning.switch-model")
      ) : null)
    ),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__body" }, modelState.isModelSelecting || isPhoneVariant ? null : /* @__PURE__ */ import_react.default.createElement(
      import_workAreas.WorkAreaList,
      {
        loading: workArea.workAreaRequest.loading,
        workAreas: workArea.workAreas,
        selectedWorkAreaId: workArea.selectedWorkAreaId,
        getText,
        translation,
        onCreate: dialogs.openCreateWorkArea,
        onSelect: handleSelectWorkArea,
        onEdit: dialogs.openEditWorkArea,
        onDelete: workArea.openDeleteModal
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      "main",
      {
        className: (0, import_classnames.default)("saas-app-device-planning__content", {
          "saas-app-device-planning__content--model-selecting": modelState.isModelSelecting
        })
      },
      modelState.isModelSelecting ? /* @__PURE__ */ import_react.default.createElement(
        import_modelSelection.ModelSelection,
        {
          loading: modelState.deviceTypeRequest.loading,
          groups: modelState.deviceTypeGroups,
          getText,
          translation,
          onSelect: handleSelectDeviceModel
        }
      ) : showInitialLoading ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__empty-workarea" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, null)) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__page-header" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__title" }, modelState.modelName), modelState.modelDescription ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__subtitle" }, modelState.modelDescription) : null), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-device-planning__page-actions" }, /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "default",
          icon: /* @__PURE__ */ import_react.default.createElement(import_icons.ReloadOutlined, null),
          loading: deviceList.deviceRequest.loading,
          onClick: deviceList.reloadDevices
        },
        getText("pisell2.saas.device-planning.refresh")
      ), /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "primary",
          icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
          onClick: () => dialogs.setAddDeviceOpen(true)
        },
        getText("pisell2.saas.device-planning.add-device")
      ))), isPhoneVariant ? /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          className: "saas-app-device-planning__workarea-trigger",
          onClick: () => dialogs.setWorkAreaDrawerOpen(true)
        },
        /* @__PURE__ */ import_react.default.createElement("span", { className: "saas-app-device-planning__workarea-trigger-label" }, getText("pisell2.saas.device-planning.work-areas")),
        /* @__PURE__ */ import_react.default.createElement("span", { className: "saas-app-device-planning__workarea-trigger-value" }, selectedWorkAreaName),
        /* @__PURE__ */ import_react.default.createElement(import_icons.DownOutlined, null)
      ) : null, /* @__PURE__ */ import_react.default.createElement(
        import_devices.DeviceTable,
        {
          data: deviceList.tableData,
          loading: deviceList.deviceRequest.loading,
          search: deviceList.search,
          page: deviceList.page,
          pageSize: deviceList.pageSize,
          linkingDeviceId: linking.linkingDeviceId,
          getText,
          translation,
          onSearchChange: (value) => {
            deviceList.setSearch(value);
            deviceList.setPage(1);
          },
          onPageChange: (nextPage, nextPageSize) => {
            deviceList.setPage(nextPage);
            deviceList.setPageSize(nextPageSize);
          },
          onAdd: () => dialogs.setAddDeviceOpen(true),
          onLink: linking.handleLinkDevice,
          onTakeBack: dialogs.setInitCheckTakeoverDevice,
          onTakeover: dialogs.setTakeoverDevice,
          onEdit: (record) => {
            dialogs.setSelectedDevice(record);
            dialogs.setEditDeviceOpen(true);
          },
          onDelete: (record) => {
            dialogs.setSelectedDevice(record);
            dialogs.setDeleteDeviceOpen(true);
          }
        }
      ))
    )),
    dialogs.addDeviceOpen ? /* @__PURE__ */ import_react.default.createElement(
      import_devices.AddDeviceModal,
      {
        open: dialogs.addDeviceOpen,
        variant: currentVariant,
        activeKind: kind,
        model: modelState.modelDetail || void 0,
        fallbackModelCode: modelState.modelCode,
        workAreaId: workArea.selectedWorkAreaId,
        workAreas: workArea.workAreas,
        submitting: deviceList.createDeviceRequest.loading,
        preparingShortNumber: deviceList.prepareShortNumberRequest.loading,
        getText,
        translation,
        onClose: () => dialogs.setAddDeviceOpen(false),
        onSubmit: handleCreateDevice,
        onPrepareShortNumber: deviceList.prepareShortNumber
      }
    ) : null,
    dialogs.editDeviceOpen ? /* @__PURE__ */ import_react.default.createElement(
      import_devices.EditDeviceModal,
      {
        open: dialogs.editDeviceOpen,
        variant: currentVariant,
        record: dialogs.selectedDevice,
        workAreas: workArea.workAreas,
        model: modelState.modelDetail || void 0,
        submitting: deviceList.updateDeviceRequest.loading,
        getText,
        translation,
        onCancel: () => dialogs.setEditDeviceOpen(false),
        onSubmit: handleUpdateDevice
      }
    ) : null,
    dialogs.deleteDeviceOpen ? /* @__PURE__ */ import_react.default.createElement(
      import_devices.DeleteDeviceModal,
      {
        open: dialogs.deleteDeviceOpen,
        variant: currentVariant,
        record: dialogs.selectedDevice,
        submitting: deviceList.removeDeviceRequest.loading,
        getText,
        onCancel: () => dialogs.setDeleteDeviceOpen(false),
        onConfirm: handleDeleteDevice
      }
    ) : null,
    dialogs.workAreaModalOpen ? /* @__PURE__ */ import_react.default.createElement(
      import_workAreas.WorkAreaModal,
      {
        open: dialogs.workAreaModalOpen,
        variant: currentVariant,
        mode: dialogs.workAreaModalMode,
        record: dialogs.editingWorkArea,
        submitting: workArea.saveRequest.loading,
        getText,
        onCancel: dialogs.closeWorkAreaModal,
        onSubmit: workArea.handleSaveWorkArea
      }
    ) : null,
    workArea.deleteModalOpen ? /* @__PURE__ */ import_react.default.createElement(
      import_workAreas.DeleteWorkAreaModal,
      {
        open: workArea.deleteModalOpen,
        variant: currentVariant,
        loading: workArea.getWorkAreaDetailRequest.loading,
        submitting: workArea.deleteRequest.loading,
        record: workArea.deleteRecord,
        counts: workArea.deleteCounts,
        translation,
        getText,
        onClose: workArea.closeDeleteModal,
        onConfirm: async () => {
          const deleted = await workArea.handleConfirmDelete();
          if (deleted) {
            deviceList.reloadDevices();
          }
        }
      }
    ) : null,
    !!(dialogs == null ? void 0 : dialogs.initCheckTakeoverDevice) ? /* @__PURE__ */ import_react.default.createElement(
      import_devices.InitCheckTakeoverModal,
      {
        open: Boolean(dialogs.initCheckTakeoverDevice),
        record: dialogs.initCheckTakeoverDevice,
        currentVariant,
        isPhoneVariant,
        linkingDeviceId: linking.linkingDeviceId,
        getText,
        onCancel: () => dialogs.setInitCheckTakeoverDevice(void 0),
        onConfirm: linking.handleLinkDevice
      }
    ) : null,
    dialogs.takeoverDevice ? /* @__PURE__ */ import_react.default.createElement(
      import_devices.TakeoverModal,
      {
        record: dialogs.takeoverDevice,
        currentVariant,
        isPhoneVariant,
        linkingDeviceId: linking.linkingDeviceId,
        getText,
        onCancel: () => dialogs.setTakeoverDevice(void 0),
        onConfirm: linking.handleLinkDevice
      }
    ) : null,
    isPhoneVariant ? /* @__PURE__ */ import_react.default.createElement(
      import_workAreas.WorkAreaDrawer,
      {
        open: dialogs.workAreaDrawerOpen,
        currentVariant,
        loading: workArea.workAreaRequest.loading,
        workAreas: workArea.workAreas,
        selectedWorkAreaId: workArea.selectedWorkAreaId,
        getText,
        translation,
        onClose: () => dialogs.setWorkAreaDrawerOpen(false),
        onCreate: closeDrawerAndCreateWorkArea,
        onSelect: handleSelectWorkArea,
        onEdit: closeDrawerAndEditWorkArea,
        onDelete: closeDrawerAndDeleteWorkArea
      }
    ) : null
  );
};
SaasAppDevicePlanning.displayName = "SaasAppDevicePlanning";
var appDevicePlanning_default = (0, import_responsive.withResponsive)(SaasAppDevicePlanning);
