import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button } from 'amos-framework';
import {
  queryRiskSourceDetailAction,
  queryRiskLevelEumListAction,
  dangerFactorListAction,
  fetchRiskTypeEumAction,
  getCompanyUserTreeAction,
  getMethodDataAction } from '../../../../services/bizService';
import BizIcon from './../../../common/icon/BizIcon';
import RiskLevelTree from './RiskLevelTree';
import RiskEvaluation from './RiskEvaluation';
import DangerFactor from './DangerFactor';
import RiskSourceDetail from './RiskSourceDetail';
import SplitterLayout from '../../../common/side/SideQueryLayout';
import SearchView from './SearchView';
import { parseTreeData, parseDepartmentTreeData } from './../treeDataProcessor';

const buttonMap = [
  { key: '1',icon: 'xiazai',label: '下载' },
  { key: '2',icon: 'daochu',label: '导出' }
];

/**
 * 风险模型
 *
 * @class ParamSet
 * @extends {Component}
 */

class RiskModel extends Component {
  constructor(props){
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    };
    this.state = {
      node: {},
      searchParam: [],
      dangerFactorData: [],
      dangerFactorTotalNum: 0,
      isThreeLevel: false,
      data: [],
      isShowRight: false,
      riskSourceId: '',
      showQuery: false,
      riskLevelData: [],
      userData: [],
      methodData: [],
      riskTypeData: []
    };
  }

  componentDidMount(){
    let { riskSourceId } = this.props.location.state || {};
    riskSourceId && this.levelTree.queryRiskSourceTree(riskSourceId);
    this.getRiskLevelEumData();
    this.getRiskTypeEumData();
    this.queryUserByCompany();
    this.queryMethodData();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.location.state) {
      let { riskSourceId } = nextProps.location.state || {};
      riskSourceId && this.levelTree.queryRiskSourceTree(riskSourceId);
    }
  }

  onClick =()=>{

  }

  setSearchAndSearch =(form)=>{
    const { riskSourceId } = this.state;
    form.riskSourceId.value = riskSourceId;
    let searchParam = [];
    for (let key in form ){
      searchParam.push(form[key]);
    }
    this.setState({ searchParam },()=>this.questStatistiscData(this.pageConfig));
  }

  getRiskLevelEumData = () => {
    queryRiskLevelEumListAction().then(data => {
      this.setState({ riskLevelData: data });
    });
  }

  questStatistiscData = (param, _table) => {
    if (_table && _table.state) {
      _table.state.selectedRowKeys = [];
      _table.state.selectedRows = [];
    }
    let { searchParam, riskType,isThreeLevel,isShowRight } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    let { pageNumber, pageSize } = param;
    if ( riskType !== '04') {//非风险源都显示详情
      isThreeLevel ? this.setState({ isThreeLevel: false }) : '';
    } else {//风险源显示风险因素信息
      isThreeLevel ? '' : this.setState({ isThreeLevel: true });
      this.queryDangerData(searchParam,pageNumber,pageSize);
    }
    isShowRight ? '' : this.setState({ isShowRight: true });
  }

  queryDangerData =(searchParam,pageNumber, pageSize)=>{
    dangerFactorListAction(searchParam, pageNumber, pageSize).then(data=>{
      this.setState({ dangerFactorData: data.content, dangerFactorTotalNum: data.totalElements });
    });
  }

  changeStatus = (open) => {
    this.setState({ showQuery: open });
  }

  loopChangeStatus = (open) => {
    const { showQuery } = this.state;
    showQuery ? this.setState({ showQuery: false }) : this.setState({ showQuery: true });
    this.search.initFormValues();
  }

  renderLevelButton =()=>{
    return (<div className='risk-level-img-button'>
      {buttonMap.map(item=>{ return <Button icon={<BizIcon icon={item.icon} />} transparent onClick={e => this.onClick(e,item.key)} />;})}
    </div>);
  }

  getRiskLevelEumData = () => {
    queryRiskLevelEumListAction().then(data => {
      this.setState({ riskLevelData: data });
    });
  }

  getRiskTypeEumData = () =>{
    fetchRiskTypeEumAction().then(data=>{
      this.setState({ riskTypeData: data });
    });
  }

  queryUserByCompany = () => {
    getCompanyUserTreeAction().then(data => {
      this.parseTreeData(data);
    });
  }

  // 解析返回的部门人员树，供TreeSelect使用
  parseTreeData = (treeList) => {
    let { userData } = this.state;
    userData = parseTreeData(treeList);
    this.setState({ userData });
    this.getBelongDepartmentData(userData);
  }

  updateLevelData =(riskSourceId)=>{
    this.setState({
      riskSourceId,
      searchParam: [{ name: 'riskSourceId', value: riskSourceId, type: '' }]
    }, () => this.refeshRiskSourceDetail(riskSourceId));
  }

  refeshRiskSourceDetail = (riskSourceId) =>{
    queryRiskSourceDetailAction(riskSourceId).then(data =>{
      this.setState({
        data,
        riskType: data.riskType ,
        searchParam: [{ name: 'riskSourceId',value: riskSourceId,type: '' }]
      },()=>this.questStatistiscData(this.pageConfig));
    });
  }

  queryMethodData = () => {
    getMethodDataAction().then(data => {
      this.setState({ methodData: data });
    });
  }

  getBelongDepartmentData = (userData) => {
    if (userData) {
      let { belongDepartmentData } = this.state;
      belongDepartmentData = parseDepartmentTreeData(userData);
      this.setState({ belongDepartmentData });
    }
  }

  render() {
    const {
      isThreeLevel,
      riskSourceId,
      riskType,
      data ,
      dangerFactorData,
      dangerFactorTotalNum,
      isShowRight,
      showQuery,
      userData,
      methodData,
      belongDepartmentData,
      riskLevelData,
      riskTypeData
    } = this.state;
    return (
      <div  className='risk-model' style={{ width: '100%',height: '100%' }}>
        <SplitterLayout open={showQuery} callback={this.changeStatus}>
          <SearchView riskSourceSearch={this.setSearchAndSearch} ref={node=>this.search = node} />
        </SplitterLayout>
        <div className='risk-model-left'>
          <div className='risk-level-img'>
            <span className='risk-level-img-span'>风险层级图</span>
          </div>
          <RiskLevelTree
            callBack={this.updateLevelData}
            userData={userData}
            methodData={methodData}
            riskLevelData={riskLevelData}
            riskTypeData={riskTypeData}
            ref={tree => this.levelTree = tree}
          />
          <RiskEvaluation  riskLevelData={riskLevelData} {...data} />
        </div>
        <div  className='risk-model-right'>
          {isShowRight ? isThreeLevel ?
            <DangerFactor
              riskSourceId={riskSourceId}
              dataList={dangerFactorData}
              totalCount={dangerFactorTotalNum}
              fetchData={this.questStatistiscData}
              changeStatus={this.loopChangeStatus}
            /> :
            <RiskSourceDetail
              riskType={riskType}
              {...data}
              userData={userData}
              methodData={methodData}
              belongDepartmentData={belongDepartmentData}
              riskLevelData={riskLevelData}
              riskTypeData={riskTypeData}
            /> : ''
          }
        </div>
      </div>
    );
  }
}

RiskModel.propTypes = {
  location: PropTypes.Object
};

export default RiskModel;
