import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Modal, AmosAlert, Button } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import { evaluateCriteriaDeleteAction } from '../../../../../services/bizService';
import EvaluationCriteriaModel from './EvaluationCriteriaModel';
import EvaluationCriteriaModelView from './EvaluationCriteriaModelView';

const getColumns = (self) => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '准则名称',
      dataIndex: 'name',
      key: 'name',
      width: '40%',
      className: 'uant-table-thead',
      render: (text, record) => {
        return (
          <span >
            <a href="javascript:;" onClick={() => self.onDetailClick(record)}>{text}</a>
          </span>
        );
      }
    },
    {
      title: '维护人员',
      dataIndex: 'createUserName',
      key: 'createUserName',
      width: '25%',
      className: 'uant-table-thead'
    },
    {
      title: '维护日期',
      dataIndex: 'updateDate',
      key: 'updateDate',
      width: '25%',
      render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
      className: 'uant-table-thead'
    }
  ];
};

/**
 * 风险评价准则
 *
 * @class RiskEvaluationCriteria
 * @extends {Component}
 */
class RiskEvaluationCriteria extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      pagination: true,
      isChecked: true,
      modal: false,
      selectedRows: [],
      selectedRowKeys: [],
      data: [],
      searchParam: [],
      selectedShowRow: {}, //选中的一条记录
      evaluateModel: {}  //风险评价模型
    };
  }

  componentWillReceiveProps(newProps) {
    let { toolBarFlag, activeKey, evaModel, initToolbarFlag } = newProps;
    if (activeKey && activeKey === '4' && toolBarFlag) {
      this.checkData(toolBarFlag);
      initToolbarFlag();
    }
    //切换风险评价模型 重置selectRow
    if(this.props.evaModel && this.props.evaModel.id != evaModel.id){ 
      this.clearSelectedRows();
    }
    this.setState({ evaluateModel: evaModel });
  }

  onDetailClick = (record) => {
    this.setState({ modal: true, toolBarFlag: '3', selectedShowRow: record });
  }

  checkData = toolBarFlag => {
    let { selectedRowKeys } = this.state;
    if (toolBarFlag === '1') {
      //新增
      this.setState({ modal: true, toolBarFlag });
    } else if (toolBarFlag === '2') {
      //编辑
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
        AmosAlert.warning('提示', '请先点击选择编辑的行');
        return;
      } else {
        this.setState({ modal: true, toolBarFlag });
      }
    } else if (toolBarFlag === '3') {
      //删除
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
        AmosAlert.warning('提示', '请先点击选择删除的行');
        return;
      } else {
        this.evaluateCriteriaDelete(selectedRowKeys);
      }
    }
  };

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

  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  getRowClassName = (record, index) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

  onRowClick = record => {
    let { selectedRowKeys, selectedRows } = this.state;
    let exist = false;
    selectedRows.find(item => {
      if (item.id === record.id) {
        exist = true;
      }
    });
    if (exist) {
      selectedRows.splice(selectedRows.findIndex(item => item.id === record.id), 1);
      selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === record.id), 1);
    } else {
      selectedRows.push(record);
      selectedRowKeys.push(record.id);
    }
    this.setState({
      selectedRows,
      selectedRowKeys
    });
  };

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

  clearSelectedRows = () => {
    this.setState({ selectedRows: [], selectedRowKeys: [], modal: false, toolBarFlag: '' });
  };

  reloadPage = () => {
    this.clearSelectedRows();
    this.state.reload();
  };

  getContext = toolBarFlag => {
    let { selectedShowRow } = this.state;
    if (toolBarFlag) {
      if (toolBarFlag === '1') {
        //新增
        return <EvaluationCriteriaModel reloadPage={this.reloadPage} ref={component => this.model = component} />;
      } else if (toolBarFlag === '2') { //编辑
        const { selectedRows } = this.state;
        return <EvaluationCriteriaModel reloadPage={this.reloadPage} selectRowData={selectedRows[0]} ref={component => this.model = component} />;
      } else if (toolBarFlag === '3') { //查看
        const { selectedRows } = this.state;
        return <EvaluationCriteriaModelView selectRowData={selectedShowRow || selectedRows[0]} />;
      }
    }
  };

  cancel = () => {
    this.setState({ modal: false, toolBarFlag: '' });
  };

  evaluateCriteriaDelete = body => {
    AmosAlert.confirm('警告', '数据可能正在使用，确定删除?', {
      callback: flag => {
        if (flag) {
          // 确定
          evaluateCriteriaDeleteAction(body).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  };

  onOk = () => {
    let { evaluateModel } = this.state;
    if (evaluateModel.id) {
      this.model.handleSubmit(evaluateModel.id);
    } else {
      AmosAlert.warning('提示','请选择风险评价模型后，再进行操作');
    }
  };

  getHeader = (toolBarFlag) => {
    if (toolBarFlag === '1') {
      return '添加风险评价准则';
    } else if (toolBarFlag === '2') {
      return '编辑风险评价准则';
    } else if (toolBarFlag === '3') {
      return '查看风险评价准则';
    }
  }

  getFooter = () => {
    const { toolBarFlag } = this.state;
    if (toolBarFlag === '1' || toolBarFlag === '2') {
      return (<div><Button type="minor" onClick={() => this.cancel()}>取消</Button><Button  onClick={() => this.onOk()}>确定</Button></div> );
    } else if (toolBarFlag === '3') {
      return (<Button onClick={() => this.cancel()}>取消</Button>);
    }
  }

  render() {
    let { pagination, isChecked, selectedRowKeys, modal, toolBarFlag } = this.state;
    let { dataList, totalCount, fetchData } = this.props;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <AmosGridTable
          columns={getColumns(this)}
          callBack={this.reload}
          isPageable={pagination}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={param => fetchData(param, this)}
          selectedRowKeys={selectedRowKeys}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
          onRowClick={this.onRowClick}
          isChecked={isChecked}
        />
        <Modal
          header={this.getHeader(toolBarFlag)}
          visible={modal}
          destroyContent
          width='45%'
          className="param-model"
          content={this.getContext(toolBarFlag)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk()}
          outterClosable={false}
          footer={this.getFooter()}
        />
      </div>
    );
  }
}

RiskEvaluationCriteria.propTypes = {
  dataList: PropTypes.array,
  totalCount: PropTypes.number,
  fetchData: PropTypes.func,
  evaModelId: PropTypes.number
};
export default RiskEvaluationCriteria;
