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/dataSourceComponents/dataSourceForm/utils.tsx
var utils_exports = {};
__export(utils_exports, {
  formItemNameReplace: () => formItemNameReplace,
  formItemNameReverse: () => formItemNameReverse,
  getNestedValue: () => getNestedValue,
  renderValueWithMap: () => renderValueWithMap,
  toArr: () => toArr,
  withDataSource: () => withDataSource,
  withFormItem: () => withFormItem,
  withMode: () => withMode,
  withOptions: () => withOptions
});
module.exports = __toCommonJS(utils_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_classnames = __toESM(require("classnames"));
var import_libphonenumber_js = require("libphonenumber-js");
var import_locales = require("../../../locales");
var import_form = __toESM(require("../../form"));
var import_useDataSource = __toESM(require("../hooks/useDataSource"));
var import_useFormSetting = __toESM(require("./provider/hooks/useFormSetting"));
var import_useJsonPrefixPath = __toESM(require("./provider/hooks/useJsonPrefixPath"));
var import_DataSourceProvider = __toESM(require("../provider/dataSource/DataSourceProvider"));
var import_useTranslationOriginal = __toESM(require("../../../hooks/useTranslationOriginal"));
var import_style = require("./style.less");
var withMode = (FieldComponent, ReadPrettyComponent, transformProps) => {
  return ({ renderMode = "edit", value, onChange, ...props }) => {
    const transformedProps = (transformProps == null ? void 0 : transformProps(
      { ...props, value, onChange, renderMode },
      renderMode
    )) || { ...props, value, onChange, renderMode };
    if (["view", "tableView"].includes(renderMode) && ReadPrettyComponent) {
      return /* @__PURE__ */ import_react.default.createElement(
        ReadPrettyComponent,
        {
          ...transformedProps
        }
      );
    }
    if (renderMode === "disabled") {
      return /* @__PURE__ */ import_react.default.createElement(
        FieldComponent,
        {
          ...transformedProps,
          disabled: true
        }
      );
    }
    return /* @__PURE__ */ import_react.default.createElement(FieldComponent, { ...transformedProps });
  };
};
var FORM_ITEM_SPLIT_CHAR = "__zsj__";
var formItemNameReplace = (name) => {
  return name.replace(/\./g, FORM_ITEM_SPLIT_CHAR);
};
var formItemNameReverse = (name) => {
  return name.replace(new RegExp(FORM_ITEM_SPLIT_CHAR, "g"), ".");
};
var withFormItem = (WrappedComponent, overlayProps) => {
  return ({
    name: propsName,
    label: propsLabel,
    mode: propsMode,
    renderMode: propsRenderMode,
    tooltip,
    noStyle,
    extra,
    required,
    requiredobj,
    minLengthobj,
    maxLengthobj,
    typeobj,
    maxobj,
    minobj,
    normalize,
    getValueProps,
    validator,
    style,
    validateTrigger,
    __designMode,
    labelCol: propsLabelCol,
    hideLabel,
    innerStyle,
    ...otherProps
  }) => {
    var _a;
    const { path: prefixPath = [] } = (0, import_useJsonPrefixPath.default)();
    const { dataSource } = (0, import_useDataSource.default)();
    const { fields } = dataSource || {};
    const { renderMode: globalRenderMode, size } = (0, import_useFormSetting.default)();
    const field = fields == null ? void 0 : fields.find((item) => item.name === propsName);
    const label = propsLabel || ((_a = field == null ? void 0 : field.uiSchema) == null ? void 0 : _a.title) || propsName;
    const effectiveMode = propsRenderMode || globalRenderMode;
    const renderComponent = (0, import_react.useMemo)(() => {
      var _a2;
      return /* @__PURE__ */ import_react.default.createElement(
        WrappedComponent,
        {
          ...otherProps,
          mode: propsMode,
          renderMode: effectiveMode,
          ...overlayProps == null ? void 0 : overlayProps.innerProps,
          style: {
            ...innerStyle || {},
            ...((_a2 = overlayProps == null ? void 0 : overlayProps.innerProps) == null ? void 0 : _a2.style) || {}
          },
          isVerification: typeobj == null ? void 0 : typeobj.enabled,
          size
        }
      );
    }, [
      effectiveMode,
      otherProps,
      propsMode,
      overlayProps == null ? void 0 : overlayProps.innerProps,
      typeobj == null ? void 0 : typeobj.enabled,
      size,
      innerStyle
    ]);
    const isDesignMode = __designMode === "design";
    const isHidden = effectiveMode === "hidden";
    const name = (0, import_utils.isString)(propsName) && propsName.includes(".") ? [propsName] : propsName;
    const concatName = name !== void 0 ? [...prefixPath, ...toArr(name)] : void 0;
    const rules = [];
    if (requiredobj && requiredobj.required) {
      rules.push({
        ...requiredobj,
        message: requiredobj.message || (0, import_locales.getText)("pisell-data-source-form-required-message")
      });
    }
    if (typeobj && typeobj.enabled) {
      if (typeobj.type === "email") {
        rules.push({
          ...typeobj,
          message: typeobj.message || (0, import_locales.getText)("pisell-data-source-form-email-message")
        });
      }
      if (typeobj.type === "url" && typeobj.enabled) {
        rules.push({
          ...typeobj,
          message: typeobj.message || (0, import_locales.getText)("pisell-data-source-form-url-message")
        });
      }
      if (typeobj.type === "phone" && typeobj.enabled) {
        rules.push({
          validator: (_, value) => {
            var _a2;
            return (0, import_libphonenumber_js.isValidPhoneNumber)(value) && ((_a2 = (0, import_libphonenumber_js.parsePhoneNumberFromString)(value)) == null ? void 0 : _a2.isValid()) ? Promise.resolve() : Promise.reject(
              new Error(
                typeobj.message || (0, import_locales.getText)("pisell-data-source-form-phone-message")
              )
            );
          }
        });
      }
    }
    if (maxLengthobj && maxLengthobj.enabled) {
      rules.push({
        // ...maxLengthobj,
        validator(_, value) {
          let length = 0;
          if ((0, import_utils.isString)(value)) {
            length = value.length;
          } else if ((0, import_utils.isArr)(value)) {
            length = value.length;
          } else if ((0, import_utils.isNumber)(value)) {
            length = `${value}`.length;
          }
          if (length > maxLengthobj.max) {
            return Promise.reject(
              new Error(
                maxLengthobj.message || (0, import_locales.getText)("pisell-data-source-form-max-length-message")(
                  maxLengthobj == null ? void 0 : maxLengthobj.max
                )
              )
            );
          }
          return Promise.resolve();
        }
      });
    }
    if (minLengthobj && minLengthobj.enabled) {
      rules.push({
        // ...minLengthobj,
        validator(_, value) {
          let length = 0;
          if ((0, import_utils.isString)(value)) {
            length = value.length;
          } else if ((0, import_utils.isArr)(value)) {
            length = value.length;
          } else if ((0, import_utils.isNumber)(value)) {
            length = `${value}`.length;
          }
          if (length < minLengthobj.min) {
            return Promise.reject(
              new Error(
                minLengthobj.message || (0, import_locales.getText)("pisell-data-source-form-min-length-message")(
                  minLengthobj == null ? void 0 : minLengthobj.min
                )
              )
            );
          }
          return Promise.resolve();
        }
      });
    }
    if (maxobj && maxobj.enabled) {
      rules.push({
        ...maxobj,
        type: "number",
        message: maxobj.message || (0, import_locales.getText)("pisell-data-source-form-max-value-message")(maxobj == null ? void 0 : maxobj.max)
      });
    }
    if (minobj && minobj.enabled) {
      rules.push({
        ...minobj,
        type: "number",
        message: minobj.message || (0, import_locales.getText)("pisell-data-source-form-min-value-message")(minobj == null ? void 0 : minobj.min)
      });
    }
    if (validator) {
      rules.push({
        validator: (_, value) => {
          return validator(value);
        }
      });
    }
    const labelCol = (0, import_react.useMemo)(() => {
      if (hideLabel) {
        return { span: 0 };
      }
      return propsLabelCol;
    }, [hideLabel, propsLabelCol]);
    return /* @__PURE__ */ import_react.default.createElement(
      import_form.default.Item,
      {
        required,
        style: {
          width: "100%",
          ...style,
          opacity: isDesignMode && isHidden ? "0.3" : 1
        },
        name: concatName,
        label,
        tooltip,
        noStyle,
        extra,
        hidden: isHidden && !isDesignMode,
        rules,
        normalize,
        getValueProps,
        validateTrigger,
        labelCol,
        initialValue: otherProps == null ? void 0 : otherProps.defaultValue,
        className: (0, import_classnames.default)("pisell-data-source-form-item", {
          "pisell-data-source-form-item-view": effectiveMode === "view"
        }),
        ...overlayProps == null ? void 0 : overlayProps.otherFormItemProps
      },
      renderComponent
    );
  };
};
var withDataSource = (WrappedComponent) => {
  return (props) => {
    const { dataSource } = props;
    return /* @__PURE__ */ import_react.default.createElement(import_DataSourceProvider.default, { dataSource }, /* @__PURE__ */ import_react.default.createElement(WrappedComponent, { ...props }));
  };
};
var withOptions = (WrappedComponent) => {
  return (props) => {
    var _a;
    const translationOriginal = (0, import_useTranslationOriginal.default)();
    const {
      options: propsOptions,
      optionSourceType,
      labelField,
      valueField
    } = props;
    const { list } = (0, import_useDataSource.default)();
    (0, import_react.useEffect)(() => {
      if (optionSourceType === "api") {
        list.run({
          page: 1,
          pageSize: 200
        });
      }
    }, []);
    const options = (0, import_react.useMemo)(() => {
      var _a2, _b;
      if (optionSourceType !== "api") {
        return propsOptions;
      }
      return (((_b = (_a2 = list.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.map((item) => ({
        label: translationOriginal(item[labelField]),
        value: item[valueField]
      }))) || []).sort((a, b) => a.label.localeCompare(b.label));
    }, [propsOptions, optionSourceType, (_a = list == null ? void 0 : list.data) == null ? void 0 : _a.data]);
    return /* @__PURE__ */ import_react.default.createElement(WrappedComponent, { ...props, options });
  };
};
var getNestedValue = (obj, path) => {
  const keys = path.split(".");
  let value = obj;
  for (const k of keys) {
    if (!value)
      break;
    value = value[k];
  }
  return value;
};
var renderValueWithMap = (value, valueMap, renderMode) => {
  const textStyle = renderMode === "tableView" ? { fontSize: 14, fontWeight: 400 } : {};
  if ((0, import_utils.isArr)(value)) {
    return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-form-read-pretty-text" }, value.map((item, index) => /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("span", { key: item, className: "pisell-form-read-pretty-value", style: textStyle }, valueMap == null ? void 0 : valueMap[item]), index < value.length - 1 && ",")));
  } else if ((0, import_utils.isString)(value)) {
    return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-form-read-pretty-text" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-form-read-pretty-value", style: textStyle }, (valueMap == null ? void 0 : valueMap[value]) || value));
  }
  return null;
};
function toArr(str) {
  return Array.isArray(str) ? str : [str];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formItemNameReplace,
  formItemNameReverse,
  getNestedValue,
  renderValueWithMap,
  toArr,
  withDataSource,
  withFormItem,
  withMode,
  withOptions
});
