import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState } from "react";
import { fetch } from '@fishx/rest';
import { connect } from "../../../redux";
import { set } from "dot-prop-immutable";
import { i18n } from '@fishx/i18n';
import { getActiveElement, getElementWithChildren } from "../../../selectors";
import { toolFormAttr } from "../../../utils";
import { SimpleForm as Form, Switch, Input, Select, Divider, Tooltip, message as Message } from '@whalecloud/fdx';
import CustomInput from "../../../components/CustomInput";
import WidthSetting from "./WidthSetting";
import GridSettings from "./CommonGridSettings";
import CommonStyleSettings from "./CommonStyleSettings";
var itemKey = 'data.formItemSettings';
var formmKey = 'data.formSettings';
var outputKey = 'data.formSettings.dependency.source.output';
var defaultOutputKey = 'data.formSettings.dependency.source.defaultOutput';

var CommonItemSettings = function CommonItemSettings(props) {
  var _rules$, _rules$2;

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

  var options = [{
    label: i18n('PAGEBUIDER_SETTINGS_UNSET'),
    value: false
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_REQUIRED_ITEM'),
    value: true
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_CHINESE'),
    value: "^[\\u0391-\\uFFE5]+$"
  }];
  var updateElement = props.updateElement,
      element = props.element,
      defaultValueHide = props.defaultValueHide,
      allowClearHide = props.allowClearHide,
      FormNameHide = props.FormNameHide,
      formLabelHide = props.formLabelHide,
      placeholderHide = props.placeholderHide,
      disabledHide = props.disabledHide,
      requiredHide = props.requiredHide,
      showAutoInitialize = props.showAutoInitialize;
  var _element$data = element.data;
  _element$data = _element$data === void 0 ? {} : _element$data;
  var _element$data$formIte = _element$data.formItemSettings,
      formItemSettings = _element$data$formIte === void 0 ? {} : _element$data$formIte,
      _element$data$formSet = _element$data.formSettings,
      formSettings = _element$data$formSet === void 0 ? {} : _element$data$formSet,
      type = element.type,
      id = element.id;
  var name = formItemSettings.name || "".concat(type, "_").concat(id);
  var _formItemSettings$all = formItemSettings.allowClear,
      allowClear = _formItemSettings$all === void 0 ? false : _formItemSettings$all,
      _formItemSettings$def = formItemSettings.defaultValue,
      defaultValue = _formItemSettings$def === void 0 ? '' : _formItemSettings$def,
      placeholder = formItemSettings.placeholder,
      mode = formItemSettings.mode,
      _formItemSettings$aut = formItemSettings.autoInitialize,
      autoInitialize = _formItemSettings$aut === void 0 ? false : _formItemSettings$aut,
      _formItemSettings$for = formItemSettings.format,
      format = _formItemSettings$for === void 0 ? 'YYYY-MM-DD' : _formItemSettings$for,
      remote = formItemSettings.remote,
      remoteMode = formItemSettings.remoteMode;
  var label = formSettings.label,
      _formSettings$require = formSettings.required,
      required = _formSettings$require === void 0 ? false : _formSettings$require,
      _formSettings$rules = formSettings.rules,
      rules = _formSettings$rules === void 0 ? [] : _formSettings$rules,
      requireOptions = formSettings.requireOptions,
      requiredText = formSettings.requiredText,
      _formSettings$depende = formSettings.dependency,
      dependency = _formSettings$depende === void 0 ? {} : _formSettings$depende;
  var message = ((_rules$ = rules[0]) === null || _rules$ === void 0 ? void 0 : _rules$.message) || i18n('PAGEBUIDER_SETTINGS_REQUIRED_TIPS');
  var defaultVal = defaultValue;

  if (['timePicker', 'datePicker', 'rangePicker'].includes(type) && defaultValue.value) {
    defaultVal = Array.isArray(defaultValue.value) ? defaultValue.value.join(',') : defaultValue.value;
  }

  var initialValues = {
    'item-allowClear': allowClear,
    'item-defaultValue': defaultVal,
    'item-placeholder': placeholder,
    'item-name': name,
    'form-label': label,
    'form-required': rules.length > 0 && !requiredText ? true : requiredText,
    'form-message': message,
    'item-autoInitialize': autoInitialize
  };

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      option = _useState2[0],
      setOption = _useState2[1];

  var _useState3 = useState(requireOptions || options),
      _useState4 = _slicedToArray(_useState3, 2),
      optionArr = _useState4[0],
      setOptionArr = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      tooltipVisible = _useState6[0],
      setTooltipVisible = _useState6[1];

  var onOptionChange = function onOptionChange(event) {
    setOption(event.target.value);
    setTooltipVisible(false);
  };

  var addItem = function addItem() {
    if (option) {
      var optionObj = {
        label: option,
        value: option
      };
      var newArr = [].concat(_toConsumableArray(optionArr), [optionObj]);
      setOptionArr(newArr);
      var newElement = set(element, "".concat(formmKey, ".requireOptions"), newArr);
      updateElement({
        element: newElement
      });
    } else {
      setTooltipVisible(true);
    }
  };

  var handleRmoteDependencyOptions = function handleRmoteDependencyOptions(obj, key) {
    var newElement = set(element, "".concat(itemKey, ".autoInitialize"), true);
    newElement = set(newElement, key, obj);
    updateElement({
      element: newElement
    });
    Message.success(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_SUCCESS'));
  };

  var handleRemoteOptions = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(obj, key) {
      var _obj$url, url, _obj$method, method, _obj$params, params, _yield$fetch, data, optionsValue, newElement;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _obj$url = obj.url, url = _obj$url === void 0 ? '' : _obj$url, _obj$method = obj.method, method = _obj$method === void 0 ? 'GET' : _obj$method, _obj$params = obj.params, params = _obj$params === void 0 ? {} : _obj$params;

              if (!(url.indexOf('${value}') > 0)) {
                _context.next = 5;
                break;
              }

              // 设置级联远程动态数据源
              handleRmoteDependencyOptions(obj, key);
              _context.next = 16;
              break;

            case 5:
              _context.prev = 5;
              _context.next = 8;
              return fetch(url, {
                method: method,
                data: _objectSpread({}, params)
              });

            case 8:
              _yield$fetch = _context.sent;
              data = _yield$fetch.data;

              if (data) {
                optionsValue = _toConsumableArray(data);
                newElement = set(element, "".concat(itemKey, ".autoInitialize"), true);
                newElement = set(newElement, key, optionsValue);
                updateElement({
                  element: newElement
                });
                Message.success(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_SUCCESS'));
              } else {
                Message.error(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_FAIL'));
              }

              _context.next = 16;
              break;

            case 13:
              _context.prev = 13;
              _context.t0 = _context["catch"](5);
              Message.error(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_FAIL'));

            case 16:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[5, 13]]);
    }));

    return function handleRemoteOptions(_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }();

  var onFormChange = function onFormChange(obj) {
    Object.keys(obj).forEach(function (key) {
      var newElement = element;
      var changeFlag = true;
      var propName, relKey, value;

      if (key === 'item-defaultValue') {
        value = obj[key];

        if (type === 'rate') {
          value = Number(value);
        }

        if (mode || ['cascader', 'checkBoxGroup'].includes(type)) {
          var arr = [];
          value.split(',').forEach(function (val) {
            arr.push(val);
          });
          value = arr;
        }

        if (['timePicker', 'datePicker', 'rangePicker'].includes(type)) {
          var relValue = obj[key];

          if (obj[key].includes(',')) {
            relValue = obj[key].split(',');
          }

          value = {
            value: relValue,
            format: format
          };
        }

        relKey = key.split('-')[1];
        propName = "".concat(itemKey, ".").concat(relKey);
        newElement = set(element, propName, value); // handleInitialValues(name, value)
      } else if (key.includes('item-')) {
        relKey = key.split('-')[1];
        value = obj[key];

        if (relKey === 'autoInitialize') {
          if (obj[key]) {
            // 远程数据源
            if (Object.keys(remote).length > 0 && remoteMode) {
              changeFlag = false;
              handleRemoteOptions(remote, "".concat(itemKey, ".options"));
            } // 级联远程数据源


            if (dependency && dependency.source) {
              var _dependency$source = dependency.source,
                  _dependency$source$ou = _dependency$source.output_metadata,
                  output_metadata = _dependency$source$ou === void 0 ? {} : _dependency$source$ou,
                  _dependency$source$de = _dependency$source.defaultOutput_metadata,
                  defaultOutput_metadata = _dependency$source$de === void 0 ? {} : _dependency$source$de;

              if (output_metadata.remote && output_metadata.remoteMode) {
                changeFlag = false;
                handleRemoteOptions(output_metadata.remote, outputKey);
              }

              if (defaultOutput_metadata.remote && defaultOutput_metadata.remoteMode) {
                changeFlag = false;
                handleRemoteOptions(defaultOutput_metadata.remote, defaultOutputKey);
              }
            }
          }
        }

        if (changeFlag) {
          propName = "".concat(itemKey, ".").concat(relKey);
          newElement = set(element, propName, value);
        }
      } else if (key === 'form-required') {
        newElement = element;
        relKey = key.split('-')[1];
        propName = "".concat(formmKey, ".rules");
        value = obj[key];

        if (typeof obj[key] === 'boolean') {
          value = obj[key] ? [{
            required: obj[key],
            message: message
          }] : [];
          newElement = set(newElement, propName, value);
          propName = "".concat(formmKey, ".requiredText");
          newElement = set(newElement, propName, obj[key]);
        } else {
          value = [{
            required: true,
            pattern: obj[key],
            message: message
          }];
          newElement = set(newElement, propName, value);
          propName = "".concat(formmKey, ".requiredText");
          newElement = set(newElement, propName, obj[key]);
        }
      } else if (key === 'form-message') {
        propName = "".concat(formmKey, ".rules");
        var oldRule = rules[0] || {};
        value = [_objectSpread(_objectSpread({}, oldRule), {}, {
          message: obj[key]
        })];
        newElement = set(element, propName, value);
      } else if (key.includes('form-')) {
        relKey = key.split('-')[1];
        propName = "".concat(formmKey, ".").concat(relKey);
        newElement = set(element, propName, obj[key]);
      }

      if (changeFlag) {
        // 数据源已单独更新，无需再次更新
        updateElement({
          element: newElement
        });
      }
    });
  };

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form, Object.assign({}, toolFormAttr, {
    form: form,
    initialValues: initialValues,
    onValuesChange: onFormChange
  }), !FormNameHide && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_NAME'),
    name: "item-name"
  }, /*#__PURE__*/React.createElement(CustomInput, {
    inputProps: {
      placeholder: 'Input the form field name'
    }
  })), !formLabelHide && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_LABEL_TEXT'),
    name: "form-label"
  }, /*#__PURE__*/React.createElement(CustomInput, {
    inputProps: {
      placeholder: 'Input the form field label text'
    }
  })), !placeholderHide && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_PLACE_HOLDER'),
    name: "item-placeholder"
  }, /*#__PURE__*/React.createElement(CustomInput, {
    inputProps: {
      placeholder: i18n('PAGEBUIDER_SETTINGS_PLACEHOLDER_PLACEHOLDER')
    }
  })), /*#__PURE__*/React.createElement(GridSettings, null), /*#__PURE__*/React.createElement(WidthSetting, null), !defaultValueHide && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_DEFAULT_VALUE'),
    name: "item-defaultValue"
  }, /*#__PURE__*/React.createElement(CustomInput, {
    inputProps: {
      placeholder: i18n('PAGEBUIDER_SETTINGS_PLACEHOLDER_DEFAULT_VALUE')
    }
  })), !allowClearHide && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_ALLOW_CLEAR'),
    name: "item-allowClear",
    valuePropName: "checked"
  }, /*#__PURE__*/React.createElement(Switch, null)), !requiredHide && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_REQUIRED'),
    name: "form-required"
  }, /*#__PURE__*/React.createElement(Select, {
    style: {
      width: '100%'
    },
    placeholder: i18n('PAGEBUIDER_SETTINGS_TIPS_REQUIRE_SELECT'),
    dropdownRender: function dropdownRender(menu) {
      return /*#__PURE__*/React.createElement("div", null, menu, /*#__PURE__*/React.createElement(Divider, {
        style: {
          margin: '4px 0'
        }
      }), /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          flexWrap: 'nowrap',
          padding: 8,
          alignItems: 'center'
        }
      }, /*#__PURE__*/React.createElement(Tooltip, {
        title: i18n('PAGEBUIDER_SETTINGS_TIPS_ACCEPT_TYPE'),
        visible: tooltipVisible
      }, /*#__PURE__*/React.createElement(Input, {
        style: {
          flex: 'auto'
        },
        value: option,
        onChange: onOptionChange,
        placeholder: i18n('PAGEBUIDER_SETTINGS_TIPS_REQUIRE_INPUT')
      })), /*#__PURE__*/React.createElement("a", {
        style: {
          flex: 'none',
          padding: '8px',
          display: 'block',
          cursor: 'pointer'
        },
        onClick: addItem
      }, i18n('PAGEBUIDER_SETTINGS_ADD_ITEM'))));
    },
    options: optionArr
  })), (required || ((_rules$2 = rules[0]) === null || _rules$2 === void 0 ? void 0 : _rules$2.required)) && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_MESSAGE'),
    name: "form-message"
  }, /*#__PURE__*/React.createElement(CustomInput, {
    inputType: "textArea"
  }))), showAutoInitialize && /*#__PURE__*/React.createElement(Form.Item, {
    label: i18n('PAGEBUIDER_SETTINGS_AUTO_INITILIZE'),
    name: "item-autoInitialize",
    valuePropName: "checked"
  }, /*#__PURE__*/React.createElement(Switch, null))), /*#__PURE__*/React.createElement(CommonStyleSettings, null));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  var ele = getActiveElement(state);
  var element = getElementWithChildren(state, ele.id);
  return {
    element: element
  };
}, mapDispatchToProps)(CommonItemSettings);
//# sourceMappingURL=CommonItemSettings.js.map