import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _isEqual from "lodash/isEqual";
import React, { useEffect, useState } from "react";
import { connect } from "../../../../editor/redux";
import moment from 'moment';
import { css } from "emotion";
import { set } from 'dot-prop-immutable';
import { SimpleForm as RenderForm, Spin } from '@whalecloud/fdx';
import Element from "../../../components/Element";
import { ElementRoot } from "../../../components/ElementRoot";
import ElementAnimation from "../../../components/ElementAnimation";
import { handleValues } from "../../../../utils/util";

var Form = function Form(props) {
  var elements = props.elements,
      element = props.element,
      initialData = props.initialData,
      forwardedRef = props.forwardedRef,
      save = props.save,
      nameSpace = props.nameSpace,
      updateElement = props.updateElement;
  var _element$data$formSet = element.data.formSettings.initialValues,
      initialValues = _element$data$formSet === void 0 ? {} : _element$data$formSet;

  var _useState = useState(element.data.formInstance),
      _useState2 = _slicedToArray(_useState, 2),
      canRender = _useState2[0],
      setCanRender = _useState2[1];

  var _RenderForm$useForm = RenderForm.useForm(),
      _RenderForm$useForm2 = _slicedToArray(_RenderForm$useForm, 1),
      form = _RenderForm$useForm2[0];

  var defaultVal = Object.keys(initialData).length > 0 ? initialData : initialValues;
  var dateComponents = new Map();
  Object.values(elements).forEach(function (data) {
    var _data$data3, _data$data3$formSetti;

    if (['timePicker', 'datePicker', 'rangePicker'].includes(data.type)) {
      var _data$data, _data$data$formSettin, _data$data2;

      var name = ((_data$data = data.data) === null || _data$data === void 0 ? void 0 : (_data$data$formSettin = _data$data.formSettings) === null || _data$data$formSettin === void 0 ? void 0 : _data$data$formSettin.name) || "".concat(data.type, "_").concat(data.id);
      dateComponents.set(name, (_data$data2 = data.data) === null || _data$data2 === void 0 ? void 0 : _data$data2.formItemSettings);
    } // 将表格数据源作为初始值


    if (['table', 'tableEdit'].includes(data.type) && !defaultVal[(_data$data3 = data.data) === null || _data$data3 === void 0 ? void 0 : (_data$data3$formSetti = _data$data3.formSettings) === null || _data$data3$formSetti === void 0 ? void 0 : _data$data3$formSetti.name]) {
      var _data$data4;

      var _data$data$formSettin2 = (_data$data4 = data.data) === null || _data$data4 === void 0 ? void 0 : _data$data4.formSettings,
          _name = _data$data$formSettin2.name;

      if (!defaultVal[_name]) {
        var _data$data5, _data$data5$component;

        defaultVal[_name] = (_data$data5 = data.data) === null || _data$data5 === void 0 ? void 0 : (_data$data5$component = _data$data5.componentSettings) === null || _data$data5$component === void 0 ? void 0 : _data$data5$component.dataSource;
      }
    }
  });
  Object.keys(defaultVal).forEach(function (key) {
    if (dateComponents.get(key)) {
      if (defaultVal[key].value) {
        if (defaultVal[key] && Array.isArray(defaultVal[key].value)) {
          defaultVal[key] = defaultVal[key].value.map(function (val) {
            return moment(val, defaultVal[key].format);
          });
        } else {
          defaultVal[key] = defaultVal[key] && defaultVal[key].value && moment(defaultVal[key].value, defaultVal[key].format);
        }
      } else {
        var _dateComponents$get = dateComponents.get(key),
            format = _dateComponents$get.format;

        if (typeof defaultVal[key] === 'string' && defaultVal[key].includes(',')) {
          var defaultArr = defaultVal[key].split(',');
          defaultVal[key] = defaultArr.map(function (val) {
            return moment(val, format);
          });
        } else {
          defaultVal[key] = moment(defaultVal[key], format);
        }
      }
    }
  });

  var handleSave = function handleSave(values) {
    if (save) {
      // getFormValue获取转换后的数据
      var newValues = form.getFormValue();
      newValues = handleValues(newValues, element);
      save(newValues);
    }
  };

  useEffect(function () {
    if (!element.data.formInstance) {
      if (forwardedRef) {
        forwardedRef.current = form;
      }

      form.resetFields();
      var newElement = set(element, 'data.formInstance', form);
      updateElement({
        element: newElement
      }, nameSpace);
      setCanRender(form);
    }
  }, [element]);

  var renderChildren = function renderChildren(elements) {
    if (canRender) {
      return elements.map(function (element) {
        return /*#__PURE__*/React.createElement(Element, {
          key: element.id,
          element: element,
          nameSpace: nameSpace
        });
      });
    }

    return /*#__PURE__*/React.createElement(Spin, null);
  };

  return /*#__PURE__*/React.createElement(ElementAnimation, null, /*#__PURE__*/React.createElement(ElementRoot, {
    element: element
  }, function (_ref) {
    var elementStyle = _ref.elementStyle,
        elementAttributes = _ref.elementAttributes,
        customClasses = _ref.customClasses,
        combineClassNames = _ref.combineClassNames;

    var width = elementStyle.width,
        alignItems = elementStyle.alignItems,
        justifyContent = elementStyle.justifyContent,
        containerStyle = _objectWithoutProperties(elementStyle, ["width", "alignItems", "justifyContent"]);

    var formSettings = element.data.formSettings;

    var labelWidth = formSettings.labelWidth,
        restFormSettings = _objectWithoutProperties(formSettings, ["labelWidth"]);

    return /*#__PURE__*/React.createElement("div", Object.assign({
      style: {
        zIndex: 20,
        position: 'relative'
      },
      className: "webiny-pb-layout-form-container " + /*#__PURE__*/css(containerStyle, "label:Form;")
    }, elementAttributes), /*#__PURE__*/React.createElement(RenderForm, Object.assign({
      style: {
        width: width ? width : '100%',
        alignSelf: justifyContent,
        alignItems: alignItems
      },
      form: form,
      className: combineClassNames.apply(void 0, _toConsumableArray(customClasses))
    }, restFormSettings, {
      initialValues: defaultVal // onFieldsChange={onFieldsChange || handleOnFieldsChange}
      ,
      onFinish: handleSave,
      name: "render_".concat(restFormSettings.name) // onFinishFailed={onFinishFailed || onFinishFailedDefault}

    }), renderChildren(element.elements)));
  }));
};

export default connect(function (state, _ref2) {
  var _state$nameSpace;

  var nameSpace = _ref2.nameSpace;
  return {
    elements: (_state$nameSpace = state[nameSpace]) === null || _state$nameSpace === void 0 ? void 0 : _state$nameSpace.elements
  };
}, null, null, {
  areStatePropsEqual: _isEqual
})(Form);
//# sourceMappingURL=Form.js.map