function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useEffect, useState, useMemo, useContext } from 'react';
import { Button, Steps, Col } from 'antd';
import StandardForm from "./index";
import RenderItemGroup from "../FormComp/RenderItemGroup";
import ActionList from "./ActionList";
import "./style/index.less";
import classNames from 'classnames';
import { FanContext } from "../ConfigContext";
import { useLanguageObject } from "../hooks/use-language";
// import { BreadcrumbProps as AntdBreadcrumbProps } from 'antd/es/form';
var Step = Steps.Step;
var StepForm = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var lang = useLanguageObject(); // 当前使用的语言包
  var InitFanContext = useContext(FanContext);
  var providerConfig = InitFanContext['StepForm'] || {}; // 使用上下文（全局配置）设置扩展的配置项
  var _providerConfig$props = _objectSpread(_objectSpread({}, providerConfig), props),
    getFormFields = _providerConfig$props.getFormFields,
    _providerConfig$props2 = _providerConfig$props.formItemGroup,
    formItemGroup = _providerConfig$props2 === void 0 ? [] : _providerConfig$props2,
    _providerConfig$props3 = _providerConfig$props.grid,
    grid = _providerConfig$props3 === void 0 ? 'md' : _providerConfig$props3,
    _providerConfig$props4 = _providerConfig$props.layout,
    layout = _providerConfig$props4 === void 0 ? 'horizontal' : _providerConfig$props4,
    onSubmit = _providerConfig$props.onSubmit,
    _providerConfig$props5 = _providerConfig$props.actionAlign,
    actionAlign = _providerConfig$props5 === void 0 ? 'center' : _providerConfig$props5,
    fieldStatus = _providerConfig$props.fieldStatus,
    _providerConfig$props6 = _providerConfig$props.fieldSize,
    fieldSize = _providerConfig$props6 === void 0 ? "middle" : _providerConfig$props6,
    initialValues = _providerConfig$props.initialValues,
    parseTransform = _providerConfig$props.parseTransform,
    actionHide = _providerConfig$props.actionHide,
    _providerConfig$props7 = _providerConfig$props.stepsConfig,
    stepsConfig = _providerConfig$props7 === void 0 ? {
      current: 0
    } : _providerConfig$props7,
    stepClick = _providerConfig$props.stepClick,
    displayLayout = _providerConfig$props.displayLayout;
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    formChildFields = _useState2[0],
    setFormChildFields = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    formChild = _useState4[0],
    setFormChild = _useState4[1];
  var _useState5 = useState(0),
    _useState6 = _slicedToArray(_useState5, 2),
    currentStep = _useState6[0],
    setCurrentStep = _useState6[1];
  // const [fieldFailed, setFieldFailed] = useState(false)

  useEffect(function () {
    if (stepsConfig && (stepsConfig.current || stepsConfig.current === 0)) {
      setCurrentStep(stepsConfig.current); // 判断是否有设置当前选中的步骤数
    }
  }, [stepsConfig]);
  if (formItemGroup.length === 0) return null;
  var formGridSize = useMemo(function () {
    if (typeof grid === 'string') return grid; // 数据格式为字符串，包括 xs,md,lg,xlg
    var sizeName = 'xs';
    if (grid <= 1) sizeName = 'xs';
    if (grid === 2) sizeName = 'md';
    if (grid === 3) sizeName = 'lg';
    if (grid > 3) sizeName = 'xlg';
    return sizeName;
  }, [grid]);
  useEffect(function () {
    forceUpdateForm();
  }, [formChildFields, formChild]);
  var forceUpdateForm = function forceUpdateForm() {
    getFormFields && getFormFields(formChildFields, formChild);
  };
  var handleStepType = function handleStepType(type, extraFunc) {
    switch (type) {
      case 'submit':
      case 'next':
        // 获取当前步骤的表单配置下有 rules 的控件进行校验（自定义的控件则自己有业务层面处理添加校验）
        var curentFields = formItemGroup[currentStep].fields;
        var valitorGroup = curentFields && Array.isArray(curentFields) ? curentFields.filter(function (fItem) {
          return fItem.rules;
        }).map(function (matchItem) {
          return matchItem.filedName || matchItem.fieldName;
        }) : [];
        formChild && formChild.validateFields(valitorGroup).then(function (values) {
          if (stepClick) stepClick(type, formChild, values);
          extraFunc && extraFunc();
        }).catch(function (_ref) {
          var errorFields = _ref.errorFields;
        } // console.log('表单校验不通过 ', errorFields.map(err => err))
        );
        break;
      case 'prev':
        if (stepClick) stepClick(type, formChild);
        extraFunc && extraFunc();
        break;
      case 'cancel':
        if (stepClick) stepClick(type, formChild);
        extraFunc && extraFunc();
        break;
      default:
        break;
    }
  };

  /*  const handleStepChange = (cur:any) => {
      // 自行判断是否校验通过
      /!*    if (cur > current) {
            formChild.validateFields()
              .then(values => {
                if (stepsConfig && stepsConfig.onChange) stepsConfig.onChange(cur, formChild);
              })
              .catch(errorInfo => {
              });
          } else {
            if (stepsConfig && stepsConfig.onChange) stepsConfig.onChange(cur, formChild);
          }*!/
      if (stepsConfig && stepsConfig.onChange) stepsConfig.onChange(cur, formChild);
    }*/
  var renderStepActions = function renderStepActions(item, index) {
    if (formItemGroup.length === 1) {
      return /*#__PURE__*/React.createElement("div", {
        className: "standardForm-actions",
        key: index
      }, /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: function onClick() {
          return handleStepType('submit');
        }
      }, (lang === null || lang === void 0 ? void 0 : lang['global.confirm.text']) || '确认'), /*#__PURE__*/React.createElement(Button, {
        onClick: function onClick() {
          return handleStepType('cancel');
        }
      }, (lang === null || lang === void 0 ? void 0 : lang['global.cancel.text']) || '取消'));
    }
    var buttonList = function buttonList(itemIndex) {
      if (itemIndex === 0) {
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          onClick: function onClick() {
            return handleStepType('next');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.next.text']) || '下一步'), /*#__PURE__*/React.createElement(Button, {
          onClick: function onClick() {
            return handleStepType('cancel');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.cancel.text']) || '取消'));
      } else if (itemIndex === formItemGroup.length - 1) {
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          onClick: function onClick() {
            return handleStepType('prev');
          }
        }, "\u4E0A\u4E00\u6B65"), /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          htmlType: "submit",
          onClick: function onClick() {
            return handleStepType('submit');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.confirm.text']) || '确认'), /*#__PURE__*/React.createElement(Button, {
          onClick: function onClick() {
            return handleStepType('cancel');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.cancel.text']) || '取消'));
      } else {
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          onClick: function onClick() {
            return handleStepType('prev');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.prev.text']) || '上一步'), /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          onClick: function onClick() {
            return handleStepType('next');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.next.text']) || '下一步'), /*#__PURE__*/React.createElement(Button, {
          onClick: function onClick() {
            return handleStepType('cancel');
          }
        }, (lang === null || lang === void 0 ? void 0 : lang['global.cancel.text']) || '取消'));
      }
    };
    return /*#__PURE__*/React.createElement("div", {
      className: "standardForm-actions",
      key: index,
      style: {
        textAlign: actionAlign
      }
    }, buttonList(index));
  };
  return /*#__PURE__*/React.createElement(StandardForm, {
    className: layout === 'inline' ? '' : '',
    actionGroup: [],
    ref: ref,
    fieldSize: fieldSize,
    initialValues: initialValues,
    parseTransform: parseTransform
    // @ts-ignore
    ,
    getFormFields: function getFormFields(fields, form) {
      setFormChildFields(fields);
      setFormChild(form);
    },
    onSubmit: onSubmit,
    layout: layout,
    onFinishFailed: function onFinishFailed() {
      // setFieldFailed(true)
    }
  }, /*#__PURE__*/React.createElement(Steps, _extends({
    style: {
      width: '80%',
      margin: '0 auto'
    }
  }, stepsConfig), formItemGroup.filter(function (fItem) {
    return !fItem.hideStep;
  }).map(function (item, index) {
    return /*#__PURE__*/React.createElement(Step, {
      key: "".concat(item.title).concat(index),
      description: item.description,
      icon: item.icon,
      status: item.status,
      title: item.title,
      subTitle: item.subTitle,
      disabled: item.disabled
    });
  })),
  // 过滤隐藏掉的步骤表单
  formItemGroup.filter(function (fItem) {
    return !fItem.hideStep;
  }).map(function (item, index) {
    return /*#__PURE__*/React.createElement("div", {
      key: index,
      className: classNames("stepForm-content", "stepForm-content-".concat(layout || '')),
      style: stepsConfig && stepsConfig.current !== index ? {
        display: 'none'
      } : {}
    }, item.fields && Array.isArray(item.fields) ? /*#__PURE__*/React.createElement(RenderItemGroup, {
      layout: layout,
      form: formChild,
      fieldStatus: fieldStatus,
      size: formGridSize,
      displayLayout: displayLayout,
      doUpdateFormFields: function doUpdateFormFields() {
        return forceUpdateForm();
      }
      // doUpdateFormFields={() => console.log('强制渲染表单')}
      ,
      itemGroup: item.fields
    }) : item.fields, !actionHide && /*#__PURE__*/React.createElement(Col, {
      span: 24
    }, item.actions ? /*#__PURE__*/React.createElement(ActionList, {
      list: item.actions,
      onStep: handleStepType,
      form: formChild,
      align: actionAlign,
      other: props
    }) : renderStepActions(item, index)));
  }));
});
export default StepForm;