import { _ as _toConsumableArray } from '../_verture/toConsumableArray-81040c9e.js';
import { _ as _slicedToArray } from '../_verture/slicedToArray-76060636.js';
import { jsx } from 'react/jsx-runtime';
import { DeepClone } from '@iam-com/lib';
import React__default from 'react';
import { F as FormItem, l as localeJson, v as validate } from '../_verture/index-ff69ced7.js';
import { u as useFormatMessage } from '../_verture/useFormatMessage-703f8b20.js';
import { $ as $prefixCls } from '../_verture/constant-66aa48a1.js';
import '../_verture/unsupportedIterableToArray-cb478f24.js';
import '../TextField/index.js';
import '../_verture/typeof-498dd2b1.js';
import '../_verture/tslib.es6-55ed4bd2.js';
import '../Label/index.js';
import '../Help/index.js';
import '../Tooltip/index.js';
import 'rc-tooltip';
import 'rc-tooltip/lib/placements';
import 'clsx';
import '../_verture/style-inject.es-300983ab.js';
import '@iam-com/icons/Help';
import '@iam-com/icons/PreviewClose';
import '@iam-com/icons/PreviewOpen';
import '@iam-com/icons/CloseCircle';
import '../AutoTips/index.js';
import '../Loading/index.js';
import '@iam-com/icons/LoadingF';
import '../HelperText/index.js';
import '../_verture/useGlobalProps-1b846a65.js';
import '@para-ui/core/GlobalContext';
import '../_verture/index-fac03ce3.js';
import 'rc-dropdown';
import '../_verture/usePopupContainer-87febeb9.js';
import 'dayjs';
import '../RadioGroup/index.js';
import '../Radio/index.js';
import '../Select/index.js';
import '../_verture/defineProperty-62acccfc.js';
import '../Empty/index.js';
import '@iam-com/icons/Close';
import '@iam-com/icons/Down';
import '@iam-com/icons/Check';
import '@iam-com/icons/Search';
import '../Popover/index.js';
import '../CheckboxGroup/index.js';
import '../Checkbox/index.js';
import '../Switch/index.js';
import 'rc-switch';
import '@iam-com/icons/Delete';
import '@iam-com/icons/LinkGroup';
import '../Button/index.js';
import '@iam-com/icons/Forbid';
import '../InputNumber/index.js';
import 'rc-input-number';
import '@iam-com/icons/Up';
import '@iam-com/icons/Minus';
import '@iam-com/icons/Plus';
import '../ComboSelect/index.js';
import '../_verture/index-beef914f.js';
import '../Table/index.js';
import '@iam-com/icons/ScreenF';
import '@iam-com/icons/UpTriangleF';
import '@iam-com/icons/DownTriangleF';
import '@iam-com/icons/Panel';
import '../OperateBtn/index.js';
import '@iam-com/icons/More';
import '@iam-com/icons/Refresh';
import '../Pagination/index.js';
import '@iam-com/icons/DoubleLeft';
import '@iam-com/icons/Left';
import 'rc-pagination';
import '@iam-com/icons/Right';
import '@iam-com/icons/DoubleRight';
import '../_verture/index-6d6244a3.js';
import 'rc-tree';
import '@iam-com/icons/Document';
import 'react-dom';
import '@iam-com/icons/EditFile';
import '@iam-com/icons/PlusCircle';
import '@iam-com/icons/MoreCircle';
import '../_verture/utils-1ffeadec.js';

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
/**
 * form 表单组件
 * @author zhanzl
 * @param {Object} form 表单对象，可以存储校验方法和其他关键数据
 * @param {configListProps} configList 表单项配置数组
 * @param {boolean} disabled 是否启用禁用状态，所有输入框禁止输入
 * @param {Function} onChange 表单选项改变传出
 * @param {string} type 表单形态 竖布局 或 横布局，默认横
 * @description 用于根据配置自动生成表单
 */
var Form = function Form(props) {
  var intl = useFormatMessage('FormItem', localeJson);
  var _props$className = props.className,
    className = _props$className === void 0 ? "" : _props$className,
    FormProps = props.FormProps,
    requiredElement = props.requiredElement,
    disRequiredElement = props.disRequiredElement,
    configList = props.configList,
    type = props.type,
    getCheckForm = props.getCheckForm,
    backData = props.backData,
    disabled = props.disabled,
    onChange = props.onChange,
    getForcedRefresh = props.getForcedRefresh,
    labelProps = props.labelProps,
    helperTextProps = props.helperTextProps,
    form = props.form,
    _props$labelWidth = props.labelWidth,
    labelWidth = _props$labelWidth === void 0 ? 60 : _props$labelWidth,
    _props$disOnlySpace = props.disOnlySpace,
    disOnlySpace = _props$disOnlySpace === void 0 ? true : _props$disOnlySpace;
  var frstBackData = React__default.useRef(backData && DeepClone(backData) || {});
  var firstConfigList = React__default.useRef(configList);
  /**
   * item配置项目
   */
  var _React$useState = React__default.useState(configList),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    itemsConfig = _React$useState2[0],
    setItemsConfig = _React$useState2[1];
  /**
   * 更新表单项
   */
  var _React$useState3 = React__default.useState(Math.random()),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    refresh = _React$useState4[0],
    setRefresh = _React$useState4[1];
  /**
   * 用于存储所有常用数据
   */
  var refData = React__default.useRef({
    allItems: {},
    itemsCheckStatus: {},
    itemsCheckMessage: {},
    configList: configList || [],
    allValues: backData && DeepClone(backData) || {}
  });
  /**
   * 强制刷新表单参数
   * @param {Array<FormItemProps>} list 表单项配置
   * @param { [name: string]: any } bData 回填数据
   */
  var refreshForm = function refreshForm(list, bData) {
    if (bData) for (var key in bData) {
      refData.current.allValues[key] = bData[key];
    }
    setItemsConfig(list || itemsConfig && _toConsumableArray(itemsConfig));
  };
  /**
   * 保存值 和 最后的 item 对象
   * @param {string} name 表单项 name
   * @param {string} type 需要设置值的类型 value | item | status | initValue | message
   * @param {any} value 需要设置的值
   */
  var setValue = function setValue(name, type, value) {
    switch (type) {
      // 设置校验状态，自定义类型的表格设置，如果有一个是false，最终校验都不会通过
      case "status":
        refData.current.itemsCheckStatus[name] = value;
        break;
      // 存储报错信息，防止表单刷新后，报错信息和状态丢失
      case "message":
        refData.current.itemsCheckMessage[name] = value;
        break;
      // 存储加工之后的item 对象
      case "item":
        refData.current.allItems[name] = value;
        break;
      // 初始化赋值
      case "initValue":
        refData.current.allValues[name] = value;
        break;
      // 赋值,会触发表单的onChange事件
      default:
        refData.current.allValues[name] = value;
        onChange && onChange(name, value);
        break;
    }
  };
  /**
   * 校验表单校验状态
   * @return {boolean | { [name: string]: any }} 返回 校验错误false，如果校验通过则返回表单所有值
   */
  var checkFrom = function checkFrom(nameList) {
    var errorCount = 0;
    // 需要校验的表单项
    var checkList = nameList ? nameList : refData.current.configList.map(function (item) {
      return item.name;
    });
    var _iterator = _createForOfIteratorHelper(checkList),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var key = _step.value;
        var tItem = refData.current.allItems[key];
        // 判断是否已经校验过了 或是 不需要校验，直接跳过
        if (tItem.disabled || tItem.hide || refData.current.itemsCheckStatus[key] === true) continue;
        if (refData.current.itemsCheckStatus[key] === false) {
          errorCount++;
          continue;
        }
        var msg = validate(tItem, refData.current.allValues[key], intl);
        if (msg) {
          errorCount++;
          if (typeof msg === "string") refData.current.itemsCheckMessage[key] = msg;
          tItem.setErrorMsg && tItem.setErrorMsg(msg);
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return !errorCount && refData.current.allValues;
  };
  /**
   * 过滤有效值
   */
  var getValidValues = function getValidValues() {
    var tObj = {};
    for (var i = 0; i < refData.current.configList.length; i++) {
      var item = refData.current.configList[i];
      if (!item.hide && refData.current.allValues[item.name]) {
        tObj[item.name] = refData.current.allValues[item.name];
      }
    }
    return tObj;
  };
  /**
   * 重置表单
   */
  var resetForm = function resetForm() {
    var isClear = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var name = arguments.length > 1 ? arguments[1] : undefined;
    if (!isClear || !name) {
      refData.current = {
        allItems: {},
        itemsCheckStatus: {},
        itemsCheckMessage: {},
        configList: firstConfigList.current || [],
        allValues: {}
      };
      if (frstBackData.current && !isClear) for (var key in frstBackData.current) {
        refData.current.allValues[key] = frstBackData.current[key];
      }
    } else {
      if (typeof name === "string") {
        setValue(name, "status", undefined);
        setValue(name, "message", "");
        setValue(name, "initValue", undefined);
      } else {
        name.forEach(function (key) {
          setValue(key, "status", undefined);
          setValue(key, "message", "");
          setValue(key, "initValue", undefined);
        });
      }
    }
    setItemsConfig(firstConfigList.current);
    setRefresh(Math.random());
  };
  /**
   * 传出校验方法
   */
  React__default.useEffect(function () {
    getCheckForm && getCheckForm(checkFrom);
    getForcedRefresh && getForcedRefresh(refreshForm);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [getCheckForm, getForcedRefresh]);
  /**
   * 更新值
   */
  React__default.useEffect(function () {
    if (backData) for (var key in backData) {
      refData.current.allValues[key] = backData[key];
    }
    setRefresh(Math.random());
  }, [backData]);
  /**
   * 更新配置
   */
  React__default.useEffect(function () {
    setItemsConfig(configList);
  }, [configList]);
  /**
   * 更新表单最新配置
   */
  React__default.useEffect(function () {
    refData.current.configList = itemsConfig || [];
  }, [itemsConfig]);
  /**
   * 表单对象赋值
   */
  React__default.useEffect(function () {
    if (form) {
      form.current = {
        get refreshForm() {
          return refreshForm;
        },
        get check() {
          return checkFrom;
        },
        get items() {
          return refData.current.allItems;
        },
        get values() {
          return refData.current.allValues;
        },
        get refData() {
          return refData.current;
        },
        get getValidValues() {
          return getValidValues;
        },
        get reset() {
          return resetForm;
        },
        get clear() {
          return function (name) {
            resetForm(true, name);
          };
        }
      };
    }
  }, [form]);
  var handleSubmit = function handleSubmit(event) {
    event.preventDefault(); // 阻止默认的提交行为
  };

  var cRender = React__default.useMemo(function () {
    return jsx("div", Object.assign({
      className: "form-content ".concat(className)
    }, {
      children: itemsConfig && itemsConfig.length > 0 && itemsConfig.map(function (item, idx) {
        // 不显示则提前保存最后值
        item.hide && setValue(item.name, "item", item);
        return !item.hide && jsx(FormItem, Object.assign({
          type: type,
          disabled: disabled,
          disOnlySpace: disOnlySpace,
          errorMessage: refData.current.itemsCheckMessage[item.name],
          requiredElement: requiredElement,
          disRequiredElement: disRequiredElement,
          labelProps: labelProps,
          helperTextProps: helperTextProps,
          llabelWidth: labelWidth
        }, item, {
          backData: refData.current.allValues,
          setValue: setValue
        }), "form-item-".concat(idx, "-").concat(refresh));
      })
    }));
  }, [className, itemsConfig, onChange, refresh, labelWidth, type, disabled, disOnlySpace, requiredElement, disRequiredElement, labelProps, helperTextProps]);
  return jsx("form", Object.assign({
    onSubmit: handleSubmit
  }, FormProps, {
    className: "".concat($prefixCls, "-form")
  }, {
    children: cRender
  }));
};

export { Form as default };
