'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = undefined;

var _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; };

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _desc, _value, _class, _class2, _temp;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _coreDecorators = require('core-decorators');

var _mxa = require('../mxa');

var _ModalWrapper = require('../../framework/pageContainer/ModalWrapper');

var _dictCodes = require('../../framework/constant/dictCodes');

var _StringUtils = require('../../framework/utils/StringUtils');

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

var ModalInput = (_class = (_temp = _class2 = function (_React$Component) {
  _inherits(ModalInput, _React$Component);

  function ModalInput(props) {
    _classCallCheck(this, ModalInput);

    var _this = _possibleConstructorReturn(this, (ModalInput.__proto__ || Object.getPrototypeOf(ModalInput)).call(this, props));

    _this._getValue = function () {
      var value = _this.props.value;
      var dictionaryItems = _this.props.record.displayComponent.dictionaryItems;
      if (dictionaryItems && dictionaryItems.length > 0) {
        var filterRes = dictionaryItems.filter(function (item) {
          return item.code === value;
        });
        if (filterRes.length > 0) {
          value = filterRes[0].value;
        }
      }
      return value;
    };

    _this.state = {
      values: [],
      selectKeys: []
    };
    return _this;
  }

  _createClass(ModalInput, [{
    key: '_callback',
    value: function _callback(value, selectType, mainEntityKey) {
      var _this2 = this;

      var _props = this.props,
          mapper = _props.mapper,
          onChange = _props.onChange,
          resetValue = _props.resetValue;

      if (value.length > 0) {
        if (selectType === _dictCodes.LIST_SELECTTYPE.CHECKBOX) {
          (function () {
            var valueClone = JSON.parse(JSON.stringify(value));
            var selectKeys = [];
            value.forEach(function (item) {
              return selectKeys.push(item[mainEntityKey]);
            });
            _this2.setState({
              values: valueClone,
              selectKeys: selectKeys
            });
          })();
        }
        var displayValue = value[0];
        if (value.length > 1) {
          value.shift();
          value.reduce(function (temp, item) {
            Object.keys(item).forEach(function (item1) {
              temp[item1] += ',' + item[item1];
            });
            return temp;
          }, displayValue);
        }
        var newValue = displayValue;
        if (mapper !== undefined && newValue) {
          displayValue = mapper !== undefined ? mapper(newValue) : newValue;
        }
        resetValue && resetValue(newValue, value.length === 1 && selectType === _dictCodes.LIST_SELECTTYPE.CHECKBOX);
        onChange && onChange(displayValue);
      } else {
        resetValue && resetValue({}, false);
      }
    }
  }, {
    key: '_onChange',
    value: function _onChange(e) {
      var value = e.target.value;
      var onChange = this.props.onChange;

      console.log(value);
      onChange && onChange(value);
    }
  }, {
    key: '_showModal',
    value: function _showModal() {
      var _props2 = this.props,
          children = _props2.children,
          getParams = _props2.getParams,
          other = _objectWithoutProperties(_props2, ['children', 'getParams']);

      var p = {};
      if (getParams) {
        var extraParams = getParams && getParams();
        if (!extraParams) {
          return;
        }
        p = Object.assign(p, getParams());
      }
      p.isModalInput = true;
      (0, _ModalWrapper.showModal)(p, other.domainType, (0, _StringUtils.trimStart)((0, _StringUtils.convertTemplate)(other.domainLink, _extends({}, other.query, other.form.getFieldsValue()), other.modalData.actionLinkMappings), '/'), this._callback, this.state.selectKeys);
    }
  }, {
    key: '_multipleOnChange',
    value: function _multipleOnChange(e, value) {
      var _this3 = this;

      e.stopPropagation();
      e.preventDefault();
      var onChange = this.props.onChange;

      var compValue = this.props.value.split(',').filter(function (item) {
        return item !== value;
      });
      if (compValue.length > 0) {
        (function () {
          var initValue = compValue.shift();
          compValue.forEach(function (item) {
            initValue += ',' + item;
          });
          console.log(initValue);
          var remoteFieldName = _this3.props.modalData.mappings[0].remoteFieldName;
          var values = _this3.state.values.filter(function (item) {
            return item[remoteFieldName] !== value;
          });
          _this3._callback(values, _dictCodes.LIST_SELECTTYPE.CHECKBOX);
        })();
      } else {
        this._callback([], _dictCodes.LIST_SELECTTYPE.CHECKBOX);
      }
    }
  }, {
    key: '_renderMultipleContent',
    value: function _renderMultipleContent(value) {
      var _this4 = this;

      var valueArr = value && value.split(',');
      return valueArr && valueArr.map(function (item) {
        return _react2.default.createElement(
          'div',
          { className: 'multiple-modal-input-content-item' },
          _react2.default.createElement(
            'span',
            null,
            item
          ),
          _react2.default.createElement(_mxa.Icon, { onClick: function onClick(e) {
              return _this4._multipleOnChange(e, item);
            }, className: 'item-icon', type: 'close' })
        );
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this5 = this;

      var value = this._getValue();
      if (this.props.selectType && this.props.selectType === _dictCodes.LIST_SELECTTYPE.CHECKBOX) {
        return _react2.default.createElement(
          'div',
          { className: 'multiple-modal-input', onClick: this._showModal },
          _react2.default.createElement(
            'div',
            { className: 'multiple-modal-input-content' },
            this._renderMultipleContent(value)
          )
        );
      }
      return _react2.default.createElement(_mxa.Input, {
        addonAfter: _react2.default.createElement(
          'div',
          { style: { display: 'inline-block' } },
          !this.props.isReadonly && _react2.default.createElement(_mxa.Icon, { type: 'bars', onClick: this._showModal, style: { paddingRight: 7, borderRight: '1px black solid' } }),
          _react2.default.createElement(_mxa.Icon, {
            type: 'delete',
            onClick: function onClick() {
              _this5.props.resetValue('');
              _this5.props.onChange();
            },
            style: { paddingLeft: !this.props.isReadonly ? 7 : 0 }
          })
        )
        // defaultValue={this.props.defaultValue}
        , disabled: this.props.disabled,
        onClick: this.props.isReadonly && this._showModal,
        value: value,
        onChange: !this.props.isReadonly && this._onChange
      });
    }
  }]);

  return ModalInput;
}(_react2.default.Component), _class2.propTypes = {
  onChange: _react.PropTypes.func,
  mapper: _react.PropTypes.func,
  defaultValue: _react.PropTypes.string
}, _temp), (_applyDecoratedDescriptor(_class.prototype, '_callback', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_callback'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_onChange', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_onChange'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_showModal', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_showModal'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_multipleOnChange', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_multipleOnChange'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_renderMultipleContent', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_renderMultipleContent'), _class.prototype)), _class);
exports.default = ModalInput;