/**
 * Created by baoyinghai on 11/17/16.
 */
import React from 'react';
import { autobind } from 'core-decorators';
import { Checkbox } from '../../../../../components/mxa';
import { VIEW, EDIT } from '../../constant';

const CheckboxGroup = Checkbox.Group;

class MyCheckboxGroup extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value
    };
  }

  componentWillReceiveProps(next) {
    if (next.value !== this.state.value) {
      this.state.value = next.value;
    }
  }

  _changeString2Array = str => {
    if (str instanceof Array) {
      return str;
    }
    return str && str.split && str.split(',');
  }

  _changeArray2String = ary => {
    return ary && ary.join && ary.join(',');
  }

  @autobind
  _onChange(value) {
    const { onChange } = this.props;
    const v = this._changeArray2String(value);
    onChange && onChange(v);
    this.setState({
      value: v
    });
  }

  render() {
    return (<CheckboxGroup options={this.props.options} value={this._changeString2Array(this.state.value)} onChange={this._onChange} disabled={this.props.disabled} />);
  }
}

const compRender = config => {
  const { record, props } = config;
  const options = [];
  record.displayComponent && record.displayComponent.dictionaryItems && record.displayComponent.dictionaryItems.forEach((i, index) => {
    options.push({ label: i.value, value: i.code });
  });
  // console.log('#### checkbox group', options);

  return (
    <MyCheckboxGroup options={options} disabled={record.isReadonly || (props.isModalInputMappingItem && props.isLeadInto && props.modalInputIsReadonly)} />
  );
};

/* eslint-disable */
class StaticDisplay extends React.Component {
  render() {
    const value = [];
    this.props.opts && this.props.opts.forEach(item => {
      if (this.props.value && this.props.value.indexOf(item.code) >=0) {
        value.push(item.value);
      }
    });
    return (
      <span>{value.join(', ')}</span>
    );
  }
}

export default {
  [VIEW]: config => {
    const { record } = config;
    const opts = record.displayComponent && record.displayComponent.dictionaryItems && record.displayComponent.dictionaryItems;
    return (
      <StaticDisplay opts={opts} />
    );
  },
  [EDIT]: compRender
};
