import React, { PropTypes } from 'react';
import { autobind } from 'core-decorators';
import { Input, Icon, Select } from '../mxa';
import { showModal } from '../../framework/pageContainer/ModalWrapper';
import { LIST_SELECTTYPE } from '../../framework/constant/dictCodes';
import { convertTemplate, trimStart } from '../../framework/utils/StringUtils';

export default class ModalInput extends React.Component {
  static propTypes = {
    onChange: PropTypes.func,
    mapper: PropTypes.func,
    defaultValue: PropTypes.string,
  };

  constructor(props) {
    super(props);
    this.state = {
      values: [],
      selectKeys: []
    };
  }

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

  @autobind
  _onChange(e) {
    const value = e.target.value;
    const { onChange } = this.props;
    console.log(value);
    onChange && onChange(value);
  }

  @autobind
  _showModal() {
    const { children, getParams, ...other } = this.props;
    let p = {};
    if (getParams) {
      const extraParams = getParams && getParams();
      if (!extraParams) {
        return;
      }
      p = Object.assign(p, getParams());
    }
    p.isModalInput = true;
    showModal(p, other.domainType, trimStart(convertTemplate(other.domainLink, { ...other.query, ...other.form.getFieldsValue() }, other.modalData.actionLinkMappings), '/'), this._callback, this.state.selectKeys);
  }

  @autobind
  _multipleOnChange(e, value) {
    e.stopPropagation();
    e.preventDefault();
    const { onChange } = this.props;
    const compValue = this.props.value.split(',').filter(item => item !== value);
    if (compValue.length > 0) {
      let initValue = compValue.shift();
      compValue.forEach(item => {
        initValue += (',' + item);
      });
      console.log(initValue);
      const remoteFieldName = this.props.modalData.mappings[0].remoteFieldName;
      const values = this.state.values.filter(item => {
        return item[remoteFieldName] !== value;
      });
      this._callback(values, LIST_SELECTTYPE.CHECKBOX);
    } else {
      this._callback([], LIST_SELECTTYPE.CHECKBOX);
    }
  }

  @autobind
  _renderMultipleContent(value) {
    const valueArr = value && value.split(',');
    return valueArr && valueArr.map(item => {
      return (
        <div className="multiple-modal-input-content-item"><span>{item}</span><Icon onClick={e => this._multipleOnChange(e, item)} className="item-icon" type="close" /></div>
      );
    });
  }

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


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