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: ['左标题', '右标题'], // 标题集合，顺序从左至右
    targetKeys: [], // 显示在右侧框数据的key集合
    // selectedKeys: [], // 设置哪些项应该被选中
    style: {},
    leftContentStyle: {}, // 左边内容样式
    rightContentStyle: {}, // 右边内容样式
    operationStyle: {}, // 中间控制区域样式
    checkedbox: true,
    notFoundContent: 'empty', // 当列表为空时显示的内容
    onSelectChange: () => {},
  }

  static propTypes = {
    titles: PropTypes.array,
    dataSource: PropTypes.array.isRequired, // 数据源，其中的数据将会被渲染到左边一栏中，targetKeys 中指定的除外。
    targetKeys: PropTypes.array,
    height: PropTypes.number,
    leftWidth: PropTypes.number,
    rightWidth: PropTypes.number,
    // selectedKeys: PropTypes.array,
    onChange: PropTypes.func.isRequired, // 选项在两栏之间转移时的回调函数
    onSelectChange: PropTypes.func, // 选中项发生改变时的回调函数
    style: PropTypes.object,
    leftContentStyle: PropTypes.object,
    rightContentStyle: PropTypes.object,
    operationStyle: PropTypes.object,
    notFoundContent: PropTypes.node,
    checkedbox: PropTypes.bool,
    rowKey: PropTypes.func, // 没有key时指定其它字段代替key  如 rowKey = (obj) => obj.id
    renderHeader: PropTypes.func.isRequired, // (data) => data.header  每行数据渲染函数，该函数的入参为 dataSource 中的项，返回值为 ReactElement。或者返回一个普通对象
    renderContent: PropTypes.func.isRequired, // (data) => data.content
  }

  constructor(props) {
    super(props);
    this.state = {
      sourceSelectedKeys: [], // 左侧选中的key列表
      targetSelectedKeys: [], // 右侧选中的key列表
    };
  }

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

  getSelectedKeysName = direction => (direction === 'left' ? 'sourceSelectedKeys' : 'targetSelectedKeys')
  getIndex = (obj, key) => obj.reduce((a, b) => a.concat(b.pid), []).indexOf(key);

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

    const leftDataSource = [];
    const rightDataSource = new Array(targetKeys.length);
    if (dataSource.length === 0) {
      return {
        leftDataSource, rightDataSource,
      };
    }

    function splitData(target, souce) {
      return {
        leftData: target.filter(item => !souce.includes(item.id)),
        rightData: target.filter(item => souce.includes(item.id)),
      };
    }
    dataSource.forEach((record) => {
      const { rowKey } = this.props;
      if (rowKey) {
        record.pid = rowKey(record);
      }
      if (targetKeys.some(it => it.pid === record.pid)) {
        const children = targetKeys.filter(t => t.pid === record.pid)[0].children;
        const { leftData, rightData } = splitData(record.children, children);
        if (leftData.length > 0) {
          leftDataSource.push({ ...record, children: leftData });
        }
        if (rightData.length > 0) {
          rightDataSource.push({ ...record, children: rightData });
        }
      } else {
        leftDataSource.push(record);
      }
    });
    this.separatedDataSource = {
      leftDataSource,
      rightDataSource,
    };
    return this.separatedDataSource;
  }

  // 合并2个对象
  mergeTargetKeys = (obj1, obj2) => obj1.reduce((pre, next) => {
    if (obj2.some(it => it.pid === next.pid)) {
      const idx = this.getIndex(obj2, next.pid);
      pre[idx].children = pre[idx].children.concat(next.children);
    } else {
      pre.push(next);
    }
    return pre;
  }, [...obj2])


  // 从obj2中过滤obj1
  filterTargetKeys = (obj1, obj2) => { 
    const filterDate = obj1.reduce((pre, next) => {
      if (obj1.length === 0) {
        return obj2;
      }
      const cloneItem = [...pre];
      const idx = this.getIndex(obj2, next.pid);
      const children = pre[idx].children;
      cloneItem[idx].children = children.filter(it => !next.children.includes(it));
      return cloneItem;
    }, obj2);
    return filterDate.filter(it => it.children.length > 0);
  };

  // 移动
  moveTo = (direction) => {
    const { targetKeys = [], onChange } = this.props;
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const moveKeys = direction === 'right' ? sourceSelectedKeys : targetSelectedKeys;
    // 过滤掉禁止的项目
    const newMoveKeys = moveKeys;
    const newTargetKeys = direction === 'right'
      ? this.mergeTargetKeys(targetKeys, newMoveKeys)
      : this.filterTargetKeys(newMoveKeys, targetKeys);
    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');

  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, type) => {
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    let holder = direction === 'left' ? [...sourceSelectedKeys] : [...targetSelectedKeys];
    // 全选 或者反选
    if (typeof type === 'string') {
      holder = !checked
        ? holder.filter(it => it.pid !== selectedItem.pid)
        : holder.filter(it => it.pid === selectedItem.pid).length === 0
          ? holder.concat([selectedItem])
          : holder.map(it => ({ ...it, children: it.pid === selectedItem.pid ? selectedItem.children : it.children }));
    } else {
      holder = checked
        ? this.mergeTargetKeys(selectedItem, holder)
        : this.filterTargetKeys(selectedItem, holder);
    }
    this.handleSelectChange(direction, holder);

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

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

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


  render() {
    const {
      style, titles, checkedbox, notFoundContent, operationStyle, leftContentStyle, rightContentStyle, leftWidth, rightWidth, height, renderContent, renderHeader,
    } = this.props;
    const { sourceSelectedKeys, targetSelectedKeys } = this.state;
    const { leftDataSource, rightDataSource } = this.separateDataSource(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}
          notFoundContent={notFoundContent}
          style={Object.assign({}, { width: leftWidth, height }, leftContentStyle)}
          renderContent={renderContent}
          renderHeader={renderHeader}
        />
        <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}
          notFoundContent={notFoundContent}
          style={Object.assign({}, { width: rightWidth, height }, rightContentStyle)}
          renderContent={renderContent}
          renderHeader={renderHeader}
        />
      </div>
    );
  }
}

export default Transfer;
