import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { CardPane, Search, Button, Select } from 'amos-framework';
import AmosGridTable from '../../../component/table/table/AmosGridTable';
import { getRoutePointInputItemAction } from '../../../../services/routeService';

const Option = Select.Option;
const riskLevelData = [{ id: -1, level: '无等级' }, { id: 1,level: '1级' }, { id: 2,level: '2级' }, { id: 3,level: '3级' }, { id: 4,level: '4级' }, { id: 5,level: '5级' }];
const riskLevelEum = { 1: '1级',2: '2级', 3: '3级', 4: '4级', 5: '5级' };
const getColumns = () =>{
  return [
    {
      title: '编码',
      dataIndex: 'itemNo',
      key: 'itemNo',
      width: '15%'
    },{
      title: '名称',
      dataIndex: 'inputName',
      key: 'inputName',
      width: '30%'
    },{
      title: '扩展分类',
      dataIndex: 'classifyName',
      key: 'classifyName',
      width: '15%'

    },{
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: '10%',
      render: text => riskLevelEum[text]
    },{
      title: '类型',
      dataIndex: 'itemType',
      key: 'itemType',
      width: '10%'

    },{
      title: '必填',
      dataIndex: 'isMust',
      key: 'isMust',
      width: '10%'
    },{
      title: '评分',
      dataIndex: 'isScore',
      key: 'isScore',
      width: '10%'
    }
  ];
};

/**
 * 检查项
 *
 * @class PointIntemModal
 * @extends {Component}
 */
class PointIntemModal extends Component{
  constructor(props) {
    super(props);
    this.state = {
      pagination: false,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      selectData: [],
      count: 0,
      classify: [],
      classifyId: '',
      level: '',
      requestParam: [],
      inputName: '',
      selectArray: [],
    };
  }
  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    const { pointId, routeId } = this.props;
    pointId && this.setState({ pointId });
    routeId && this.setState({ routeId });
  };

  onChange = (e, value) => {
    this.setState({ inputName: value });
  }

  onIconClick = (e, value) => {
    const { pointId, routeId, inputName, level, classifyId } = this.state;
    let body = {};
    body.pointId = pointId;
    body.routeId = routeId;
    body.inputName = inputName;
    body.level = level;
    body.classifyId = classifyId;
    this.getSelectChangeData(body);
  }

  onSelectChange =(key,value)=>{
    const { pointId, routeId, inputName, level, classifyId } = this.state;
    let body = {};
    body.inputName = inputName;
    body.routeId = routeId;
    body.pointId = pointId;
    key === 'level' ? body.classifyId = classifyId : body.level = level;
    body[key] = value;
    this.getSelectChangeData(body);
    this.setState({ [key]: value });
  }

  getSelectChangeData = (body) => {
    let { selectedRowKeys } = this.state;
    getRoutePointInputItemAction(body).then(data => {
      // let selectData = data.routePointItem.filter(item =>item.isBound === 'bound');
      // let boundKeys = selectData.map(item=>{return item.tempId; });
      this.setState({ data: data.routePointItem, selectedRowKeys: selectedRowKeys });
    });
  }

  /**
   * 分页设置参数
  */
  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.pageNumber = current;
    }
  }

  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    let { selectData, classifyId } = this.state;
    const {PointItemArray,changePointItemArray} = this.props;
    let newSelectData = selectData.slice();
    if (classifyId) {
      let index = newSelectData.findIndex(item =>item.pointClassifyId === classifyId );
      while (index >= 0){
        newSelectData.splice(index,1);
        index = newSelectData.findIndex(item =>item.pointClassifyId === classifyId );
      }
      this.setState({ selectData: [...selectedRows, ...newSelectData], selectedRows, selectedRowKeys });
    } else {
      this.setState({ selectData: selectedRows, selectedRows, selectedRowKeys });
    }
    
    PointItemArray[selectedRows[0].pointId] = selectedRowKeys;
    changePointItemArray(PointItemArray);
  };


  getDeleteItem =()=>{
    let { data, selectedRowKeys } = this.state;
    let newData = data.slice();
    for (let key of selectedRowKeys){
      let index = newData.indexOf(newData.filter(e=>e.tempId === key)[0]);
      newData.splice(index,1);
    }
    let waitReturn = newData.filter(e=>e.isBound === 'bound');
    waitReturn.map(it => it.isDelete = true);
    return waitReturn;
  }

  chooseChange =(e, key) => {
    let { data, selectedRowKeys, pointId } = this.state;
    const {PointItemArray,changePointItemArray} = this.props;
    let newData = data.slice();
    let allKey = newData.map(item =>{
      return item.tempId;
    });
    let selects = [];
    let newSelectData = [];
    if (key === 1){//全选
      selects = allKey;
      newSelectData = newData;
    } else {//反选
      for (let select of selectedRowKeys){
        newData.findIndex(e => e.tempId === select) >= 0 ? newData.splice(newData.findIndex(e => e.tempId === select),1) : '';
      }
      newSelectData = newData;
      selects = newSelectData.map(item => {return item.tempId;});
    }
    this.setState({ selectedRowKeys: selects, selectData: newSelectData });
    
    PointItemArray[pointId] = selects;
    changePointItemArray(PointItemArray);
    // this.state.selectArray = selectArray;
    // this.setState({selectArray});
  }

  /**
   * 获取表格刷新方法
   */
  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: []});
        }
      },
      r()
    );
  };

  queryPointInputItem = (param,flag) => {
    const { pointId, routeId } = this.state;
    
    let body = {};
    body.routeId = routeId;
    body.pointId = pointId;
    pointId && getRoutePointInputItemAction(body).then(data => {
      if (!flag){
        this.setState({ classify: data.pointClassifyList, data: data.routePointItem });
      } else {
        let selectData = data.routePointItem.filter(item =>item.isBound === 'bound');
        let selectedRowKeys = selectData.map(item=>{return item.tempId; });
        this.setState({ classify: data.pointClassifyList, data: data.routePointItem, selectedRowKeys, selectData });
        this.changePointRowKey(pointId);
      }
    });
  };

  changePointRowKey = (pointId) => {
    const { PointItemArray } = this.props;
    if(PointItemArray[pointId]){
      this.setState({selectedRowKeys: PointItemArray[pointId]});
    }
  }

  render() {
    let { pagination, isChecked, data, count, selectedRowKeys, classify, inputName, classifyId, level } = this.state;
    return (
      <div className="route-point-intem">
        <div className="route-point-intem-search">
          <Button  transparent onClick={e=>this.chooseChange(e,1)}>全选</Button>
          <Button  transparent onClick={e=>this.chooseChange(e,2)}>反选</Button>
          <div className="route-point-intem-select-1">
            <span>扩展分类：</span>
            <Select
              className="route-point-intem-modal-select"
              data={classify}
              defaultOption={<Option value="">全部</Option>}
              renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
              value={classifyId}
              onChange={e => this.onSelectChange('classifyId',e)}
            />
          </div>
          <div className="route-point-intem-select-2">
            <span>等级：</span>
            <Select
              className="route-point-intem-modal-select"
              data={riskLevelData}
              defaultOption={<Option value="">全部</Option>}
              renderOption={item => <Option value={item.id}>{item.level}</Option>}
              value={level}
              onChange={e => this.onSelectChange('level',e)}
            />
          </div>
          <div className="route-point-intem-search">
            <Search icon="search" value={inputName} placeholder="检查项编码、名称" onChange={this.onChange} onIconClick={this.onIconClick} />
          </div>
        </div>
        <AmosGridTable
          rowKey="tempId"
          columns={getColumns()}
          isPageable={pagination}
          isChecked={isChecked}
          dataList={data}
          totals={count}
          callBack={this.reload}
          selectedRowKeys={selectedRowKeys}
          getTableDataAction={this.queryPointInputItem}
          getSelectedRows={this.getSelectedRows}
          onRowDoubleClick={this.onRowDoubleClick}
        />
      </div>
    );
  }
}

PointIntemModal.propTypes = {
  pointId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  routeId: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

export default PointIntemModal;
