"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactSelect = _interopRequireWildcard(require("react-select"));

var _map = _interopRequireDefault(require("lodash/map"));

var _find = _interopRequireDefault(require("lodash/find"));

var _isArray = _interopRequireDefault(require("lodash/isArray"));

var _validation = _interopRequireDefault(require("../../helpers/validation"));

var _TooltipComponent = _interopRequireDefault(require("../TooltipComponent"));

var _FormGenerator = require("../FormGenerator");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _extends() { _extends = Object.assign || 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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

// import { ControlComponent } from '../multiselect/multiSelectCustomControl';
var CustomInput = function CustomInput(Icon) {
  return function (props) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: 'flex'
      }
    }, Icon, /*#__PURE__*/_react["default"].createElement(_reactSelect.components.Input, props));
  };
};
/*eslint-disable*/


function inputComponent(_ref) {
  var inputRef = _ref.inputRef,
      props = _objectWithoutProperties(_ref, ["inputRef"]);

  return /*#__PURE__*/_react["default"].createElement("div", _extends({
    ref: inputRef
  }, props, {
    style: {
      display: 'flex',
      padding: '8px 14px',
      minHeight: 40
    }
  }));
}
/*eslint-disable*/


var CustomControl = function CustomControl(library) {
  return function (props) {
    var TextField = library.TextField;
    var className = props.selectProps.classes && props.selectProps.classes.input;
    return /*#__PURE__*/_react["default"].createElement(TextField, _extends({
      fullWidth: true,
      variant: "outlined",
      InputProps: {
        inputComponent: inputComponent,
        inputProps: _objectSpread({
          className: className,
          inputRef: props.innerRef,
          children: props.children
        }, props.innerProps)
      }
    }, props.selectProps.textFieldProps));
  };
};
/** SelectField Component */


var SelectField = /*#__PURE__*/function (_React$Component) {
  _inherits(SelectField, _React$Component);

  var _super = _createSuper(SelectField);

  function SelectField(props) {
    var _this;

    _classCallCheck(this, SelectField);

    _this = _super.call(this, props);
    _this.state = {
      value: props.attributes.selected,
      errorText: props.attributes.errorText || '',
      selectedOption: _this.getProperValueForReactSelect()
    };
    _this.onChange = _this.onChange.bind(_assertThisInitialized(_this));
    _this.handleChange = _this.handleChange.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(SelectField, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(props) {
      this.setState({
        value: props.attributes.selected,
        errorText: props.attributes.errorText || '',
        selectedOption: this.getProperValueForReactSelect(props.attributes.selected)
      });
    }
  }, {
    key: "validate",
    value: function validate(value) {
      var isValid = true;
      var props = this.props;

      if (props.rules && props.rules.validation) {
        for (var i = 0; i < props.rules.validation.length; i += 1) {
          var data = props.rules.validation[i];
          isValid = _validation["default"][data.rule](value, data.value);

          if (!isValid) {
            return {
              isValid: false,
              message: data.message
            };
          }
        }
      }

      return {
        isValid: true,
        message: ''
      };
    }
  }, {
    key: "onChange",
    value: function onChange() {
      var props = this.props;

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var value = args[0].target.value;
      var validator = this.validate(value);

      if (!validator.isValid) {
        this.setState({
          errorText: validator.message,
          value: value
        });
      } else {
        this.setState({
          errorText: '',
          value: value
        });
      }

      if (typeof props.onChange === 'function') {
        props.onChange(props.control, '', '', value);
      }
    }
  }, {
    key: "handleChange",
    value: function handleChange(selectedOption) {
      var props = this.props;
      this.clearFormData(selectedOption);
      this.setState({
        selectedOption: selectedOption
      });

      if (typeof props.onChange === 'function') {
        var s = (0, _isArray["default"])(selectedOption) ? selectedOption : [selectedOption];
        props.onChange(props.control, '', '', (0, _map["default"])(s, 'value').join(';'));
      }
    }
  }, {
    key: "getProperValueForReactSelect",
    value: function getProperValueForReactSelect(selected) {
      var props = this.props;
      var selectedOption = [];
      var options = props.control.options;
      var o = selected || props.attributes.selected || props.attributes.value;
      var k = (0, _isArray["default"])(o) ? o : o && o.toString().split(';');
      (0, _map["default"])(k, function (value) {
        var f = (0, _find["default"])(options, {
          value: value
        });
        f && selectedOption.push({
          value: f.value,
          label: f.primaryText || f.label || ''
        });
      });
      return selectedOption;
    }
  }, {
    key: "styles",
    value: function styles() {
      var style = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return {
        menu: function menu(base) {
          return Object.assign({}, base, {
            zIndex: '20000 !important'
          }, style.menu);
        },
        control: function control(base) {
          return Object.assign({}, base, style.control);
        },
        placeholder: function placeholder(base) {
          return Object.assign({}, base, style.placeholder);
        },
        singleValue: function singleValue(base) {
          return Object.assign({}, base, style.singleValue);
        },
        input: function input(base) {
          return Object.assign({}, _objectSpread(_objectSpread({}, base), {}, {
            '& input': {
              font: 'inherit'
            }
          }), style.input);
        }
      };
    }
  }, {
    key: "clearFormData",
    value: function clearFormData(selectedOption) {
      var state = this.state;
      var difference = state.selectedOption.filter(function (x) {
        return !selectedOption.includes(x);
      });
      (0, _map["default"])(difference, function (v) {
        (0, _FormGenerator.ClearFormGeneratorByGuid)(v.value);
      });
    }
  }, {
    key: "render",
    value: function render() {
      var props = this.props;
      var SELECTFIELD = props.library[props.component];
      var FORMCONTROL = props.library.FormControl;
      var INPUTLABEL = props.library.InputLabel;
      var FORMHELPERTEXT = props.library.FormHelperText;
      var ICON = props.library.Icon;
      var NOSSR = props.library.NoSsr;
      var OPTION = props.library[props.option];
      var GRID = props.library.Grid;
      var _this$state = this.state,
          selectedOption = _this$state.selectedOption,
          value = _this$state.value,
          errorText = _this$state.errorText;
      var attributes = props.attributes;
      var size = 12;
      return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          display: 'flex'
        }
      }, props.attributes.nativeselect ? /*#__PURE__*/_react["default"].createElement(FORMCONTROL, props.attributes.formControl, /*#__PURE__*/_react["default"].createElement(INPUTLABEL, {
        htmlFor: props.control.id
      }, props.attributes.label), /*#__PURE__*/_react["default"].createElement(SELECTFIELD, _extends({}, attributes, {
        inputProps: {
          name: props.control.id,
          id: props.control.id
        },
        value: value,
        errorText: errorText,
        onChange: this.onChange
      }), props.control.options.map(function (option, index) {
        var primaryText = option.primaryText;
        option = Object.assign({}, option, {
          primaryText: null
        });
        return /*#__PURE__*/_react["default"].createElement(OPTION, _extends({}, option, {
          key: index
        }), primaryText);
      })), /*#__PURE__*/_react["default"].createElement(FORMHELPERTEXT, attributes.errorStyle, props.attributes.errorText)) : /*#__PURE__*/_react["default"].createElement("div", {
        style: Object.assign({}, {
          width: '100%',
          marginTop: '10px',
          marginRight: '5px',
          maxWidth: '100%'
        }, props.attributes.style)
      }, /*#__PURE__*/_react["default"].createElement(NOSSR, null, /*#__PURE__*/_react["default"].createElement(_reactSelect["default"], _extends({}, attributes, {
        components: {
          Input: CustomInput(attributes.inputIcon ? /*#__PURE__*/_react["default"].createElement(ICON, null, attributes.inputIcon) : null),
          Control: CustomControl(props.library)
        },
        textFieldProps: {
          label: attributes.label || attributes.placeholder,
          InputLabelProps: {
            shrink: true
          }
        },
        value: selectedOption,
        onChange: this.handleChange,
        isMulti: attributes.isMulti,
        options: props.control.options.map(function (option) {
          return {
            value: option.value,
            label: option.primaryText || option.label || ''
          };
        }),
        styles: this.styles(attributes.componentstyle)
      })))), props.attributes.tooltip && /*#__PURE__*/_react["default"].createElement(_TooltipComponent["default"], {
        tooltip: props.attributes.tooltip
      })), props.control.addform && selectedOption && (0, _isArray["default"])(selectedOption) && /*#__PURE__*/_react["default"].createElement(GRID, {
        item: true,
        xs: size,
        sm: size,
        md: size,
        xl: size,
        lg: size
      }, /*#__PURE__*/_react["default"].createElement(_FormGenerator.FormGenerator, {
        data: this.pannelData,
        library: props.library,
        guid: ""
      })));
    }
  }, {
    key: "pannelData",
    get: function get() {
      var ui = [];

      try {
        var props = this.props;
        var state = this.state;
        var v = state.selectedOption;

        if (v && (0, _isArray["default"])(v) && v.length <= 10) {
          var p = {
            id: 'expansionpannel',
            type: 'expansionpannel',
            props: {
              id: 'expansionpannel',
              style: {
                marginTop: 15
              }
            },
            options: [],
            layout: {
              xs: {
                col: 12
              },
              sm: {
                col: 12
              },
              md: {
                col: 12
              },
              lg: {
                col: 12
              }
            }
          };

          for (var i = 0; i < v.length; i += 1) {
            var addform = props.control.addform;
            var data = addform.data;
            var t = addform.text;
            var text = addform.showselected ? "".concat(t, " #").concat(v[i].label) : t;
            var guid = v[i].value;
            var patch = props.control.patchdata ? props.control.patchdata[guid] || {} : {};
            var forceUpdate = false; // const currentFormData = currentFormDataByGuid(guid, JSON.parse(JSON.stringify(data)));
            // if (currentFormData) {
            //   data = currentFormData;
            // }

            var k = {
              expansionPanel: {
                defaultExpanded: addform.defaultExpanded || false
              },
              expandIcon: {
                style: {
                  color: '#fff'
                }
              },
              expansionPanelSummary: {
                icon: 'expand_more'
              },
              headerTypography: {
                text: text,
                style: {
                  backgroundColor: "rgb(66, 133, 244)",
                  border: "2px solid rgb(66, 133, 244)",
                  color: "rgb(255, 255, 255)",
                  fontSize: 16,
                  fontWeight: 600,
                  padding: "5px 10px",
                  width: "100%",
                  margin: "-12px"
                }
              },
              expansionPanelDetails: {
                style: {
                  width: '100%'
                }
              },
              content: {
                guid: guid,
                data: data,
                patch: patch,
                forceUpdate: forceUpdate
              }
            };
            p.options.push(k);
          }

          ui.push(p);
        }
      } catch (e) {
        console.log(e);
      }

      return ui;
    }
  }]);

  return SelectField;
}(_react["default"].Component);

SelectField.propTypes = process.env.NODE_ENV !== "production" ? {
  library: _propTypes["default"].object,
  component: _propTypes["default"].string.isRequired,
  attributes: _propTypes["default"].object,
  control: _propTypes["default"].object,
  option: _propTypes["default"].string.isRequired,
  rules: _propTypes["default"].object,
  onChange: _propTypes["default"].func
} : {};
SelectField.defaultProps = {
  library: null,
  attributes: null,
  control: null,
  rules: null,
  onChange: null
};
var _default = SelectField;
exports["default"] = _default;