/**
 * Created by baoyinghai on 2/20/17.
 */
import React from 'react';
import { VIEW, EDIT } from '../../constant';
import { Transfer } from '../../../../../components/mxa';


class MyTransfer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedKeys: [],
      targetKeys: (this.props.value || '').split(',')
    };
  }

  componentWillReceiveProps(next) {
    if (next.value !== this.props.value) {
      this.state.targetKeys = (this.props.value || '').split(',');
    }
  }

  handleChange = (nextTargetKeys = [], direction, moveKeys) => {
    const { onChange } = this.props;
    this.setState({ targetKeys: nextTargetKeys });
    onChange && onChange(nextTargetKeys.join(','));
  };

  handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    this.setState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
  };

  render() {
    const state = this.state;
    return (
      <Transfer
        showSearch={true}
        listStyle={{
          width: 300,
          height: 300
        }}
        dataSource={this.props.dataSource}
        targetKeys={state.targetKeys}
        selectedKeys={state.selectedKeys}
        onChange={this.handleChange}
        onSelectChange={this.handleSelectChange}
        render={item => item.title}
        titles={this.props.titles || ['Source', 'Target']}
      />
    );
  }
}

const compRender = config => {
  const { record, props } = config;
  const dataSource = record.displayComponent.dictionaryItems && record.displayComponent.dictionaryItems.map(item => {
    return {
      key: item.code,
      title: item.value,
      description: 'description of content' + item.value
    };
  });
  return (
    <MyTransfer dataSource={dataSource} titles={record.displayComponent.titles} />
  );
};


/* 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
};
