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/components/authentication/admin/ChannelAuthSetting/OnlineShopAuth/index.tsx
var OnlineShopAuth_exports = {};
__export(OnlineShopAuth_exports, {
  default: () => OnlineShopAuth_default
});
module.exports = __toCommonJS(OnlineShopAuth_exports);
var import_react = __toESM(require("react"));
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_PageSetting = __toESM(require("../PageSetting"));
var import_AuthenticationMethods = __toESM(require("../AuthenticationMethods"));
var import_CollectInfo = __toESM(require("../CollectInfo"));
var import_locales = __toESM(require("../locales"));
var import_index = require("./index.less");
var { Title, Paragraph } = import_antd.Typography;
var Onlineshopauth = ({
  className,
  style,
  value,
  defaultActiveTab,
  visibleTabs,
  showRegisterPage = true,
  onSave
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const { useParams } = context.appHelper.utils.getApp().history;
  let channel = new URLSearchParams(window.location.search).get("channel") || "";
  const { channel: _channel } = useParams();
  channel = channel || _channel;
  const { request } = context.appHelper.utils.getApp();
  const [loading, setLoading] = (0, import_react.useState)(true);
  const [channelData, setChannelData] = (0, import_react.useState)(null);
  const pageSettingRef = (0, import_react.useRef)(null);
  import_utils.locales.init(import_locales.default, ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
  const allTabs = ["pageSetting", "authenticationMethods"];
  const saveData = (data) => {
    request.post(`/api/tenant_channel:update?filter=%7B%22channel_code%22%3A%22${channel}%22%7D`, {
      ...channelData,
      metadata: {
        ...channelData == null ? void 0 : channelData.metadata,
        register_login: data
      }
    }, {
      isNocobase: true,
      headers: {
        "x-data-source": "pisell2"
      }
    }).then((res) => {
      import_antd.message.success(import_utils.locales.getText("channel.auth.setting.message.saveSuccess"));
    }).catch((error) => {
      console.error("Error fetching tenant data:", error);
      import_antd.message.error(import_utils.locales.getText("channel.auth.setting.message.saveError"));
    });
  };
  (0, import_react.useEffect)(() => {
    if (channel) {
      setLoading(true);
      request.get(`/api/tenant_channel:get?filter=%7B%22channel_code%22%3A%22${channel}%22%7D&appends=channel`, {}, {
        isNocobase: true,
        headers: {
          "x-data-source": "pisell2"
        }
      }).then((res) => {
        if (res == null ? void 0 : res.data) {
          try {
            delete res.data.deleted_at;
          } catch (error) {
          }
          setChannelData(res == null ? void 0 : res.data);
        }
        console.log("res_online_shop_auth", res);
        setLoading(false);
      }).catch((error) => {
        console.error("Error fetching tenant data:", error);
        setLoading(false);
      });
    }
  }, [request, channel]);
  const filteredTabsByVisibleTabs = (0, import_react.useMemo)(() => {
    if (visibleTabs && visibleTabs.length > 0) {
      return allTabs.filter((tab) => visibleTabs.includes(tab));
    }
    return allTabs;
  }, [visibleTabs]);
  const displayTabs = (0, import_react.useMemo)(() => {
    if (channel === "management") {
      if (filteredTabsByVisibleTabs.includes("pageSetting")) {
        return ["pageSetting"];
      }
      return [];
    }
    return filteredTabsByVisibleTabs;
  }, [channel, filteredTabsByVisibleTabs]);
  const initialActiveTab = (0, import_react.useMemo)(() => {
    if (defaultActiveTab && displayTabs.includes(defaultActiveTab)) {
      return defaultActiveTab;
    }
    return displayTabs[0] || "pageSetting";
  }, [defaultActiveTab, displayTabs]);
  const [activeTab, setActiveTab] = (0, import_react.useState)(initialActiveTab);
  const [internalValue, setInternalValue] = (0, import_react.useState)(
    value || {}
  );
  (0, import_react.useEffect)(() => {
    if (value) {
      setInternalValue(value);
    }
  }, [value]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
    if ((_a2 = channelData == null ? void 0 : channelData.metadata) == null ? void 0 : _a2.register_login) {
      const { page, auth } = channelData.metadata.register_login;
      const pageSettingValue = {};
      if (page) {
        pageSettingValue.registerPage = {
          backgroundImage: ((_b2 = page.register) == null ? void 0 : _b2.background_image_url) || "",
          termsConditions: ((_d = (_c = page.register) == null ? void 0 : _c.terms) == null ? void 0 : _d.map((term) => {
            var _a3, _b3, _c2, _d2, _e2, _f2;
            return {
              name: {
                original: ((_a3 = term.name) == null ? void 0 : _a3.original) || "",
                en: ((_b3 = term.name) == null ? void 0 : _b3.en) || "",
                "zh-CN": ((_c2 = term.name) == null ? void 0 : _c2["zh-CN"]) || "",
                "zh-HK": ((_d2 = term.name) == null ? void 0 : _d2["zh-HK"]) || "",
                ja: ((_e2 = term.name) == null ? void 0 : _e2["ja"]) || "",
                pt: ((_f2 = term.name) == null ? void 0 : _f2["pt"]) || ""
              },
              url: term.url || ""
            };
          })) || []
        };
        pageSettingValue.loginPage = {
          sameAsRegister: ((_e = page.login) == null ? void 0 : _e.same_as_register) ?? true,
          settings: ((_f = page.login) == null ? void 0 : _f.same_as_register) ? void 0 : {
            backgroundImage: ((_g = page.login) == null ? void 0 : _g.background_image_url) || "",
            termsConditions: ((_i = (_h = page.login) == null ? void 0 : _h.terms) == null ? void 0 : _i.map((term) => {
              var _a3, _b3, _c2, _d2, _e2, _f2;
              return {
                name: {
                  original: ((_a3 = term.name) == null ? void 0 : _a3.original) || "",
                  en: ((_b3 = term.name) == null ? void 0 : _b3.en) || "",
                  "zh-CN": ((_c2 = term.name) == null ? void 0 : _c2["zh-CN"]) || "",
                  "zh-HK": ((_d2 = term.name) == null ? void 0 : _d2["zh-HK"]) || "",
                  ja: ((_e2 = term.name) == null ? void 0 : _e2["ja"]) || "",
                  pt: ((_f2 = term.name) == null ? void 0 : _f2["pt"]) || ""
                },
                url: term.url || ""
              };
            })) || []
          }
        };
      }
      const authenticationMethodsValue = {};
      if (auth) {
        authenticationMethodsValue.mode = auth.mode || "default";
        authenticationMethodsValue.methods = {};
        if ((_j = auth.method) == null ? void 0 : _j.email) {
          authenticationMethodsValue.methods.email = {
            enabled: auth.method.email.enabled ?? true,
            sort: auth.method.email.sort ?? 0
          };
        }
        if ((_k = auth.method) == null ? void 0 : _k.phone) {
          authenticationMethodsValue.methods.phoneNumber = {
            enabled: auth.method.phone.enabled ?? true,
            sort: auth.method.phone.sort ?? 1
          };
        }
        if ((_l = auth.method) == null ? void 0 : _l.facebook) {
          authenticationMethodsValue.methods.facebook = {
            enabled: auth.method.facebook.enabled ?? true,
            sort: auth.method.facebook.sort ?? 2
          };
        }
        if ((_m = auth.method) == null ? void 0 : _m.apple) {
          authenticationMethodsValue.methods.apple = {
            enabled: auth.method.apple.enabled ?? true,
            sort: auth.method.apple.sort ?? 3
          };
        }
        if ((_n = auth.method) == null ? void 0 : _n.guest) {
          authenticationMethodsValue.methods.guest = {
            enabled: auth.method.guest.enabled ?? false,
            sort: auth.method.guest.sort ?? 4
          };
        }
      }
      setInternalValue({
        pageSetting: pageSettingValue,
        authenticationMethods: authenticationMethodsValue
      });
    }
  }, [channelData]);
  const handlePageSettingChange = (0, import_react.useCallback)((pageSettingValue) => {
    setInternalValue((prev) => {
      const hasPageSettingChanged = JSON.stringify(prev.pageSetting) !== JSON.stringify(pageSettingValue);
      if (hasPageSettingChanged) {
        return {
          ...prev,
          pageSetting: pageSettingValue
        };
      }
      return prev;
    });
  }, []);
  const handleAuthenticationMethodsChange = (0, import_react.useCallback)((authMethodsValue) => {
    setInternalValue((prev) => {
      const hasAuthMethodsChanged = JSON.stringify(prev.authenticationMethods) !== JSON.stringify(authMethodsValue);
      if (hasAuthMethodsChanged) {
        return {
          ...prev,
          authenticationMethods: authMethodsValue
        };
      }
      return prev;
    });
  }, []);
  const handleCollectInfoChange = (0, import_react.useCallback)((collectInfoValue) => {
    setInternalValue((prev) => {
      const hasCollectInfoChanged = JSON.stringify(prev.collectInfo) !== JSON.stringify(collectInfoValue);
      if (hasCollectInfoChanged) {
        return {
          ...prev,
          collectInfo: collectInfoValue
        };
      }
      return prev;
    });
  }, []);
  const transformToNewFormat = (value2, currentTab) => {
    var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
    const { pageSetting, authenticationMethods } = value2;
    const result = {};
    console.log("pageSetting data:", pageSetting);
    const shouldTransformPage = !currentTab || currentTab === "pageSetting";
    const shouldTransformAuth = !currentTab || currentTab === "authenticationMethods";
    if (shouldTransformPage) {
      result.page = {
        register: {
          background_image_url: ((_a2 = pageSetting == null ? void 0 : pageSetting.registerPage) == null ? void 0 : _a2.backgroundImage) || "",
          terms: ((_c = (_b2 = pageSetting == null ? void 0 : pageSetting.registerPage) == null ? void 0 : _b2.termsConditions) == null ? void 0 : _c.map((term) => ({
            name: {
              original: term.name.original || "",
              en: term.name.en || "",
              "zh-CN": term.name["zh-CN"] || "",
              "zh-HK": term.name["zh-HK"] || "",
              ja: term.name["ja"] || "",
              pt: term.name["pt"] || ""
            },
            url: term.url || ""
          }))) || []
        },
        login: {
          same_as_register: ((_d = pageSetting == null ? void 0 : pageSetting.loginPage) == null ? void 0 : _d.sameAsRegister) ?? true,
          background_image_url: ((_e = pageSetting == null ? void 0 : pageSetting.loginPage) == null ? void 0 : _e.sameAsRegister) ? null : ((_g = (_f = pageSetting == null ? void 0 : pageSetting.loginPage) == null ? void 0 : _f.settings) == null ? void 0 : _g.backgroundImage) || null,
          terms: ((_h = pageSetting == null ? void 0 : pageSetting.loginPage) == null ? void 0 : _h.sameAsRegister) ? [] : ((_k = (_j = (_i = pageSetting == null ? void 0 : pageSetting.loginPage) == null ? void 0 : _i.settings) == null ? void 0 : _j.termsConditions) == null ? void 0 : _k.map((term) => ({
            name: {
              original: term.name.original || "",
              en: term.name.en || "",
              "zh-CN": term.name["zh-CN"] || "",
              "zh-HK": term.name["zh-HK"] || "",
              ja: term.name["ja"] || "",
              pt: term.name["pt"] || ""
            },
            url: term.url || ""
          }))) || []
        }
      };
    }
    if (shouldTransformAuth) {
      const methods = (authenticationMethods == null ? void 0 : authenticationMethods.methods) || {};
      console.log("authenticationMethods:", authenticationMethods);
      console.log("methods config:", methods);
      result.auth = {
        mode: (authenticationMethods == null ? void 0 : authenticationMethods.mode) || "default",
        method: {
          email: {
            enabled: ((_l = methods.email) == null ? void 0 : _l.enabled) ?? true,
            sort: ((_m = methods.email) == null ? void 0 : _m.sort) ?? 0
          },
          phone: {
            enabled: ((_n = methods.phoneNumber) == null ? void 0 : _n.enabled) ?? true,
            sort: ((_o = methods.phoneNumber) == null ? void 0 : _o.sort) ?? 1
          },
          facebook: {
            enabled: ((_p = methods.facebook) == null ? void 0 : _p.enabled) ?? true,
            sort: ((_q = methods.facebook) == null ? void 0 : _q.sort) ?? 2
          },
          apple: {
            enabled: ((_r = methods.apple) == null ? void 0 : _r.enabled) ?? true,
            sort: ((_s = methods.apple) == null ? void 0 : _s.sort) ?? 3
          },
          guest: {
            enabled: ((_t = methods.guest) == null ? void 0 : _t.enabled) ?? false,
            sort: ((_u = methods.guest) == null ? void 0 : _u.sort) ?? 4
          }
        }
      };
    }
    return result;
  };
  const handleSave = async () => {
    var _a2;
    try {
      if (activeTab === "pageSetting" && pageSettingRef.current) {
        await pageSettingRef.current.validateFields();
      }
      const transformedValue = transformToNewFormat(internalValue, activeTab);
      const currentRegisterLogin = ((_a2 = channelData == null ? void 0 : channelData.metadata) == null ? void 0 : _a2.register_login) || {};
      const mergedData = {
        ...currentRegisterLogin,
        ...transformedValue
      };
      console.log("transformedValue", transformedValue, internalValue);
      console.log("mergedData", mergedData);
      saveData(mergedData);
    } catch (error) {
      console.error("表单校验失败:", error);
      import_antd.message.error(import_utils.locales.getText("channel.auth.setting.validation.error"));
    }
  };
  const allTabItems = (0, import_react.useMemo)(() => ({
    pageSetting: {
      key: "pageSetting",
      label: import_utils.locales.getText("channel.auth.setting.tab.pageSetting"),
      children: /* @__PURE__ */ import_react.default.createElement(
        import_PageSetting.default,
        {
          ref: pageSettingRef,
          value: internalValue.pageSetting,
          onChange: handlePageSettingChange,
          showRegisterPage,
          showImageUpload: false
        }
      )
    },
    authenticationMethods: {
      key: "authenticationMethods",
      label: import_utils.locales.getText("channel.auth.setting.tab.authenticationMethods"),
      children: /* @__PURE__ */ import_react.default.createElement(
        import_AuthenticationMethods.default,
        {
          value: internalValue.authenticationMethods,
          onChange: handleAuthenticationMethodsChange
        }
      )
    },
    collectInfo: {
      key: "collectInfo",
      label: import_utils.locales.getText("channel.auth.setting.tab.collectInfo"),
      children: /* @__PURE__ */ import_react.default.createElement(
        import_CollectInfo.default,
        {
          value: internalValue.collectInfo,
          onChange: handleCollectInfoChange
        }
      )
    }
  }), [internalValue.pageSetting, internalValue.authenticationMethods, internalValue.collectInfo, showRegisterPage, handlePageSettingChange, handleAuthenticationMethodsChange, handleCollectInfoChange]);
  const tabItems = (0, import_react.useMemo)(() => {
    return displayTabs.map((tabKey) => allTabItems[tabKey]);
  }, [displayTabs, allTabItems]);
  if (loading) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("channel-auth-setting", className), style: { ...style, display: "flex", justifyContent: "center", alignItems: "center", minHeight: "400px" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "large" }));
  }
  return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("onlineshopauth", className), style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "onlineshopauth-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 1, className: "onlineshopauth-title" }, import_utils.locales.getText("channel.auth.setting.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "onlineshopauth-description" }, import_utils.locales.getText("channel.auth.setting.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "onlineshopauth-tabs" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Tabs,
    {
      activeKey: activeTab,
      onChange: setActiveTab,
      items: tabItems
    }
  )), /* @__PURE__ */ import_react.default.createElement("div", { className: "onlineshopauth-footer" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: handleSave }, import_utils.locales.getText("channel.auth.setting.button.save"))));
};
var OnlineShopAuth_default = Onlineshopauth;
