import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosAlert,Button,Modal } from 'amos-framework';
import {
  addDangerFactorAction,
  deleteDangerFactorAction,
  relateEquipMgtCtrlObjAction,
  relateTaskworkMgtCtrlObjAction,
  startWorkFlowAction } from '../../../../services/bizService';
import BizIcon from './../../../common/icon/BizIcon';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import DangerFactorModal from './modal/DangerFactorModal';
import MgtCtrlEquip from './modal/MgtCtrlEquip';
import MgtCtrlTaskwork from './modal/MgtCtrlTaskwork';
import ControlMeasures from './modal/ControlMeasures';


const buttonMap = [
  { key: 'add',icon: 'tianjia',label: '添加' },
  { key: 'edit',icon: 'xiugai',label: '修改' },
  { key: 'delete',icon: 'shanchu',label: '删除' },
  { key: 'relate',icon: 'buzhou-daolu',label: '关联对象' },
  { key: 'apply',icon: 'buzhou-queren',label: '发起流程' },
  { key: 'filter',icon: 'shaixuan',label: '筛选' }
];

//流程状态（0：未启动；1：执行中；2：挂起；3：执行完成；4：撤销）
const workFlowStatus = {
  '0': '未启动',
  '1': '执行中',
  '2': '挂起',
  '3': '执行完成',
  '4': '撤销'
};
const ondefaultFootBtn = ['objDetail','meaDetail'];
const factorTypeEum = { 1: '设备设施危险因素',2: '作业活动危险因素' };
const getColumns = (self) => {
  return [
    {
      title: '危险因素名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%'
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: '5%'
    },
    {
      title: '危险因素类型',
      dataIndex: 'type',
      key: 'type',
      width: '12%',
      render: text => factorTypeEum[text]
    },
    {
      title: '辨识人',
      dataIndex: 'userNames',
      key: 'userNames',
      width: '12%'
    },
    {
      title: '辨识方法',
      dataIndex: 'methodNames',
      key: 'methodNames',
      width: '12%'
    },
    {
      title: '安全管控对象',
      dataIndex: 'controlModelName',
      key: 'controlModelName',
      width: '16%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.openDetail(record,'objDetail');}}>{text}</a>
          </span>
        );
      }
    },
    {
      title: '安全管控状态',
      dataIndex: 'controlStatus',
      key: 'controlStatus',
      width: '9%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.openDetail(record,'meaDetail');}}>{text}</a>
          </span>
        );
      }
    },
    {
      title: '流程状态',
      dataIndex: 'status',
      key: 'status',
      width: '9%',
      render: text => workFlowStatus[text]
    }
  ];
};

/**
 *
 * 危险因素列表
 * @class DangerFactor
 * @extends {Component}
 */
class DangerFactor extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      pagination: true,
      isChecked: true,
      selectedRows: [],
      modal: false,
      selectedRowKeys: []
    };
  }

  componentWillMount() {
    const { riskSourceId } = this.props;
    riskSourceId && this.setState({ riskSourceId });
  }

  componentWillReceiveProps(nextProp) {
    const { riskSourceId } = nextProp;
    riskSourceId && this.setState({ riskSourceId, selectedRowKeys: [] });
  }

  onRowClick = record => {

  }

  onToolBarClick =(key)=>{
    const { selectedRowKeys,selectedRows } = this.state;
    if (key === 'add'){//新增
      this.setState({ modal: true,btnType: key });
    } else if (key === 'edit'){//编辑
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击选择编辑的行');
        return;
      }
      if (selectedRowKeys.length > 1){
        AmosAlert.warning('提示', '每次只能编辑一行');
        return;
      } else if (selectedRows[0].status === '1'){
        AmosAlert.warning('提示', '流程执行中，不能编辑');
        return;
      }
      this.setState({ modal: true,btnType: key });
    } else if (key === 'delete'){//删除
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击选择删除的行');
        return;
      }
      this.deleteDangerFactor(selectedRowKeys, selectedRows);
    } else if (key === 'relate') {
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击选择要关联的行');
        return;
      }
      let selectFactorTypes = Array.from(new Set(selectedRows.map(row =>row.factorType)));
      if (selectFactorTypes.length > 1) {
        AmosAlert.warning('提示', '请选择相同类型的危险因素进行绑定');
        return;
      }
      if (selectedRows.filter(item=>item.status  === '1').length > 0) {// 0：未启动；1：执行中；3：执行完成；4：撤销
        AmosAlert.warning('提示', '执行中状态不允许再次绑定');
        return;
      }
      this.setState({ modal: true,btnType: key });
    } else if (key === 'apply') {
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0){
        AmosAlert.warning('提示', '请先点击发起审批申请的行');
        return;
      }
      let noBindArry = selectedRows.filter(row=>!row.controlModelId) || [];
      if (noBindArry.length > 0) {
        AmosAlert.warning('提示', '未绑定设备前不允许发起流程');
        return;
      }
      if (selectedRows.filter(item=>item.status  === '1').length > 0) {// 0：未启动；1：执行中；3：执行完成；4：撤销
        AmosAlert.warning('提示', '执行中状态不允许再次发起流程');
        return;
      }
      this.initiateApply(selectedRows);
    } else if (key === 'filter') {
      this.props.changeStatus();
    }
  }

  onOk = (btnType) =>{
    const { form, names = [], methodData = [], userListData = [] } = this.model.state;
    this.model.form.validate((valid, dataValues) => {
      if (valid) {
        if (btnType === 'add') {
          let arry = names.map(e=>{
            return e.name;
          });
          form.lastOne ? arry.includes(form.lastOne) ? '' : arry.push(form.lastOne) : '';
          if (arry.length === 0) {
            AmosAlert.warning('危险因素名称不能包含空');
            return ;
          }
          let userNames = form.userNames.join();
          let identificationMethodNames = form.identificationMethodNames.join();
          let userIds = form.userIds.join();
          let identificationMethodIds = form.identificationMethodIds.join();
          const entry = { ...form, names: arry, userIds, identificationMethodIds, userNames, identificationMethodNames };
          this.addRiskFactor(entry);
        } else if (btnType === 'edit') {
          if (!form.name) {
            AmosAlert.warning('危险因素名称不能包含空');
            return ;
          }
          let setUserIds = Array.from(new Set(form.userIds));
          let userNames = setUserIds.map(e=>{
            return (userListData.find(item=>parseInt(item.key) === parseInt(e)) || {}).label;
          });
          let identificationMethodNames = form.identificationMethodIds.map(e=>{
            return (methodData.find(item=>item.id === parseInt(e)) || {}).name;
          });
          const userIds = setUserIds.length > 0 ? setUserIds.join(',') : '';
          userNames = userNames.length > 0 ? userNames.join(',') : '';
          const identificationMethodIds = form.identificationMethodIds.length > 0 ? form.identificationMethodIds.join(',') : '';
          identificationMethodNames = identificationMethodNames.length > 0 ? identificationMethodNames.join(',') : '';
          const entry = { ...form, userIds, identificationMethodIds ,
            userNames,
            identificationMethodNames,names: [form.name] };
          this.addRiskFactor(entry);
        } else if (btnType === 'relate') {
          const { factorIds } = this.model.state;
          this.relateMgtCtrlObj(form,factorIds);
        }
        this.cancel();
      } else {
        return false;
      }
    });
  }

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

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

  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.pageNumber = current;
    }
  }

  getContext = (btnType) => {
    const { riskSourceId, selectedRows, selectedRowKeys } = this.state;
    if (btnType === 'add') {
      return <DangerFactorModal riskSourceId={riskSourceId} ref={component =>this.model = component} /> ;
    } else if (btnType === 'edit'){
      return <DangerFactorModal riskSourceId={riskSourceId} selectedRow={selectedRows.length > 0 ? selectedRows[0] : {}} ref={component =>this.model = component} /> ;
    } else if (selectedRows.length > 0 && btnType === 'relate' ){
      if (selectedRows[0].type === '1') {//设备设施危险因素
        return <MgtCtrlEquip factorIds={selectedRowKeys} factorType={selectedRows[0].type} ref={cpt=>this.model = cpt} />;
      } else if (selectedRows[0].type === '2') {//作业活动危险因素
        return <MgtCtrlTaskwork factorIds={selectedRowKeys} factorType={selectedRows[0].type} ref={cpt=>this.model = cpt} />;
      }
    } else if (selectedRows.length > 0 && btnType === 'objDetail' ){
      if (selectedRows[0].type === '1') {//设备设施危险因素
        return <MgtCtrlEquip factorId={selectedRowKeys[0]} factorType={selectedRows[0].type} ref={cpt=>this.model = cpt} />;
      } else if (selectedRows[0].type === '2') {//作业活动危险因素
        return <MgtCtrlTaskwork controlObjectId={selectedRows[0].controlModelId} factorType={selectedRows[0].type} ref={cpt=>this.model = cpt} />;
      }
    } else if (selectedRows.length > 0 && btnType === 'meaDetail' ){
      return <ControlMeasures factorId={selectedRowKeys[0]} evaluateId={selectedRows[0].evaluateId} factorName={selectedRows[0].name} />;
    }
  }

  getModelHeader =(btnType)=>{
    switch (btnType){
      case 'add':
        return '添加危险因素';
      case 'edit':
        return '编辑危险因素';
      case 'relate' :
        return '关联安全管控对象';
      case 'objDetail' :
        return '安全管控对象详情';
      case 'meaDetail' :
        return '管控措施';
    }
  }

  openDetail =(record,btnType)=>{
    this.setState({ selectedRows: [record], selectedRowKeys: [record.id], btnType, modal: true });
  }

  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  }

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

  relateMgtCtrlObj =(form,factorIds)=>{
    let arry = factorIds.map(id=>{
      // return { riskFactorId: id, equipmentId: form.controlObjectId, controlObjectName: form.controlObjectName };
      return { riskFactorId: id, controlObjectId: form.controlObjectId, controlObjectName: form.controlObjectName };
    });
    let { type } = form;
    if (type === '1'){//设备设施
      this.relateEquipMgtCtrlObj(arry);
    } else if (type === '2'){//作业活动
      this.relateTaskworkMgtCtrlObj(arry);
    }
  }

  relateEquipMgtCtrlObj =(relateArry)=>{
    relateEquipMgtCtrlObjAction(relateArry).then(data=>{
      AmosAlert.success('关联成功');
      this.reloadPage();
    },error=>{
      AmosAlert.error('关联失败');
    });
  }

  relateTaskworkMgtCtrlObj =(relateArry)=>{
    relateTaskworkMgtCtrlObjAction(relateArry).then(data=>{
      AmosAlert.success('关联成功');
      this.reloadPage();
    },error=>{
      AmosAlert.error('关联失败');
    });
  }

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

  deleteDangerFactor = (ids, objs) => {
    let prevent = [];
    objs.map(item => {
      if (item.status !== '0') {
        prevent.push(item);
      }
    });
    if (prevent.length > 0) {
      AmosAlert.error('错误', '该风险因素使用中，无法删除', {
        callback: (flag) => {}
      });
    } else {
      AmosAlert.confirm('提示', '确定要删除么?', {
        callback: flag => {
          if (flag) {
            // 确定
            deleteDangerFactorAction(ids).then(
              data => {
                AmosAlert.success('提示', '删除成功');
                this.reloadPage();
              },
              err => {
                AmosAlert.error('错误', err);
              }
            );
          }
        }
      });
    }
  }

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

  addRiskFactor = (entry) =>{
    addDangerFactorAction(entry).then(data=>{
      AmosAlert.success('提示', '操作成功');
      this.reloadPage();
    },err => {
      AmosAlert.error('错误', err);
    });
  }

  initiateApply = (selectedRows) => {
    //1.组织数据
    let ids = [];
    selectedRows.map(item => {
      ids.push(item.id);
    });

    //2.弹出确认提升框
    AmosAlert.confirm('提示', '是否启动评价流程?', {
      callback: (flag) => {
        if (flag) {
          //3.调用接口
          startWorkFlowAction(ids.join()).then(data => {
            AmosAlert.success('提示', '启动成功');
            this.state.reload();
          }, err => {
            AmosAlert.error('启动失败', err);
          });
        }
      }
    });
  }

  renderButton =()=>{
    return buttonMap.map(item=>{
      return <Button title={item.label} icon={<BizIcon icon={item.icon} />} transparent onClick={e => this.onToolBarClick(item.key)} />;
    });
  }

  render() {
    const { pagination, isChecked, selectedRowKeys, modal,btnType } = this.state;
    const { dataList, fetchData, totalCount } = this.props;
    const defaultPageConfig = this.pageConfig;
    return (
      <div className='danger-factor'>
        <div className='danger-factor-header'>
          <div className='header-descript' >危险因素</div>
          <div className='risk-lever-button' >
            {this.renderButton()}
          </div>
        </div>
        <div className='danger-factot-cxt'>
          <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}
          />
        </div>
        <Modal
          header={this.getModelHeader(btnType)}
          visible={modal}
          className="danger-factor-modal"
          destroyContent
          width='45%'
          content={this.getContext(btnType)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk(btnType)}
          noDefaultFooter={ondefaultFootBtn.includes(btnType) ? true : false}
          okText="确定"
          cancelText="取消"
        />
      </div>
    );
  }
}

DangerFactor.propTypes = {
  dataList: PropTypes.array,
  fetchData: PropTypes.func,
  totalCount: PropTypes.number,
  riskSourceId: PropTypes.number,
  changeStatus: PropTypes.func
};

export default DangerFactor;
