import React, { Component } from 'react';
import Operation from './Operation';
import TransferItem from './TransferItem';
import PropTypes from 'prop-types';
import './transfer.scss';

class Transfer extends Component {
  static defaultProps = {
    leftWidth: 360,
    rightWidth: 360,
    height: 270,
    titles: ['左标题', '右标题'], // 标题集合，顺序从左至右
    dataSource: [], // 数据源，其中的数据将会被渲染到左边一栏中，targetKeys 中指定的除外。
    targetKeys: [], // 显示在右侧框数据的key集合
    render: () => {}, // 每行数据渲染函数，该函数的入参为 dataSource 中的项，返回值为 ReactElement。或者返回一个普通对象
    selectedKeys: [], // 设置哪些项应该被选中
    onChange: () => {}, // 选项在两栏之间转移时的回调函数
    onSelectChange: () => {}, // 选中项发生改变时的回调函数
    style: {},
    leftContentStyle: {}, // 左边内容样式
    rightContentStyle: {}, // 右边内容样式
    operationStyle: {}, // 中间控制区域样式
    checkedbox: true,
    isTable: false,
    notFoundContent: 'empty', // 当列表为空时显示的内容
  }

  static propTypes = {
    titles: PropTypes.array.isRequired,
    dataSource: PropTypes.array.isRequired,
    targetKeys: PropTypes.array.isRequired,
    render: PropTypes.func.isRequired,
    selectedKeys: PropTypes.array,
    onChange: PropTypes.func.isRequired,
    onSelectChange: PropTypes.func,
    style: PropTypes.object,
    checkedbox: PropTypes.bool,
    isTable: PropTypes.bool,
    rowKey: PropTypes.func, // 没有key时指定其它字段代替key  如 rowKey = (obj) => obj.id
  }

  constructor(props) {
    super(props);
    const { selectedKeys, targetKeys } = props;
    this.state = {
      sourceSelectedKeys: selectedKeys.filter(key => targetKeys.indexOf(key) === -1), // 左侧选中的key列表
      targetSelectedKeys: selectedKeys.filter(key => targetKeys.indexOf(key) > -1), // 右侧选中的key列表
    };
  }

  componentWillReceiveProps(nextProps) {
    // 清除缓存
    if (nextProps.targetKeys !== this.props.targetKeys ||
      nextProps.dataSource !== this.props.dataSource) {
      this.separatedDataSource = null;
    }
  }

  getRenderContent = (props) => {
    if (this.renderConent) {
      return this.renderConent;
    }
    const { render, dataSource, isTable } = props;
    let renderLeftTable = null;
    let renderRightTable = null;
    if (!isTable) {
      renderLeftTable = render;
      renderRightTable = render;
    } else {
      const renderTableContent = render(dataSource);
      if (Object.prototype.toString.call(renderTableContent) === '[object Object]') {
        renderLeftTable = renderTableContent;
        renderRightTable = renderTableContent;
      } else {
        renderLeftTable = renderTableContent[0];
        renderRightTable = renderTableContent[1];
      }
    }

    this.renderConent = {
      renderLeftTable, renderRightTable,
    };
    return this.renderConent;
  }

  getSelectedKeysName = direction => (direction === 'left' ? 'sourceSelectedKeys' : 'targetSelectedKeys')

  // 获取左右2边数据
  separateDataSource = (props) => {
    if (this.separatedDataSource) {
      return this.separatedDataSource;
    }
    const { dataSource, rowKey, targetKeys } = props;

    const leftDataSource = [];
    const rightDataSource = new Array(targetKeys.length);
    if (dataSource.length === 0) {
      return {
        leftDataSource, rightDataSource,
      };
    }
    dataSource.forEach((record) => {
      // 如果数据没有key，务必使用 rowKey 来指定数据列的主键。
      if (rowKey) {
        record.key = rowKey(record);
      }

      const indexOfKey = targetKeys.indexOf(record.key);
      if (indexOfKey !== -1) {
        rightDataSource[indexOfKey] = record;
      } else {
        leftDataSource.push(record);
      }
    });

    this.separatedDataSource = {
      leftDataSource,
      rightDataSource,
    };
    return this.separatedDataSource;
  }

  // 移动
  moveTo = (direction) => {
    const { targetKeys = [], dataSource = [], onChange } = this.props;
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const moveKeys = direction === 'right' ? sourceSelectedKeys : targetSelectedKeys;
    // 过滤掉禁止的项目
    const newMoveKeys = moveKeys.filter(key =>
      !dataSource.some(data => !!(key === data.key && data.disabled)));
    const newTargetKeys = direction === 'right'
      ? newMoveKeys.concat(targetKeys)
      : targetKeys.filter(targetKey => newMoveKeys.indexOf(targetKey) === -1);

    const oppositeDirection = direction === 'right' ? 'left' : 'right';
    // 清空选中列表
    this.setState({
      [this.getSelectedKeysName(oppositeDirection)]: [],
    });
    this.handleSelectChange(oppositeDirection, []);
    if (onChange) {
      onChange(newTargetKeys, direction, newMoveKeys);
    }
  }

  moveToLeft = () => this.moveTo('left');
  moveToRight = () => this.moveTo('right');

  // 全选
  handleSelectAll = (direction, filteredDataSource, checkAll) => {
    const originalSelectedKeys = this.state[this.getSelectedKeysName(direction)] || [];
    const currentKeys = filteredDataSource.map(item => item.key);
    const newKeys1 = originalSelectedKeys.filter(key => currentKeys.indexOf(key) === -1);
    const newKeys2 = [...originalSelectedKeys];
    currentKeys.forEach((key) => {
      if (newKeys2.indexOf(key) === -1) {
        newKeys2.push(key);
      }
    });
    const holder = checkAll ? newKeys1 : newKeys2;
    this.handleSelectChange(direction, holder);

    this.setState({
      [this.getSelectedKeysName(direction)]: holder,
    });
  }

  handleLeftSelectAll = (filteredDataSource, checkAll) => (
    this.handleSelectAll('left', filteredDataSource, checkAll)
  )
  handleRightSelectAll = (filteredDataSource, checkAll) => (
    this.handleSelectAll('right', filteredDataSource, checkAll)
  )

  handleSelectChange(direction, holder) {
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const onSelectChange = this.props.onSelectChange;
    if (!onSelectChange) {
      return;
    }

    if (direction === 'left') {
      onSelectChange(holder, targetSelectedKeys);
    } else {
      onSelectChange(sourceSelectedKeys, holder);
    }
  }

  // 单选
  handleSelect = (direction, selectedItem, checked) => {
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const holder = direction === 'left' ? [...sourceSelectedKeys] : [...targetSelectedKeys];
    const index = holder.indexOf(selectedItem.key);
    if (index > -1) {
      holder.splice(index, 1);
    }
    if (checked) {
      holder.push(selectedItem.key);
    }
    this.handleSelectChange(direction, holder);

    this.setState({
      [this.getSelectedKeysName(direction)]: holder,
    });
  }

  handleLeftSelect = (selectedItem, checked) => this.handleSelect('left', selectedItem, checked)

  handleRightSelect = (selectedItem, checked) => this.handleSelect('right', selectedItem, checked)


  render() {
    const {
      style, titles, checkedbox, notFoundContent, operationStyle, isTable, leftContentStyle, rightContentStyle,
    } = this.props;
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const { leftDataSource, rightDataSource } = this.separateDataSource(this.props);
    const { renderLeftTable, renderRightTable } = this.getRenderContent(this.props);
    const leftActive = targetSelectedKeys.length > 0;
    const rightActive = sourceSelectedKeys.length > 0;
    return (
      <div style={style} className="ui-transfer">
        <TransferItem
          title={titles[0]}
          checkedbox={checkedbox}
          dataSource={leftDataSource}
          checkedKeys={sourceSelectedKeys}
          handleSelect={this.handleLeftSelect}
          handleSelectAll={this.handleLeftSelectAll}
          render={renderLeftTable}
          notFoundContent={notFoundContent}
          isTable={isTable}
          style={leftContentStyle}
        />
        <Operation
          moveToRight={this.moveToRight}
          moveToLeft={this.moveToLeft}
          leftActive={leftActive}
          rightActive={rightActive}
          style={operationStyle}
        />
        <TransferItem
          title={titles[1]}
          checkedbox={checkedbox}
          dataSource={rightDataSource}
          checkedKeys={targetSelectedKeys}
          handleSelect={this.handleRightSelect}
          handleSelectAll={this.handleRightSelectAll}
          render={renderRightTable}
          notFoundContent={notFoundContent}
          isTable={isTable}
          style={rightContentStyle}
        />
      </div>
    );
  }
}

export default Transfer;
