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/saasTeamMembers/components/MemberDrawer/index.tsx
var MemberDrawer_exports = {};
__export(MemberDrawer_exports, {
  default: () => MemberDrawer_default
});
module.exports = __toCommonJS(MemberDrawer_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_lodash = require("lodash");
var import_serve = require("../../serve");
var import_ExtensionFormTabContent = __toESM(require("./ExtensionFormTabContent"));
var import_index = require("./index.less");
var AntdDrawer = import_materials.Drawer;
var AntdButton = import_materials.Button;
var isValueEqual = (a, b) => {
  if (a === "" && b == null || a == null && b === "") return true;
  if (Array.isArray(a) && Array.isArray(b)) {
    return (0, import_lodash.isEqual)((0, import_lodash.sortBy)(a), (0, import_lodash.sortBy)(b));
  }
  return (0, import_lodash.isEqual)(a, b);
};
var PREFIX = "saas-member-drawer";
var MemberDrawer = ({
  visible,
  mode,
  currentMember,
  roleOptions,
  roles,
  onClose,
  onSubmit,
  loading,
  getText,
  getLocaleText,
  tenantId,
  mypisellData,
  locale
}) => {
  const [form] = import_antd.Form.useForm();
  const [activeTab, setActiveTab] = (0, import_react.useState)("basic");
  const [selectedRoleIds, setSelectedRoleIds] = (0, import_react.useState)([]);
  const [isEmailRegistered, setIsEmailRegistered] = (0, import_react.useState)(false);
  const [checkingEmail, setCheckingEmail] = (0, import_react.useState)(false);
  const [isBasicFormDirty, setIsBasicFormDirty] = (0, import_react.useState)(false);
  const [iframeDirtyStates, setIframeDirtyStates] = (0, import_react.useState)({});
  const extensionTabRefs = (0, import_react.useRef)(
    {}
  );
  const initialValuesRef = (0, import_react.useRef)(null);
  const [modal, contextHolder] = import_antd.Modal.useModal();
  const isFormDirty = (0, import_react.useMemo)(() => {
    const hasIframeDirty = Object.values(iframeDirtyStates).some(Boolean);
    return isBasicFormDirty || hasIframeDirty;
  }, [isBasicFormDirty, iframeDirtyStates]);
  const handleIframeDirtyChange = (0, import_react.useCallback)(
    (formId, isDirty) => {
      setIframeDirtyStates((prev) => ({
        ...prev,
        [formId]: isDirty
      }));
    },
    []
  );
  const checkFormDirty = (0, import_react.useCallback)(() => {
    if (!initialValuesRef.current) return;
    const currentValues = form.getFieldsValue();
    const initialValues = initialValuesRef.current;
    const fieldsToCompare = [
      "nickname",
      "member_id",
      "status",
      "tenant_role_ids",
      "email",
      "password",
      "first_name",
      "last_name",
      "phone"
    ];
    for (const field of fieldsToCompare) {
      if (!isValueEqual(currentValues[field], initialValues[field])) {
        setIsBasicFormDirty(true);
        return;
      }
    }
    setIsBasicFormDirty(false);
  }, [form]);
  (0, import_react.useEffect)(() => {
    var _a, _b, _c, _d, _e;
    if (visible) {
      let values;
      if (mode === "edit" && currentMember) {
        const roleIds = ((_a = currentMember.roles) == null ? void 0 : _a.map((r) => r.id)) || [];
        values = {
          nickname: currentMember.nickname || "",
          member_id: currentMember.member_id || "",
          status: currentMember.status || "active",
          tenant_role_ids: roleIds,
          email: ((_b = currentMember.account) == null ? void 0 : _b.email) || "",
          first_name: ((_c = currentMember.account) == null ? void 0 : _c.first_name) || "",
          last_name: ((_d = currentMember.account) == null ? void 0 : _d.last_name) || "",
          phone: ((_e = currentMember.account) == null ? void 0 : _e.phone) || ""
        };
        form.setFieldsValue(values);
        setSelectedRoleIds(roleIds);
        setIsEmailRegistered(false);
      } else {
        values = {
          nickname: "",
          member_id: "",
          status: "active",
          tenant_role_ids: [],
          email: "",
          password: "",
          first_name: "",
          last_name: "",
          phone: ""
        };
        form.resetFields();
        form.setFieldsValue(values);
        setSelectedRoleIds([]);
        setIsEmailRegistered(false);
      }
      initialValuesRef.current = values;
      setIsBasicFormDirty(false);
      setIframeDirtyStates({});
      setActiveTab("basic");
    }
  }, [visible, mode, currentMember, form]);
  const handleFormValuesChange = (0, import_react.useCallback)(() => {
    setTimeout(checkFormDirty, 0);
  }, [checkFormDirty]);
  const { run: checkEmail } = (0, import_ahooks.useDebounceFn)(
    async (email) => {
      if (!email || mode === "edit") {
        setIsEmailRegistered(false);
        setCheckingEmail(false);
        return;
      }
      setCheckingEmail(true);
      try {
        const account = await (0, import_serve.getAccountByEmail)({
          filter: JSON.stringify({
            tenant_id: tenantId,
            email
          })
        });
        if (account == null ? void 0 : account.id) {
          const { first_name, last_name, phone } = account;
          form.setFieldsValue({
            first_name,
            last_name,
            phone
          });
          setIsEmailRegistered(true);
        } else {
          setIsEmailRegistered(false);
        }
      } catch (error) {
      } finally {
        setCheckingEmail(false);
      }
    },
    { wait: 500 }
  );
  const handleEmailChange = (0, import_react.useCallback)(
    (e) => {
      const email = e.target.value;
      if (mode === "create") {
        checkEmail(email);
      }
    },
    [mode, checkEmail]
  );
  const selectedRoles = (0, import_react.useMemo)(() => {
    return roles.filter((role) => selectedRoleIds.includes(role.id));
  }, [roles, selectedRoleIds]);
  const extensionFormIds = (0, import_react.useMemo)(() => {
    const formIds = /* @__PURE__ */ new Set();
    selectedRoles.forEach((role) => {
      var _a;
      if ((_a = role.metadata) == null ? void 0 : _a.extension_form_id) {
        formIds.add(role.metadata.extension_form_id);
      }
    });
    return Array.from(formIds);
  }, [selectedRoles]);
  const extensionFormRoles = (0, import_react.useMemo)(() => {
    const formRoles = {};
    selectedRoles.forEach((role) => {
      var _a;
      const formId = (_a = role.metadata) == null ? void 0 : _a.extension_form_id;
      if (formId) {
        if (!formRoles[formId]) {
          formRoles[formId] = [];
        }
        formRoles[formId].push(getLocaleText(role.name));
      }
    });
    return formRoles;
  }, [selectedRoles, getLocaleText]);
  const prevExtensionFormRolesRef = (0, import_react.useRef)({});
  const prevAccountIdRef = (0, import_react.useRef)(void 0);
  const {
    data: relationList,
    run: runGetRelationList,
    refresh: refreshRelationList
  } = (0, import_ahooks.useRequest)(
    async () => {
      if (!(currentMember == null ? void 0 : currentMember.id)) return [];
      if (extensionFormIds.length === 0) return [];
      const data = await (0, import_serve.getRelationRecords)({
        relation_type: "tenant_account",
        relation_id: currentMember.id,
        form_id: extensionFormIds
      });
      return Array.isArray(data) ? data : [];
    },
    { manual: true }
  );
  (0, import_react.useEffect)(() => {
    if ((currentMember == null ? void 0 : currentMember.id) !== prevAccountIdRef.current) {
      prevExtensionFormRolesRef.current = {};
      prevAccountIdRef.current = currentMember == null ? void 0 : currentMember.id;
    }
  }, [currentMember == null ? void 0 : currentMember.id]);
  (0, import_react.useEffect)(() => {
    if (!visible) return;
    if (!(currentMember == null ? void 0 : currentMember.id)) return;
    const prev = prevExtensionFormRolesRef.current || {};
    const curr = extensionFormRoles || {};
    const normalize = (obj) => {
      const result = {};
      Object.keys(obj).forEach((key) => {
        const k = Number(key);
        result[k] = (0, import_lodash.sortBy)(obj[k] || []);
      });
      return result;
    };
    const changed = !(0, import_lodash.isEqual)(normalize(prev), normalize(curr));
    if (changed) {
      runGetRelationList();
    }
    prevExtensionFormRolesRef.current = curr;
  }, [
    visible,
    currentMember == null ? void 0 : currentMember.account_id,
    extensionFormRoles,
    runGetRelationList
  ]);
  const handleTabChange = (0, import_react.useCallback)(
    (key) => {
      const currentTabDirty = activeTab === "basic" ? isBasicFormDirty : iframeDirtyStates[parseInt(activeTab.replace("extension-", ""))] || false;
      if (currentTabDirty) {
        modal.confirm({
          title: getText("pisell2.saas.team-members.confirm.unsaved-title"),
          content: getText("pisell2.saas.team-members.confirm.unsaved-content"),
          okText: getText("pisell2.saas.team-members.confirm.leave"),
          cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
          onOk: () => {
            var _a, _b;
            if (activeTab === "basic") {
              setIsBasicFormDirty(false);
              if (initialValuesRef.current) {
                form.setFieldsValue(initialValuesRef.current);
              }
            } else {
              const formId = parseInt(activeTab.replace("extension-", ""));
              (_b = (_a = extensionTabRefs.current[formId]) == null ? void 0 : _a.reset) == null ? void 0 : _b.call(_a);
              setIframeDirtyStates((prev) => ({
                ...prev,
                [formId]: false
              }));
            }
            setActiveTab(key);
          }
        });
      } else {
        setActiveTab(key);
      }
    },
    [activeTab, isBasicFormDirty, iframeDirtyStates, getText, form]
  );
  const handleClose = (0, import_react.useCallback)(() => {
    if (isFormDirty) {
      modal.confirm({
        title: getText("pisell2.saas.team-members.confirm.unsaved-title"),
        content: getText("pisell2.saas.team-members.confirm.unsaved-content"),
        okText: getText("pisell2.saas.team-members.confirm.leave"),
        cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
        onOk: () => {
          setIsBasicFormDirty(false);
          setIframeDirtyStates({});
          onClose();
        }
      });
    } else {
      onClose();
    }
  }, [isFormDirty, onClose, getText]);
  const handleBasicInfoSubmit = (0, import_react.useCallback)(async () => {
    try {
      const values = await form.validateFields();
      await onSubmit(values);
      setSelectedRoleIds((values == null ? void 0 : values.tenant_role_ids) || []);
      setIsBasicFormDirty(false);
      initialValuesRef.current = form.getFieldsValue();
    } catch (error) {
      console.error("Form validation failed:", error);
    }
  }, [form, onSubmit]);
  const isFounder = mode === "edit" && (currentMember == null ? void 0 : currentMember.type) === "founder";
  const renderBasicInfoTab = () => /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}_tab-content` }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form,
    {
      form,
      layout: "vertical",
      size: "large",
      onValuesChange: handleFormValuesChange,
      autoComplete: "false"
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ import_react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText("pisell2.saas.team-members.form.section.team-member-info")), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "nickname",
        label: getText("pisell2.saas.team-members.form.name"),
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.team-members.form.name-required"
            )
          }
        ],
        help: getText("pisell2.saas.team-members.form.name-hint")
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Input,
        {
          placeholder: getText(
            "pisell2.saas.team-members.form.name-placeholder"
          )
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "member_id",
        label: getText("pisell2.saas.team-members.form.member-id"),
        help: getText("pisell2.saas.team-members.form.member-id-hint")
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Input,
        {
          placeholder: getText(
            "pisell2.saas.team-members.form.member-id-placeholder"
          )
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "status",
        label: getText("pisell2.saas.team-members.form.status"),
        initialValue: "active",
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.team-members.form.status-required"
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.Select, { disabled: isFounder }, /* @__PURE__ */ import_react.default.createElement(import_materials.Select.Option, { value: "active" }, getText("pisell2.saas.team-members.status.active")), /* @__PURE__ */ import_react.default.createElement(import_materials.Select.Option, { value: "inactive" }, getText("pisell2.saas.team-members.status.inactive")))
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "tenant_role_ids",
        label: getText("pisell2.saas.team-members.form.roles"),
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.team-members.form.roles-required"
            )
          }
        ],
        extra: isFounder ? /* @__PURE__ */ import_react.default.createElement(
          import_materials.Alert,
          {
            message: getText("pisell2.saas.team-members.founder-notice"),
            type: "info",
            showIcon: true,
            icon: /* @__PURE__ */ import_react.default.createElement(
              import_materials.Icon,
              {
                type: "pisell2-info-circle",
                size: 16,
                color: "#7f8694",
                style: {
                  marginTop: 2,
                  alignSelf: "flex-start"
                }
              }
            ),
            className: `${PREFIX}_founder-notice`
          }
        ) : getText("pisell2.saas.team-members.form.roles-hint")
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Select,
        {
          mode: "multiple",
          placeholder: getText(
            "pisell2.saas.team-members.form.roles-placeholder"
          ),
          options: roleOptions
        }
      )
    )),
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ import_react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText(
      "pisell2.saas.team-members.form.section.account-email-login"
    )), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "email",
        label: getText("pisell2.saas.team-members.form.email"),
        rules: mode === "create" ? [
          {
            required: true,
            message: getText(
              "pisell2.saas.team-members.form.email-required"
            )
          },
          {
            type: "email",
            message: getText(
              "pisell2.saas.team-members.form.email-invalid"
            )
          }
        ] : [],
        extra: mode === "create" && isEmailRegistered && /* @__PURE__ */ import_react.default.createElement(
          import_materials.Alert,
          {
            type: "info",
            showIcon: true,
            icon: /* @__PURE__ */ import_react.default.createElement(
              import_materials.Icon,
              {
                type: "pisell2-info-circle",
                size: 16,
                color: "#7f8694"
              }
            ),
            className: `${PREFIX}_email-registered-alert`,
            message: getText(
              "pisell2.saas.team-members.form.email-registered"
            )
          }
        )
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Input,
        {
          placeholder: getText(
            "pisell2.saas.team-members.form.email-placeholder"
          ),
          disabled: mode === "edit",
          onChange: handleEmailChange,
          prefix: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-mail-01", size: 18, color: "#98A2B3" })
        }
      )
    ), mode === "create" && !isEmailRegistered && /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "password",
        label: getText("pisell2.saas.team-members.form.password"),
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.team-members.form.password-required"
            )
          },
          {
            // 至少6个字符且不包含空格
            pattern: /^\S{6,}$/,
            message: getText(
              "pisell2.saas.team-members.form.password-invalid"
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Input.Password,
        {
          placeholder: getText(
            "pisell2.saas.team-members.form.password-placeholder"
          )
        }
      )
    )),
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ import_react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText("pisell2.saas.team-members.form.section.personal-info")), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 16
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          name: "first_name",
          label: getText("pisell2.saas.team-members.form.first-name")
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.Input,
          {
            placeholder: getText(
              "pisell2.saas.team-members.form.first-name-placeholder"
            ),
            disabled: mode === "edit" || isEmailRegistered
          }
        )
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          name: "last_name",
          label: getText("pisell2.saas.team-members.form.last-name")
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.Input,
          {
            placeholder: getText(
              "pisell2.saas.team-members.form.last-name-placeholder"
            ),
            disabled: mode === "edit" || isEmailRegistered
          }
        )
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_materials.FormItemInput.Phone,
      {
        type: "tel",
        name: "phone",
        label: getText("pisell2.saas.team-members.form.mobile"),
        disabled: mode === "edit" || isEmailRegistered
      }
    ))
  ));
  const renderExtensionFormTab = (formId) => {
    const roleNames = extensionFormRoles[formId] || [];
    const tabLabel = roleNames.join(" / ");
    return /* @__PURE__ */ import_react.default.createElement(
      import_ExtensionFormTabContent.default,
      {
        ref: (instance) => {
          extensionTabRefs.current[formId] = instance;
        },
        formId,
        domain: (mypisellData == null ? void 0 : mypisellData.domain) || "",
        token: (mypisellData == null ? void 0 : mypisellData.account_token) || "",
        locale,
        tenantAccountId: currentMember == null ? void 0 : currentMember.id,
        onDirtyChange: (isDirty) => handleIframeDirtyChange(formId, isDirty),
        onCancel: onClose,
        getText,
        tabLabel,
        prefix: PREFIX,
        relationList: relationList || [],
        refreshRelationList: runGetRelationList
      }
    );
  };
  const tabItems = (0, import_react.useMemo)(() => {
    const items = [
      {
        key: "basic",
        label: getText("pisell2.saas.team-members.tab.basic-info"),
        children: renderBasicInfoTab()
      }
    ];
    if (mode === "edit" && selectedRoleIds.length > 0) {
      extensionFormIds.forEach((formId) => {
        const roleNames = extensionFormRoles[formId] || [];
        const tabLabel = roleNames.join(" / ");
        items.push({
          key: `extension-${formId}`,
          label: tabLabel,
          children: renderExtensionFormTab(formId)
        });
      });
    }
    return items;
  }, [
    mode,
    selectedRoleIds,
    extensionFormIds,
    extensionFormRoles,
    isEmailRegistered,
    checkingEmail,
    loading,
    relationList,
    refreshRelationList
  ]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    AntdDrawer,
    {
      title: mode === "create" ? getText("pisell2.saas.team-members.drawer.create-title") : getText("pisell2.saas.team-members.drawer.edit-title"),
      open: visible,
      onClose: handleClose,
      width: 600,
      className: "saas-member-drawer",
      headerStyle: {
        borderBottom: "2px solid #f0f0f0"
      },
      destroyOnHidden: true,
      footer: activeTab === "basic" ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}_footer` }, /* @__PURE__ */ import_react.default.createElement(AntdButton, { onClick: handleClose, style: { marginRight: 8 } }, getText("pisell2.saas.team-members.drawer.cancel")), /* @__PURE__ */ import_react.default.createElement(
        AntdButton,
        {
          type: "primary",
          onClick: handleBasicInfoSubmit,
          loading,
          disabled: checkingEmail || mode === "edit" && !isBasicFormDirty
        },
        getText("pisell2.saas.team-members.drawer.save")
      )) : false
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Tabs,
      {
        activeKey: activeTab,
        onChange: handleTabChange,
        items: tabItems,
        className: `${PREFIX}_tabs`
      }
    )
  ), contextHolder);
};
var MemberDrawer_default = MemberDrawer;
