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/components/ProfileSetting/index.tsx
var ProfileSetting_exports = {};
__export(ProfileSetting_exports, {
  default: () => ProfileSetting_default
});
module.exports = __toCommonJS(ProfileSetting_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_icons = require("@ant-design/icons");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_UnsavedConfirmModal = require("../UnsavedConfirmModal");
var import_utils2 = require("./utils");
var import_BasicForm = __toESM(require("./BasicForm"));
var import_index = require("./index.less");
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_hooks = require("../../hooks");
var import_serve = require("../../serve");
var getText = import_utils.locales.getText;
var LowCodePage = (props) => {
  var _a;
  const { id, ...others } = props;
  const context = (0, import_useEngineContext.default)();
  const { RenderLowCodeByKey, getRenderLowCodeByKey } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const Com = getRenderLowCodeByKey ? getRenderLowCodeByKey == null ? void 0 : getRenderLowCodeByKey() : RenderLowCodeByKey;
  if (!Com) return /* @__PURE__ */ import_react.default.createElement("div", null, "RenderLowCodeByKey is not found");
  return /* @__PURE__ */ import_react.default.createElement(Com, { ...others, id, key: id });
};
var BASIC_KEY = "basic";
var ProfileSetting = (props) => {
  var _a, _b, _c, _d;
  const context = (0, import_useEngineContext.default)();
  const app = ((_c = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b)) || {};
  const { record, deviceModel, deviceType, scene = "profile", onBack } = props;
  const translation = (0, import_hooks.useTranslation)();
  const [model, setModel] = (0, import_react.useState)(deviceModel);
  const [typeItem, setTypeItem] = (0, import_react.useState)();
  const [bootstrapping, setBootstrapping] = (0, import_react.useState)(true);
  (0, import_react.useEffect)(() => {
    if (!record) return;
    (async () => {
      try {
        if (deviceType) setTypeItem(deviceType);
        if (deviceModel) setModel(deviceModel);
      } catch (error) {
        app.logger.addLog({
          type: "error",
          title: "加载配置模板上下文失败",
          metadata: error
        });
      } finally {
        setBootstrapping(false);
      }
    })();
  }, []);
  const profileStructure = (_d = model == null ? void 0 : model.data) == null ? void 0 : _d.profile_structure;
  const extraTabs = (0, import_react.useMemo)(
    () => (profileStructure == null ? void 0 : profileStructure.required) ? [...profileStructure.tabs ?? []].sort(
      (a, b) => ((a == null ? void 0 : a.sort) ?? 0) - ((b == null ? void 0 : b.sort) ?? 0)
    ) : [],
    [profileStructure]
  );
  const menuItems = (0, import_react.useMemo)(
    () => [
      {
        key: BASIC_KEY,
        label: getText("pisell2.saas.device-profile.setting.menu.basic")
      },
      ...(extraTabs == null ? void 0 : extraTabs.map((t, i) => ({
        key: `tab-${i}`,
        label: translation(t.title) || `Tab ${i + 1}`
      }))) || []
    ],
    [extraTabs]
  );
  const [activeKey, setActiveKey] = (0, import_react.useState)(BASIC_KEY);
  const formRef = (0, import_react.useRef)(null);
  const [dirty, setDirty] = (0, import_react.useState)(false);
  const [saving, setSaving] = (0, import_react.useState)(false);
  const [displayName, setDisplayName] = (0, import_react.useState)(
    record == null ? void 0 : record.name
  );
  if (!record) {
    return null;
  }
  const title = translation(displayName) || record.code;
  const subtitle = getText("pisell2.saas.device-profile.setting.subtitle");
  const switchKey = (next) => {
    if (next === activeKey) return;
    if (dirty && activeKey === BASIC_KEY) {
      (0, import_UnsavedConfirmModal.unsavedChangesConfirm)(() => {
        setDirty(false);
        setActiveKey(next);
      });
      return;
    }
    setActiveKey(next);
  };
  const handleBack = () => {
    if (dirty) {
      (0, import_UnsavedConfirmModal.unsavedChangesConfirm)(() => {
        setDirty(false);
        onBack();
      });
      return;
    }
    onBack();
  };
  const handleSave = async () => {
    if (!formRef.current) return;
    try {
      const values = await formRef.current.getValues();
      setSaving(true);
      await (0, import_serve.updateDeviceProfile)(record.id, (0, import_utils2.toUpdatePayload)(values));
      setDisplayName(values.name);
      import_antd.message.success(
        getText("pisell2.saas.device-profile.message.updateSuccess")
      );
      setDirty(false);
    } catch (error) {
      if (error && error.errorFields) {
        return;
      }
      app.logger.addLog({
        type: "error",
        title: "更新配置模板失败",
        metadata: error
      });
    } finally {
      setSaving(false);
    }
  };
  const activeTab = activeKey === BASIC_KEY ? null : extraTabs[Number(activeKey.replace("tab-", ""))];
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__header-left" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      type: "text",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.ArrowLeftOutlined, null),
      onClick: handleBack
    }
  ), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__title" }, title), subtitle ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__subtitle" }, subtitle) : null))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__alert-wrap" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Alert,
    {
      type: "warning",
      showIcon: true,
      message: getText("pisell2.saas.device-profile.setting.saveWarning")
    }
  )), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__main" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__menu-card" }, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellMenu,
    {
      mode: "inline",
      theme: "light",
      dataSource: menuItems,
      selectedKeys: [activeKey],
      onSelect: ({ key }) => switchKey(String(key))
    }
  )), /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "saas-device-profile-setting__content-card",
      style: { padding: activeKey === BASIC_KEY ? "24px" : 0 }
    },
    bootstrapping ? /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__loading-wrap" }, /* @__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",
      {
        style: { display: activeKey === BASIC_KEY ? "block" : "none" }
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__section-title" }, getText(
        "pisell2.saas.device-profile.setting.section.basicInfo"
      )), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__subtitle" }, getText(
        "pisell2.saas.device-profile.setting.section.basicInfoDesc"
      ))),
      /* @__PURE__ */ import_react.default.createElement(
        import_BasicForm.default,
        {
          ref: formRef,
          mode: "edit",
          deviceType: typeItem,
          deviceModels: model ? [model] : [],
          initialValue: record,
          onDirty: () => setDirty(true)
        }
      ),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-device-profile-setting__save-actions" }, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          type: "primary",
          size: "large",
          loading: saving,
          onClick: handleSave
        },
        getText("pisell2.saas.device-profile.common.save")
      ))
    ), activeKey !== BASIC_KEY && activeTab ? /* @__PURE__ */ import_react.default.createElement(
      LowCodePage,
      {
        id: activeTab == null ? void 0 : activeTab.page_id,
        scene,
        sceneRequestId: record == null ? void 0 : record.id
      }
    ) : null)
  )));
};
var ProfileSetting_default = ProfileSetting;
