/* eslint-disable object-curly-newline */
import React, { Component } from 'react';
import { Table } from 'antd-v4';
import * as utils from '../../../utils/utils';
import * as comFunc from '../ComFunc';
import AntdDraggableModal from '../AntdDraggableModal';

class ModalList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalListVisible: props.modalListVisible,
      scrollX: 1000,
      columns: [],
      data: [],
      selectedRowKeys: [], /* 选中行 */
      sMenuName: '', /* 弹窗标题 */
      copyFromConfig: {}, /* 复制从按钮配置 */
      slaveAssignData: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    let { columns } = this.state;
    const { modalListData, modalListVisible } = nextProps;
    if (utils.isNotEmptyObject(modalListData) && modalListVisible) {
      const { formData, data, sMenuName, copyFromConfig } = modalListData;
      if (utils.isNotEmptyArr(formData)) {
        columns = comFunc.getListHeader(formData[0], columns);
        const scrollX = comFunc.getScrollX(columns);
        this.setState({
          scrollX,
          modalListVisible,
          columns,
          data,
          sMenuName,
          copyFromConfig,
        });
      }
    } else {
      this.setState({ modalListVisible });
    }
  }

  onSelectChange = (selectedRowKeys) => {
    const { data, copyFromConfig } = this.state;
    const slaveData = data.filter(item => selectedRowKeys.includes(item.key));
    const slaveAssign = [utils.returnObjValue(copyFromConfig.sAssignField)];
    const slaveAssignData = comFunc.getCopyToSlaveAssign(slaveData, slaveAssign, {});
    this.setState({ selectedRowKeys, slaveAssignData });
  };

  handleCancel = () => {
    this.setState({
      selectedRowKeys: [],
      modalListVisible: false,
    });
  };

  handleOk = () => {
    const { slaveAssignData } = this.state;
    this.setState({ selectedRowKeys: [] });
    this.props.onModalListData(slaveAssignData);
  };

  render() {
    const { modalListVisible, columns, data, scrollX, selectedRowKeys, sMenuName } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        {
          modalListVisible ?
            <AntdDraggableModal
              visible={modalListVisible}
              width={1000}
              title={sMenuName}
              onCancel={this.handleCancel}
              onOk={this.handleOk}
            >
              <div id="mergeTable">
                <Table
                  bordered
                  size="middle"
                  pagination={false}
                  columns={columns}
                  dataSource={data}
                  rowSelection={rowSelection}
                  scroll={{ x: scrollX, y: 'calc(40vh)' }}
                />
              </div>
            </AntdDraggableModal>
            : ''
        }
      </div>
    );
  }
}

export default ModalList;
