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/deviceProfile/index.tsx
var deviceProfile_exports = {};
__export(deviceProfile_exports, {
  default: () => deviceProfile_default
});
module.exports = __toCommonJS(deviceProfile_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_icons = require("@ant-design/icons");
var import_classnames = __toESM(require("classnames"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_utils2 = require("../../../utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_useLocale = __toESM(require("../../../hooks/useLocale"));
var import_TwoColumnPageLayout = __toESM(require("./components/TwoColumnPageLayout"));
var import_SiderMenuPanel = __toESM(require("./components/SiderMenuPanel"));
var import_CreateProfileModal = __toESM(require("./components/CreateProfileModal"));
var import_DeleteProfileModal = __toESM(require("./components/DeleteProfileModal"));
var import_serve = require("./serve");
var import_hooks = require("./hooks");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var import_ProfileSetting = __toESM(require("./components/ProfileSetting"));
var KIND_ORDER = ["smart", "dumb", "integrated"];
var DEFAULT_PAGE_SIZE = 10;
var SaasDeviceProfile = ({
  className,
  style,
  scene = "profile",
  showBackButton = false
}) => {
  var _a, _b, _c;
  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) || {};
  if (utils == null ? void 0 : utils.request) {
    import_utils2.request.setRequest(utils.request);
  }
  const [siderSearch, setSiderSearch] = (0, import_react.useState)("");
  const [selectedCode, setSelectedCode] = (0, import_react.useState)("");
  const [page, setPage] = (0, import_react.useState)(1);
  const [pageSize, setPageSize] = (0, import_react.useState)(DEFAULT_PAGE_SIZE);
  const [filters, setFilters] = (0, import_react.useState)({});
  const [createOpen, setCreateOpen] = (0, import_react.useState)(false);
  const [duplicateSource, setDuplicateSource] = (0, import_react.useState)(void 0);
  const [deleteOpen, setDeleteOpen] = (0, import_react.useState)(false);
  const [deleteRecord, setDeleteRecord] = (0, import_react.useState)(
    void 0
  );
  const [linkedDevices, setLinkedDevices] = (0, import_react.useState)([]);
  const [modalOpen, setModalOpen] = (0, import_react.useState)(false);
  const [modalState, setModalState] = (0, import_react.useState)(null);
  const tableRef = (0, import_react.useRef)(null);
  const skipNextFetchRef = (0, import_react.useRef)(false);
  const detailRequest = (0, import_ahooks.useRequest)(import_serve.getDeviceTypes, { manual: true });
  const profileRequest = (0, import_ahooks.useRequest)(import_serve.getDeviceProfiles, { manual: true });
  const checkLinkedRequest = (0, import_ahooks.useRequest)(import_serve.getProfileLinkedDevices, {
    manual: true
  });
  const deleteRequest = (0, import_ahooks.useRequest)(import_serve.deleteDeviceProfile, { manual: true });
  const handleSelectType = (0, import_react.useCallback)(
    (code) => {
      var _a2, _b2;
      if (!code || code === selectedCode) return;
      skipNextFetchRef.current = true;
      setSelectedCode(code);
      setFilters({});
      setPage(1);
      (_b2 = (_a2 = tableRef.current) == null ? void 0 : _a2.formInstance) == null ? void 0 : _b2.resetFields([
        ["filters", "search"],
        ["filters", "model"],
        ["filters", "status"]
      ]);
      detailRequest.run({
        code,
        with: ["activeModels", "activeModels.activeProfileTemplates"]
      });
      profileRequest.run({
        page: 1,
        size: pageSize,
        type_code: code
      });
    },
    [selectedCode, pageSize, detailRequest, profileRequest]
  );
  const listRequest = (0, import_ahooks.useRequest)(() => (0, import_serve.getDeviceTypes)(), {
    onSuccess: (list) => {
      if (!selectedCode && list.length) {
        const first = list.find((it) => it.status === "active") || list[0];
        handleSelectType(first.code);
      }
    }
  });
  const selectedDetail = (0, import_react.useMemo)(() => {
    const data = detailRequest.data || [];
    return data.find((it) => it.code === selectedCode) || data[0];
  }, [detailRequest.data, selectedCode]);
  (0, import_react.useEffect)(() => {
    if (skipNextFetchRef.current) {
      skipNextFetchRef.current = false;
      return;
    }
    if (!selectedCode) return;
    profileRequest.run({
      page,
      size: pageSize,
      type_code: selectedCode,
      model_code: filters.model || void 0,
      status: filters.status || void 0,
      search: filters.search || void 0
    });
  }, [selectedCode, page, pageSize, filters]);
  const menuItems = (0, import_react.useMemo)(() => {
    const all = listRequest.data || [];
    const keyword = siderSearch.trim().toLowerCase();
    return KIND_ORDER.map((kind) => {
      const children = all.filter((it) => it.kind === kind).sort((a, b) => a.sort - b.sort).map((it) => ({
        item: it,
        text: translation(it.name)
      })).filter(
        ({ text }) => keyword ? String(text).toLowerCase().includes(keyword) : true
      ).map(({ item, text }) => ({
        key: item.code,
        label: text,
        icon: item.icon ? /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: item.icon }) : null
      }));
      return {
        key: `group-${kind}`,
        type: "group",
        label: getText(`pisell2.saas.device-profile.kind.${kind}`),
        children
      };
    });
  }, [listRequest.data, siderSearch, translation, getText]);
  const modelOptions = (0, import_react.useMemo)(
    () => ((selectedDetail == null ? void 0 : selectedDetail.active_models) || []).map((m) => ({
      label: translation(m.name),
      value: m.code
    })),
    [selectedDetail, translation]
  );
  const modelNameMap = (0, import_react.useMemo)(() => {
    const map = {};
    ((selectedDetail == null ? void 0 : selectedDetail.active_models) || []).forEach((m) => {
      map[m.code] = translation(m.name);
    });
    return map;
  }, [selectedDetail, translation]);
  const tableData = (0, import_react.useMemo)(() => {
    var _a2;
    const list = ((_a2 = profileRequest.data) == null ? void 0 : _a2.list) || [];
    return list.map((it) => {
      var _a3;
      return {
        id: it.id,
        name: translation(it.name),
        modelCode: it.model_code,
        modelName: modelNameMap[it.model_code] || it.model_code,
        status: it.status,
        updated_at: it.updated_at,
        _deviceType: selectedDetail,
        _deviceModel: (_a3 = selectedDetail == null ? void 0 : selectedDetail.active_models) == null ? void 0 : _a3.find(
          (m) => m.code === (it == null ? void 0 : it.model_code)
        ),
        _raw: it
      };
    });
  }, [profileRequest.data, modelNameMap, translation]);
  const total = ((_b = profileRequest.data) == null ? void 0 : _b.count) || 0;
  const noop = (0, import_react.useCallback)(
    (action, record) => {
      var _a2;
      console.log("action =>>>>", action, record);
      switch (action) {
        case "edit":
          setModalOpen(true);
          setModalState({
            record,
            deviceModel: record == null ? void 0 : record._deviceModel,
            deviceType: record == null ? void 0 : record._deviceType
          });
          break;
        case "copy":
          if (record == null ? void 0 : record._raw) {
            setDuplicateSource(record._raw);
            setCreateOpen(true);
          }
          break;
        case "delete": {
          const typeKind = (_a2 = record._deviceType) == null ? void 0 : _a2.kind;
          if (!record.id || !typeKind) return;
          setDeleteRecord(record);
          setLinkedDevices([]);
          setDeleteOpen(true);
          checkLinkedRequest.runAsync({
            profile_id: record.id,
            type_kind: typeKind,
            with: ["workarea"]
          }).then((list) => setLinkedDevices(list || [])).catch(() => setLinkedDevices([]));
          break;
        }
      }
    },
    [checkLinkedRequest]
  );
  const filterConfig = (0, import_react.useMemo)(
    () => ({
      show: true,
      quickFilterMaxLength: 3,
      list: [
        {
          key: "search",
          type: "search",
          name: "search",
          isCustom: true,
          columnKey: "",
          localFilter: false,
          other: {
            size: "large",
            allowClear: true,
            trigger: ["onChange", "onPressEnter"],
            placeholder: getText("pisell2.saas.device-profile.search-profiles"),
            style: { width: 280 }
          }
        },
        {
          key: "model",
          type: "single",
          name: "model",
          isCustom: true,
          columnKey: "",
          localFilter: false,
          other: {
            size: "large",
            allowClear: true,
            placeholder: getText(
              "pisell2.saas.device-profile.filter.all-models"
            ),
            options: modelOptions,
            style: { width: 200 }
          }
        },
        {
          key: "status",
          type: "single",
          name: "status",
          isCustom: true,
          columnKey: "",
          localFilter: false,
          other: {
            size: "large",
            allowClear: true,
            placeholder: getText(
              "pisell2.saas.device-profile.filter.all-status"
            ),
            options: [
              {
                label: getText("pisell2.saas.device-profile.status.active"),
                value: "active"
              },
              {
                label: getText("pisell2.saas.device-profile.status.inactive"),
                value: "inactive"
              }
            ],
            style: { width: 160 }
          }
        }
      ]
    }),
    [getText, modelOptions]
  );
  const handleValuesChange = (0, import_react.useCallback)((_changed, values) => {
    const f = (values == null ? void 0 : values.filters) || {};
    setFilters({
      search: f.search,
      model: f.model,
      status: f.status
    });
    if (values == null ? void 0 : values.pagination) {
      setPage(values.pagination.page || 1);
      setPageSize(values.pagination.size || DEFAULT_PAGE_SIZE);
    }
  }, []);
  const columns = (0, import_react.useMemo)(
    () => [
      {
        title: getText("pisell2.saas.device-profile.column.name"),
        dataIndex: "name",
        key: "name"
      },
      {
        title: getText("pisell2.saas.device-profile.column.device-model"),
        dataIndex: "modelName",
        key: "modelName"
      },
      {
        title: getText("pisell2.saas.device-profile.column.status"),
        dataIndex: "status",
        key: "status",
        width: 120,
        render: (status) => /* @__PURE__ */ import_react.default.createElement(
          import_materials.Tag,
          {
            variant: "solid",
            color: status === "active" ? "green" : "default"
          },
          getText(`pisell2.saas.device-profile.status.${status}`)
        )
      },
      {
        title: getText("pisell2.saas.device-profile.column.updated"),
        dataIndex: "updated_at",
        key: "updated_at",
        width: 180,
        render: (text) => text ? (0, import_dayjs.default)(text).format("DD/MM/YYYY HH:mm") : "-"
      },
      {
        title: getText("pisell2.saas.device-profile.column.actions"),
        key: "actions",
        width: 140,
        render: (record) => /* @__PURE__ */ import_react.default.createElement(import_materials.Space, { size: 4 }, /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.EditOutlined, null),
            onClick: () => noop("edit", record)
          }
        ), /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.CopyOutlined, null),
            onClick: () => noop("copy", record)
          }
        ), /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            danger: true,
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.DeleteOutlined, null),
            onClick: () => noop("delete", record)
          }
        ))
      }
    ],
    [getText, noop]
  );
  const emptyProfilesText = (0, import_react.useMemo)(() => {
    const dt = selectedDetail ? translation(selectedDetail.name) : "";
    return getText("pisell2.saas.device-profile.empty.profiles").replace(
      "{DeviceType}",
      dt || ""
    );
  }, [getText, selectedDetail, translation]);
  const reload = () => {
    profileRequest.run({
      page,
      size: pageSize,
      type_code: selectedCode,
      model_code: filters.model || void 0,
      status: filters.status || void 0,
      search: filters.search || void 0
    });
  };
  const handleBack = (0, import_react.useCallback)(() => {
    var _a2, _b2, _c2, _d, _e;
    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);
  }, [(_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils]);
  const pageSubTitle = getText("pisell2.saas.device-profile.subtitle");
  const pageTitle = (0, import_react.useMemo)(() => {
    const title = getText("pisell2.saas.device-profile.title");
    if (!showBackButton) return title;
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile__page-heading" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "text",
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.ArrowLeftOutlined, null),
        className: "saas-device-profile__back-button",
        onClick: handleBack,
        size: "large"
      }
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile__page-title" }, /* @__PURE__ */ import_react.default.createElement("span", null, title), /* @__PURE__ */ import_react.default.createElement("span", { className: "saas-device-profile__page-subtitle" }, pageSubTitle)));
  }, [getText, handleBack, pageSubTitle, showBackButton]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("saas-device-profile", className), style }, /* @__PURE__ */ import_react.default.createElement(
    import_TwoColumnPageLayout.default,
    {
      title: pageTitle,
      subTitle: showBackButton ? void 0 : pageSubTitle,
      sider: /* @__PURE__ */ import_react.default.createElement(
        import_SiderMenuPanel.default,
        {
          title: getText("pisell2.saas.device-profile.device-type"),
          searchable: true,
          searchPlaceholder: getText("pisell2.saas.device-profile.search"),
          onSearch: setSiderSearch,
          items: menuItems,
          selectedKey: selectedCode,
          onSelect: handleSelectType,
          emptyText: getText(
            "pisell2.saas.device-profile.empty.device-types"
          )
        }
      )
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.Table,
      {
        ref: tableRef,
        rowKey: "id",
        dataSource: tableData,
        columns,
        loading: detailRequest.loading || profileRequest.loading,
        filter: filterConfig,
        onValuesChange: handleValuesChange,
        scroll: {
          autoCalc: true,
          scrollToFirstRowOnChange: true
        },
        pagination: {
          localPagination: false,
          current: page,
          pageSize,
          total,
          showSizeChanger: true,
          onChange: (p) => {
            setPage(p.page);
            setPageSize(p.size);
          }
        },
        showTitle: false,
        showSubTitle: false,
        actionButtons: [
          {
            type: "primary",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
            title: getText("pisell2.saas.device-profile.create"),
            onClick: () => setCreateOpen(true),
            disabled: !selectedDetail
          }
        ],
        locale: { emptyText: emptyProfilesText },
        bordered: true
      }
    )
  ), createOpen && /* @__PURE__ */ import_react.default.createElement(
    import_CreateProfileModal.default,
    {
      open: createOpen,
      mode: duplicateSource ? "duplicate" : "create",
      sourceProfile: duplicateSource,
      deviceType: selectedDetail,
      getText,
      translation,
      onClose: () => {
        setCreateOpen(false);
        setDuplicateSource(void 0);
      },
      onSuccess: () => {
        setCreateOpen(false);
        setDuplicateSource(void 0);
        if (page !== 1) {
          setPage(1);
        } else {
          profileRequest.run({
            page: 1,
            size: pageSize,
            type_code: selectedCode,
            model_code: filters.model || void 0,
            status: filters.status || void 0,
            search: filters.search || void 0
          });
        }
      }
    }
  ), deleteOpen && /* @__PURE__ */ import_react.default.createElement(
    import_DeleteProfileModal.default,
    {
      open: deleteOpen,
      loading: checkLinkedRequest.loading,
      submitting: deleteRequest.loading,
      profileName: deleteRecord ? deleteRecord.name : "",
      linkedDevices,
      translation,
      getText,
      onClose: () => {
        setDeleteOpen(false);
        setDeleteRecord(void 0);
        setLinkedDevices([]);
      },
      onConfirm: async () => {
        console.log("deleteRecord =>>>>", deleteRecord);
        if (!deleteRecord) return;
        try {
          await deleteRequest.runAsync(deleteRecord.id);
          (0, import_materials.PisellToast)({
            content: getText(
              "pisell2.saas.device-profile.message.delete-success"
            ),
            duration: 2
          });
          setDeleteOpen(false);
          setDeleteRecord(void 0);
          setLinkedDevices([]);
          reload();
        } catch (e) {
        }
      }
    }
  ), modalOpen && /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-template-modal" }, /* @__PURE__ */ import_react.default.createElement(
    import_ProfileSetting.default,
    {
      record: modalState == null ? void 0 : modalState.record,
      deviceModel: modalState == null ? void 0 : modalState.deviceModel,
      deviceType: modalState == null ? void 0 : modalState.deviceType,
      scene,
      onBack: () => {
        reload();
        setModalOpen(false);
        setModalState(null);
      }
    }
  )));
};
var deviceProfile_default = SaasDeviceProfile;
