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/systemSettings/registry/components/ItemModal.tsx
var ItemModal_exports = {};
__export(ItemModal_exports, {
  default: () => ItemModal_default
});
module.exports = __toCommonJS(ItemModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_typeValidation = require("../utils/typeValidation");
var import_validators = require("../utils/validators");
var import_OptionDataSource = __toESM(require("./OptionDataSource"));
var import_serve = require("./DataSourceTreeSelect/serve");
var { Option } = import_antd.Select;
var { TextArea } = import_antd.Input;
var scopeOptions = [
  { value: "system", label: "registry.scope.systemDefault" },
  { value: "saas", label: "registry.scope.saasDefault" },
  { value: "organization", label: "registry.scope.organization" },
  { value: "business", label: "registry.scope.business" },
  { value: "channel", label: "registry.scope.channel" },
  { value: "board", label: "registry.scope.board" }
];
var fieldTypeOptions = [
  { value: "string", label: "String" },
  { value: "integer", label: "Integer" },
  { value: "float", label: "Float" },
  { value: "boolean", label: "Boolean" },
  { value: "array", label: "Array" }
];
var interfaceTypeOptions = {
  string: [
    { value: "Input", label: "单行文本输入框" },
    { value: "Input.TextArea", label: "多行文本输入框" },
    { value: "Select", label: "单选下拉框" }
  ],
  integer: [{ value: "InputNumber", label: "数字输入框（整数模式）" }],
  float: [{ value: "InputNumber", label: "数字输入框（支持小数）" }],
  boolean: [
    { value: "Checkbox", label: "复选框" },
    { value: "Switch", label: "开关组件" }
  ],
  array: [
    { value: "Select", label: "多选下拉框" },
    { value: "Input.JSON", label: "JSON编辑器" },
    { value: "RecordListWrapper", label: "记录列表包装器" },
    { value: "Translation", label: "多语言输入框" }
  ]
};
var ItemModal = ({
  open,
  type,
  data,
  section,
  onOk,
  onCancel
}) => {
  const [form] = import_antd.Form.useForm();
  const [selectedFieldType, setSelectedFieldType] = (0, import_react.useState)("string");
  const [selectedScopes, setSelectedScopes] = (0, import_react.useState)([]);
  const [showSystemDefaultValue, setShowSystemDefaultValue] = (0, import_react.useState)(false);
  const _interfaceType = import_antd.Form.useWatch("interfaceType", form);
  const [treeDataSource, setTreeDataSource] = (0, import_react.useState)([]);
  (0, import_react.useEffect)(() => {
    (0, import_serve.getAllDataSources)().then((data2) => setTreeDataSource(data2));
  }, []);
  const renderDefaultValueInput = (fieldType) => {
    switch (fieldType) {
      case "string":
        return /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { placeholder: "请输入默认值", allowClear: true });
      case "integer":
        return /* @__PURE__ */ import_react.default.createElement(
          import_antd.InputNumber,
          {
            placeholder: "请输入整数",
            style: { width: "100%" },
            precision: 0,
            allowClear: true
          }
        );
      case "float":
        return /* @__PURE__ */ import_react.default.createElement(
          import_antd.InputNumber,
          {
            placeholder: "请输入数字",
            style: { width: "100%" },
            allowClear: true
          }
        );
      case "boolean":
        return /* @__PURE__ */ import_react.default.createElement(import_antd.Select, { placeholder: "请选择布尔值", allowClear: true }, /* @__PURE__ */ import_react.default.createElement(Option, { value: "true" }, "true"), /* @__PURE__ */ import_react.default.createElement(Option, { value: "false" }, "false"));
      case "array":
        return /* @__PURE__ */ import_react.default.createElement(
          TextArea,
          {
            placeholder: "请输入JSON对象或数组，例如：{} 或 []",
            rows: 4,
            allowClear: true
          }
        );
      default:
        return /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { placeholder: "请输入默认值", allowClear: true });
    }
  };
  (0, import_react.useEffect)(() => {
    if (open) {
      if (type === "edit" && data) {
        const getName = (nameField) => {
          if (typeof nameField === "string") return nameField;
          if (nameField && typeof nameField === "object") {
            return nameField["zh-CN"] || nameField.original || nameField.en || "";
          }
          return "";
        };
        const getDescription = (descField) => {
          if (typeof descField === "string") {
            return {
              en: "",
              "zh-CN": "",
              "zh-HK": "",
              "ja": "",
              "pt": "",
              original: descField
            };
          }
          if (descField && typeof descField === "object") {
            return {
              en: descField.en || "",
              "zh-CN": descField["zh-CN"] || "",
              "zh-HK": descField["zh-HK"] || "",
              "ja": descField["ja"] || "",
              "pt": descField["pt"] || "",
              original: descField.original || descField["zh-CN"] || descField.en || ""
            };
          }
          return {
            en: "",
            "zh-CN": "",
            "zh-HK": "",
            "ja": "",
            "pt": "",
            original: ""
          };
        };
        const formData = {
          name: getDescription(data.title),
          key: data.key || data.code,
          fieldType: data.type || data.fieldType || "string",
          interfaceType: data.interface || data.interfaceType,
          scopes: data.scopes || [],
          description: getDescription(data.description),
          default: data.default
        };
        const schema = (data == null ? void 0 : data.schema) || {};
        const xDataSource = schema["x-data-source"] || {};
        if (Object.keys(xDataSource).length > 0) {
          const extraParams = xDataSource == null ? void 0 : xDataSource.extraParams;
          if (!extraParams) {
            xDataSource.extraParams = "";
          } else if (typeof extraParams === "string") {
            xDataSource.extraParams = extraParams;
          } else if (typeof extraParams === "object") {
            xDataSource.extraParams = JSON.stringify(extraParams, null, 2);
          }
          formData.xDataSource = xDataSource;
        } else {
          formData.xDataSource = { type: "default", options: [] };
        }
        const xRecordSchema = schema["x-record-schema"];
        if (!xRecordSchema) {
          formData.xRecordSchema = "";
        } else if (typeof xRecordSchema === "string") {
          formData.xRecordSchema = xRecordSchema;
        } else if (typeof xRecordSchema === "object") {
          formData.xRecordSchema = JSON.stringify(xRecordSchema, null, 2);
        }
        const xCustomUiSchema = schema["x-custom-ui-schema"];
        if (!xCustomUiSchema) {
          formData.xCustomUiSchema = "";
        } else if (typeof xCustomUiSchema === "string") {
          formData.uiSchema = xCustomUiSchema;
        } else if (typeof xCustomUiSchema === "object") {
          formData.uiSchema = JSON.stringify(xCustomUiSchema, null, 2);
        }
        form.setFieldsValue(formData);
        setSelectedFieldType(formData.fieldType);
        setSelectedScopes(formData.scopes);
        setShowSystemDefaultValue(formData.scopes.includes("system"));
      } else {
        form.resetFields();
        const defaultValues = {
          name: {
            en: "",
            "zh-CN": "",
            "zh-HK": "",
            "ja": "",
            "pt": "",
            original: ""
          },
          description: {
            en: "",
            "zh-CN": "",
            "zh-HK": "",
            "ja": "",
            "pt": "",
            original: ""
          },
          fieldType: "string",
          scopes: ["string"],
          // 为key字段添加section code前缀作为默认值
          key: (section == null ? void 0 : section.code) ? `${section.code}.` : "",
          xDataSource: { type: "default", options: [] },
          xRecordSchema: ""
        };
        form.setFieldsValue(defaultValues);
        setSelectedFieldType("string");
        setSelectedScopes(["string"]);
      }
    }
  }, [open, type, data, form]);
  const handleFieldTypeChange = (value) => {
    setSelectedFieldType(value);
    form.setFieldsValue({ interfaceType: void 0 });
    form.setFieldsValue({ default: void 0 });
    form.setFieldsValue({ xDataSource: { type: "default", options: [] } });
    form.setFieldsValue({ xRecordSchema: "" });
    form.validateFields(["default"]).catch(() => {
    });
  };
  const handleInterfaceTypeChange = (value) => {
    form.setFieldsValue({
      xDataSource: { type: "default", options: [] },
      xRecordSchema: ""
    });
  };
  const handleScopesChange = (values) => {
    const stringValues = values.map((v) => String(v));
    setSelectedScopes(stringValues);
    console.log("stringValues", stringValues);
    setShowSystemDefaultValue(stringValues.includes("system"));
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (values.default !== void 0 && values.default !== null && values.default !== "") {
        if (values.fieldType === "integer" || values.fieldType === "float") {
          if (typeof values.default !== "number") {
            const validation = (0, import_typeValidation.validateDefaultValue)(
              values.fieldType,
              values.default
            );
            if (!validation.isValid) {
              throw new Error(`默认值验证失败: ${validation.error}`);
            }
            values.default = (0, import_typeValidation.parseDefaultValue)(
              values.fieldType,
              values.default
            );
          }
        } else {
          const validation = (0, import_typeValidation.validateDefaultValue)(
            values.fieldType,
            values.default
          );
          if (!validation.isValid) {
            throw new Error(`默认值验证失败: ${validation.error}`);
          }
          values.default = (0, import_typeValidation.parseDefaultValue)(values.fieldType, values.default);
        }
      } else {
        values.default = null;
      }
      let schema = {};
      if (values == null ? void 0 : values.xCustomUiSchema) {
        try {
          schema["x-custom-ui-schema"] = JSON.parse(values.xCustomUiSchema);
        } catch (error) {
          throw new Error(
            `UI Schema格式错误: ${error instanceof Error ? error.message : "未知错误"}`
          );
        }
      }
      const needUseXDataSource = ["Select", "RecordListWrapper"].includes(
        values.interfaceType || ""
      );
      if (needUseXDataSource && values.xDataSource) {
        const {
          type: type2 = "default",
          options = [],
          ...rest
        } = (values == null ? void 0 : values.xDataSource) || {};
        if (type2 === "default") {
          schema["x-data-source"] = { type: type2, options };
        } else if (type2 === "api") {
          schema["x-data-source"] = { type: type2, ...rest || {} };
          if (rest == null ? void 0 : rest.extraParams) {
            try {
              schema["x-data-source"].extraParams = JSON.parse(
                rest.extraParams
              );
            } catch (error) {
              throw new Error(
                `Extra Params格式错误: ${error instanceof Error ? error.message : "未知错误"}`
              );
            }
          }
        } else if (type2 === "custom") {
          schema["x-data-source"] = { type: type2 };
        }
      } else {
        schema["x-data-source"] = void 0;
      }
      const needUseXRecordSchema = values.interfaceType === "RecordListWrapper";
      if (needUseXRecordSchema && values.xRecordSchema) {
        try {
          schema["x-record-schema"] = JSON.parse(values.xRecordSchema);
        } catch (error) {
          throw new Error(
            `Record List Wrapper Schema格式错误: ${error instanceof Error ? error.message : "未知错误"}`
          );
        }
      } else {
        schema["x-record-schema"] = void 0;
      }
      values.schema = Object.keys(schema).length > 0 ? schema : void 0;
      delete values.xDataSource;
      delete values.xRecordSchema;
      delete values.xCustomUiSchema;
      await onOk(values);
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };
  const title = import_utils.locales.getText(
    type === "add" ? "registry.modal.add.item" : "registry.modal.edit.item"
  );
  const jsonValidator = (value, message) => {
    if (!value || value.trim() === "") {
      return Promise.resolve();
    }
    try {
      JSON.parse(value);
      return Promise.resolve();
    } catch (error) {
      return Promise.reject(new Error(message));
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_antd.Drawer,
    {
      title,
      open,
      onClose: handleCancel,
      width: 600,
      destroyOnClose: true,
      footer: /* @__PURE__ */ import_react.default.createElement("div", { style: { textAlign: "right" } }, /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { onClick: handleCancel, style: { marginRight: 8 } }, import_utils.locales.getText("registry.button.cancel")), /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "primary", onClick: handleOk }, import_utils.locales.getText("registry.button.save")))
    },
    /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical", requiredMark: true }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "name",
        label: import_utils.locales.getText("registry.form.name"),
        rules: [
          {
            required: true,
            validator: (_, value) => {
              if (!value || !value.original) {
                return Promise.reject(
                  new Error(import_utils.locales.getText("registry.message.required"))
                );
              }
              if (value.original.length > 100) {
                return Promise.reject(
                  new Error(
                    import_utils.locales.getText("registry.message.name.maxLength")
                  )
                );
              }
              return Promise.resolve();
            }
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.BaseTranslation,
        {
          placeholder: import_utils.locales.getText("registry.form.name.placeholder"),
          type: "text",
          renderMode: "edit"
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "key",
        label: import_utils.locales.getText("registry.form.key"),
        rules: [
          {
            required: true,
            message: import_utils.locales.getText("registry.message.required")
          },
          {
            max: 100,
            message: import_utils.locales.getText("registry.message.key.maxLength")
          },
          {
            validator: (section == null ? void 0 : section.code) ? (0, import_validators.createPrefixedAppIdentifierValidator)(section.code) : (_, value) => {
              if (!value) return Promise.resolve();
              return Promise.reject(new Error("未找到当前区块信息"));
            }
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Input,
        {
          placeholder: import_utils.locales.getText("registry.form.key.placeholder"),
          maxLength: 100
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(import_antd.Row, { gutter: 16 }, /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 12 }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "fieldType",
        label: import_utils.locales.getText("registry.form.fieldType"),
        rules: [
          {
            required: true,
            message: import_utils.locales.getText("registry.message.required")
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Select,
        {
          placeholder: import_utils.locales.getText(
            "registry.form.fieldType.placeholder"
          ),
          onChange: handleFieldTypeChange
        },
        fieldTypeOptions.map((option) => /* @__PURE__ */ import_react.default.createElement(Option, { key: option.value, value: option.value }, option.label))
      )
    )), /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 12 }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "interfaceType",
        label: import_utils.locales.getText("registry.form.interfaceType"),
        rules: [
          {
            required: true,
            message: import_utils.locales.getText("registry.message.required")
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Select,
        {
          placeholder: import_utils.locales.getText(
            "registry.form.interfaceType.placeholder"
          ),
          allowClear: true,
          onChange: handleInterfaceTypeChange
        },
        (interfaceTypeOptions[selectedFieldType] || []).map(
          (option) => /* @__PURE__ */ import_react.default.createElement(Option, { key: option.value, value: option.value }, option.label)
        )
      )
    ))), ["Select", "RecordListWrapper"].includes(_interfaceType || "") && /* @__PURE__ */ import_react.default.createElement(import_OptionDataSource.default, { form, treeDataSource }), _interfaceType === "RecordListWrapper" && /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "xRecordSchema",
        label: import_utils.locales.getText("registry.form.recordListWrapper.label"),
        rules: [
          {
            validator: (_, value) => jsonValidator(
              value,
              import_utils.locales.getText(
                "registry.message.recordListWrapper.invalid"
              )
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        TextArea,
        {
          placeholder: import_utils.locales.getText(
            "registry.form.recordListWrapper.placeholder"
          ),
          rows: 6,
          style: { fontFamily: "monospace" }
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "scopes",
        label: import_utils.locales.getText("registry.form.scopes"),
        rules: [
          {
            required: true,
            message: import_utils.locales.getText("registry.message.required")
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Checkbox.Group,
        {
          options: scopeOptions.map((option) => ({
            label: import_utils.locales.getText(option.label),
            value: option.value
          })),
          onChange: handleScopesChange
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "description",
        label: import_utils.locales.getText("registry.form.description"),
        rules: [
          {
            validator: (_, value) => {
              if (value && value.original && value.original.length > 500) {
                return Promise.reject(
                  new Error(
                    import_utils.locales.getText("registry.message.description.maxLength")
                  )
                );
              }
              return Promise.resolve();
            }
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.BaseTranslation,
        {
          placeholder: import_utils.locales.getText(
            "registry.form.description.placeholder"
          ),
          type: "textarea",
          renderMode: "edit"
        }
      )
    ), showSystemDefaultValue && /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "default",
        label: import_utils.locales.getText("registry.form.systemDefaultValue"),
        rules: [
          {
            validator: (_, value) => {
              if (value === null || value === void 0 || value === "") {
                return Promise.resolve();
              }
              const currentFieldType = form.getFieldValue("fieldType");
              if (!currentFieldType) {
                return Promise.reject(new Error("请先选择字段类型"));
              }
              const validation = (0, import_typeValidation.validateDefaultValue)(
                currentFieldType,
                value
              );
              if (!validation.isValid) {
                return Promise.reject(new Error(validation.error));
              }
              return Promise.resolve();
            }
          }
        ]
      },
      renderDefaultValueInput(selectedFieldType)
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "xCustomUiSchema",
        label: import_utils.locales.getText("registry.form.uiSchema"),
        rules: [
          {
            validator: (_, value) => jsonValidator(
              value,
              import_utils.locales.getText("registry.message.uiSchema.invalid")
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        TextArea,
        {
          placeholder: import_utils.locales.getText("registry.form.uiSchema.placeholder"),
          rows: 6,
          style: { fontFamily: "monospace" }
        }
      )
    ))
  );
};
var ItemModal_default = ItemModal;
