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/ExtensionFormTabContent.tsx
var ExtensionFormTabContent_exports = {};
__export(ExtensionFormTabContent_exports, {
  default: () => ExtensionFormTabContent_default
});
module.exports = __toCommonJS(ExtensionFormTabContent_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_serve = require("../../serve");
var FORM_MESSAGE_TYPES = {
  LOADED: "form_loaded",
  RECORD_UPDATE_SUCCESS: "form_record_update_success",
  RECORD_UPDATE_FAILED: "form_record_update_failed",
  RECORD_CREATE_SUCCESS: "form_record_create_success",
  RECORD_CREATE_FAILED: "form_record_create_failed",
  CANCELED: "form_canceled",
  VALUES_CHANGE: "form_values_change",
  RESET: "form_reset"
};
var ExtensionFormTabContent = import_react.default.forwardRef(
  ({
    formId,
    domain,
    token,
    locale,
    tenantAccountId,
    onDirtyChange,
    onLoad,
    onCancel,
    getText,
    tabLabel,
    prefix,
    relationList,
    refreshRelationList
  }, ref) => {
    const iframeRef = (0, import_react.useRef)(null);
    const [loading, setLoading] = (0, import_react.useState)(true);
    const [relationRecord, setRelationRecord] = (0, import_react.useState)(null);
    const [isBinding, setIsBinding] = (0, import_react.useState)(false);
    const [bindModalVisible, setBindModalVisible] = (0, import_react.useState)(false);
    const [selectedRecordId, setSelectedRecordId] = (0, import_react.useState)(
      void 0
    );
    const [recordKeyword, setRecordKeyword] = (0, import_react.useState)("");
    const [modal, contextHolder] = import_antd.Modal.useModal();
    (0, import_react.useEffect)(() => {
      const item = (relationList || []).find((r) => (r == null ? void 0 : r.form_id) === formId) || null;
      setRelationRecord(item);
    }, [relationList, formId]);
    const {
      data: recordsData,
      loading: recordsLoading,
      run: runGetRecords
    } = (0, import_ahooks.useRequest)(
      async (kw) => {
        const res = await (0, import_serve.getFormRecords)({
          form_id: formId,
          keyword: kw || "",
          skip: 1,
          num: 50,
          with_relation_record_by_type: 1
        });
        return res;
      },
      { manual: true, debounceWait: 300 }
    );
    (0, import_react.useEffect)(() => {
      if (bindModalVisible) {
        runGetRecords(recordKeyword);
      }
    }, [bindModalVisible, recordKeyword, runGetRecords]);
    const _recordOptions = (0, import_react.useMemo)(() => {
      const options = ((recordsData == null ? void 0 : recordsData.list) || []).map((item) => {
        const disabled = Array.isArray(item == null ? void 0 : item.relation_record) && item.relation_record.length > 0 && item.form_record_id != (relationRecord == null ? void 0 : relationRecord.form_record_id);
        return {
          label: item.main_field,
          value: item.form_record_id,
          disabled
        };
      });
      const current = relationRecord == null ? void 0 : relationRecord.form_record;
      const hasCurrent = ((recordsData == null ? void 0 : recordsData.list) || []).some(
        (i) => i.form_record_id == (relationRecord == null ? void 0 : relationRecord.form_record_id)
      ) || options.some((o) => o.value === (relationRecord == null ? void 0 : relationRecord.form_record_id));
      if (current && !hasCurrent) {
        options.push({
          label: current.main_field,
          value: relationRecord.form_record_id,
          disabled: false
        });
      }
      return options;
    }, [recordsData, relationRecord]);
    const iframeUrl = import_react.default.useMemo(() => {
      const url = new URL(`https://${domain}/admin/form/view/${formId}`);
      url.searchParams.set("scene", "1005");
      url.searchParams.set("locale", locale);
      url.searchParams.set("token", `bearer ${token}`);
      url.searchParams.set("footer", "fixed");
      url.searchParams.set("mode", "edit");
      if (relationRecord == null ? void 0 : relationRecord.form_record_id) {
        url.searchParams.set(
          "form_record_id",
          String(relationRecord == null ? void 0 : relationRecord.form_record_id)
        );
      }
      return url.toString();
    }, [domain, formId, locale, token, relationRecord == null ? void 0 : relationRecord.form_record_id]);
    const upsertRelationRecord = (0, import_react.useCallback)(
      async (rid) => {
        if (!rid || !tenantAccountId) {
          return;
        }
        try {
          setIsBinding(true);
          if (!relationRecord) {
            await (0, import_serve.bindRelationRecord)({
              relation_type: "tenant_account",
              relation_id: tenantAccountId,
              form_id: formId,
              form_record_id: rid
            });
          } else if (relationRecord.form_record_id !== rid) {
            await (0, import_serve.updateRelationRecord)(relationRecord.id, {
              form_record_id: rid
            });
          }
          await (refreshRelationList == null ? void 0 : refreshRelationList());
        } catch (e) {
        } finally {
          setIsBinding(false);
        }
      },
      [tenantAccountId, formId, relationRecord, refreshRelationList]
    );
    const syncRelationRecord = (0, import_react.useCallback)(
      async (rid) => {
        if (!rid) return;
        await upsertRelationRecord(rid);
      },
      [upsertRelationRecord]
    );
    const handleMessage = (0, import_react.useCallback)(
      (event) => {
        const expectedOrigin = new URL(iframeUrl).origin;
        if (event.origin !== expectedOrigin) {
          return;
        }
        try {
          const msg = typeof event.data === "string" ? JSON.parse(event.data) : event.data;
          const data = msg == null ? void 0 : msg.data;
          if ((data == null ? void 0 : data.form_id) !== formId) return;
          switch (msg.type) {
            case FORM_MESSAGE_TYPES.VALUES_CHANGE:
              onDirtyChange == null ? void 0 : onDirtyChange(true);
              break;
            case FORM_MESSAGE_TYPES.LOADED:
              setLoading(false);
              onLoad == null ? void 0 : onLoad();
              break;
            case FORM_MESSAGE_TYPES.RECORD_CREATE_SUCCESS:
            case FORM_MESSAGE_TYPES.RECORD_UPDATE_SUCCESS:
              onDirtyChange == null ? void 0 : onDirtyChange(false);
              syncRelationRecord(data == null ? void 0 : data.form_record_id);
              break;
            case FORM_MESSAGE_TYPES.CANCELED:
              onCancel == null ? void 0 : onCancel();
              break;
            default:
              break;
          }
        } catch (error) {
        }
      },
      [iframeUrl, onDirtyChange, onLoad, onCancel, formId, syncRelationRecord]
    );
    (0, import_react.useEffect)(() => {
      window.addEventListener("message", handleMessage);
      return () => {
        window.removeEventListener("message", handleMessage);
      };
    }, [handleMessage]);
    const sendMessage = (0, import_react.useCallback)(
      (message) => {
        var _a;
        if ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) {
          iframeRef.current.contentWindow.postMessage(
            JSON.stringify(message),
            new URL(iframeUrl).origin
          );
        }
      },
      [iframeUrl]
    );
    (0, import_react.useImperativeHandle)(
      ref,
      () => ({
        reset: () => {
          onDirtyChange == null ? void 0 : onDirtyChange(false);
          sendMessage({
            type: FORM_MESSAGE_TYPES.RESET,
            data: { form_id: formId }
          });
        }
      }),
      [formId, onDirtyChange, sendMessage]
    );
    const handleIframeLoad = (0, import_react.useCallback)(() => {
      setTimeout(() => {
        setLoading(false);
      }, 1e3);
    }, []);
    const openBindModal = (0, import_react.useCallback)(() => {
      setBindModalVisible(true);
      setSelectedRecordId(relationRecord == null ? void 0 : relationRecord.form_record_id);
      setRecordKeyword("");
    }, [relationRecord]);
    const openBindWithConfirm = (0, import_react.useCallback)(() => {
      if (relationRecord) {
        modal.confirm({
          title: getText("pisell2.saas.team-members.bind.confirm.rebind-title"),
          content: getText(
            "pisell2.saas.team-members.bind.confirm.rebind-content"
          ),
          okText: getText("pisell2.saas.team-members.bind.modal.ok"),
          cancelText: getText("pisell2.saas.team-members.bind.modal.cancel"),
          onOk: () => openBindModal()
        });
        return;
      }
      openBindModal();
    }, [relationRecord, getText, openBindModal]);
    const handleBindConfirm = (0, import_react.useCallback)(async () => {
      if (!tenantAccountId || !selectedRecordId) return;
      if (selectedRecordId == (relationRecord == null ? void 0 : relationRecord.form_record_id)) return;
      await upsertRelationRecord(selectedRecordId);
      setBindModalVisible(false);
    }, [
      tenantAccountId,
      selectedRecordId,
      relationRecord == null ? void 0 : relationRecord.form_record_id,
      upsertRelationRecord
    ]);
    const handleUnbind = (0, import_react.useCallback)(() => {
      if (!relationRecord) return;
      modal.confirm({
        title: getText("pisell2.saas.team-members.bind.confirm.unbind-title"),
        content: getText("pisell2.saas.team-members.bind.confirm.unbind-content"),
        okText: getText("pisell2.saas.team-members.drawer.save"),
        cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
        onOk: async () => {
          setIsBinding(true);
          try {
            await (0, import_serve.unbindRelationRecord)(relationRecord.id);
            setRelationRecord(null);
            await (refreshRelationList == null ? void 0 : refreshRelationList());
          } catch (e) {
          }
          setIsBinding(false);
        }
      });
    }, [relationRecord, getText, refreshRelationList]);
    const menuItems = relationRecord ? [
      {
        key: "bind",
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-link-01", size: 16 }),
        label: getText("pisell2.saas.team-members.bind.menu.bind"),
        onClick: openBindWithConfirm
      },
      {
        key: "unbind",
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-link-broken-02", size: 16 }),
        label: getText("pisell2.saas.team-members.bind.menu.unbind"),
        onClick: handleUnbind
      }
    ] : [
      {
        key: "bind",
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-link-01", size: 16 }),
        label: getText("pisell2.saas.team-members.bind.menu.bind"),
        onClick: openBindWithConfirm
      }
    ];
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_extension-tab-content` }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_section-header` }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_section-header-title` }, getText("pisell2.saas.team-members.tab.extended-fields").replace(
      "{roleName}",
      tabLabel
    )), /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_section-header-subtitle` }, getText(
      "pisell2.saas.team-members.form.extend-fields-subtitle"
    ).replace("{roleName}", tabLabel)), /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_section-header-actions` }, /* @__PURE__ */ import_react.default.createElement(import_materials.Dropdown, { menu: { items: menuItems }, trigger: ["click"] }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "text",
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-dots-vertical", size: 18 })
      }
    )))), /* @__PURE__ */ import_react.default.createElement("div", { className: "extension-form-iframe-container" }, (loading || isBinding) && /* @__PURE__ */ import_react.default.createElement("div", { className: "extension-form-iframe-loading" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "large" })), /* @__PURE__ */ import_react.default.createElement(
      "iframe",
      {
        ref: iframeRef,
        src: iframeUrl,
        title: `Extension Form ${formId}`,
        className: "extension-form-iframe",
        onLoad: handleIframeLoad,
        style: {
          width: "100%",
          height: "100%",
          border: "none",
          opacity: loading ? 0 : 1,
          transition: "opacity 0.3s ease"
        }
      }
    )), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Modal,
      {
        open: bindModalVisible,
        title: getText("pisell2.saas.team-members.bind.modal.title"),
        onOk: handleBindConfirm,
        onCancel: () => {
          setBindModalVisible(false);
          setRecordKeyword("");
        },
        okText: getText("pisell2.saas.team-members.bind.modal.ok"),
        cancelText: getText("pisell2.saas.team-members.bind.modal.cancel"),
        styles: {
          header: {
            padding: "0px 0px 8px 0px"
          }
        },
        okButtonProps: {
          disabled: !selectedRecordId || selectedRecordId === (relationRecord == null ? void 0 : relationRecord.form_record_id)
        }
      },
      /* @__PURE__ */ import_react.default.createElement("div", { style: { marginBottom: 16, color: "#7a7d80" } }, getText("pisell2.saas.team-members.bind.modal.description")),
      /* @__PURE__ */ import_react.default.createElement("div", { className: `${prefix}_bind-modal-label` }, getText("pisell2.saas.team-members.bind.modal.select-record")),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            display: "flex"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.Select,
          {
            size: "large",
            style: { flex: 1 },
            placeholder: getText(
              "pisell2.saas.team-members.bind.modal.placeholder"
            ),
            allowClear: true,
            loading: recordsLoading,
            value: selectedRecordId,
            onChange: (val) => setSelectedRecordId(val),
            showSearch: true,
            filterOption: false,
            onSearch: (kw) => setRecordKeyword(kw),
            options: _recordOptions
          }
        )
      )
    )), /* @__PURE__ */ import_react.default.createElement(import_antd.ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
  }
);
var ExtensionFormTabContent_default = ExtensionFormTabContent;
