import React, { Component } from 'react';
import { Tabs,Button, AmosAlert, Modal } from 'amos-framework';
import SplitterLayout from '../../../common/side/SideQueryLayout';
import BizIcon from './../../../common/icon/BizIcon';
import CommonBodyTable from './CommonBodyTable';
import { tabConf } from './conf';
import EquipRiskFactorListSearch from './equip/EquipRiskFactorListSearch';
import EquipRiskSourceListSearch from './equip/EquipRiskSourceListSearch';
import MajorHazardsListSearch from './major/MajorHazardsListSearch';
import RiskAreaListSearch from './risk/RiskAreaListSearch';
import RiskPositionListSearch from './risk/RiskPositionListSearch';
import TaskworkRiskFactorListSearch from './taskwork/TaskworkRiskFactorListSearch';
import TaskworkRiskSourceListSearch from './taskwork/TaskworkRiskSourceListSearch';
import {
  queryRiskAreaListAction,
  queryRiskLocationListAction,
  queryEquipHazardSourceListAction,
  queryControlObjFactorListAction,
  getCompanyUserTreeAction,
  getMethodDataAction,
  fetchRiskSourceListAction,
  getRiskLevelTreeAction,
  getRegionDepartmentTreeAction,
  queryMajorHazardInstallationListAction,
  deleteMajorHazardInstallationAction,
  addMajorHazardInstallationAction
} from './../../../../services/bizService';
import { parseTreeData } from './../treeDataProcessor';
import RiskSourceQR from './riskQR/RiskSourceQR';
import MajorHazardModel from './major/MajorHazardModel';

const { TabList, Tab, TabPanel } = Tabs;
const tabs = tabConf;
const buttonMap = [
  { key: 'add', icon: 'tianjia', label: '添加' },
  { key: 'edit', icon: 'xiugai', label: '修改' },
  { key: 'delete', icon: 'shanchu', label: '删除' },
  { key: 'filter', icon: 'shaixuan', label: '筛选' }
];
/**
 * 风险清单
 *
 * @class RiskList
 * @extends {Component}
 */

class RiskList extends Component {
  constructor(props) {
    super(props);
    let activeKey = '1';
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    };
    this.state = {
      activeKey,
      showQuery: false,
      dataList: [],
      totalNum: 0,
      searchParam: [],
      methodData: [],
      userData: [],
      searchCommonData: {},
      modalEnable: false,
      toolbarFlag: 0, //操作按钮flag 0新增，1编辑
    };
  }

  componentWillMount() {}

  componentDidMount() {
    this.queryUserByCompany();
    this.queryMethodData();
    this.queryRiskLevelData();
    this.queryRegionData();
  }

  onTabClick = value => {
    this.initData(value);
  };

  onToolBarClick = (btnType) => {
    if (btnType === 'filter') {
      this.loopChangeStatus();
    }
    if (btnType === 'add') {
      this.add();
    }
    if (btnType === 'edit') {
      this.edit();
    }
    if (btnType === 'delete') {
      this.delete();
    }
  };

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

  questStatistiscData = (param) => {
    let { searchParam, activeKey } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    let { pageNumber, pageSize } = param;
    if (activeKey === '1') {
      this.queryRiskArea(searchParam, pageNumber, pageSize);
    } else if (activeKey === '2') {
      this.queryRiskLocation(searchParam, pageNumber, pageSize);
    } else if (activeKey === '3') {
       //this.queryRiskFactor(searchParam, pageNumber, pageSize);
      this.queryEquipmentSource(searchParam, pageNumber, pageSize);
    } else if (activeKey === '4') {
      searchParam['type'] = '1';
      this.queryControlObjFactor(searchParam, pageNumber, pageSize);
    } else if (activeKey === '5') {
       //this.queryEvaModel(searchParam);
    } else if (activeKey === '6') {
      searchParam['type'] = '2';
      this.queryControlObjFactor(searchParam, pageNumber, pageSize);
    } else if (activeKey === '7') {//重大危险源
      this.queryMajorHazardInstallation(searchParam, pageNumber, pageSize);
    } else if (activeKey === '8') {
      let param = [];
      param = [...searchParam,{ name: 'riskType',type: 'EQUAL',value: '04' },{ name: 'riskLevel',type: 'BIGGER',value: 0 }];
      this.queryRiskSource(param, pageNumber, pageSize);
    }
  };

  initData = value => {
    this.setState({ activeKey: value, searchParam: [] });
  }

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

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

  getSearchView = (activeKey) => {
    let { searchCommonData } = this.state;
    switch (activeKey){
      case '1':
        return <RiskAreaListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '2':
        return <RiskPositionListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '3':
        return <EquipRiskSourceListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '4':
        return <EquipRiskFactorListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '5':
        return <TaskworkRiskSourceListSearch search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '6':
        return <TaskworkRiskFactorListSearch search={this.setSearchAndSearch} ref={node=>this.search = node} />;
      case '7':
        return <MajorHazardsListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node=>this.search = node} />;
    }
  }

  add() {
    this.setState({
      modalEnable: true,
      toolbarFlag: 0
    });
  }

  edit() {
    let { selectedRowKeys } = this.table.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要编辑的重大危险源');
      return;
    }

    if (selectedRowKeys.length > 1) {
      AmosAlert.warning('提示', '请选择一项重大危险源进行编辑');
      return;
    }

    let majorHazardId = selectedRowKeys[0];

    this.setState({
      modalEnable: true,
      majorHazardId,
      toolbarFlag: 1
    });
  }

  delete = () => {
    let { selectedRowKeys, reload } = this.table.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的重大危险源');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定重大危险源?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let ids = selectedRowKeys;
          deleteMajorHazardInstallationAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.cancel();
              reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  getHead = () => {
    const { modalEnable, toolbarFlag } = this.state;
    if (modalEnable) {
      return toolbarFlag === 0 ? '添加重大危险源' : '编辑重大危险源';
    }
  }

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

  submit = (e) => {
    let { form } = this.model;
    let { reload } = this.table.state;
    form.validate((valid, dataValues) => {
      if (valid) {
        addMajorHazardInstallationAction(dataValues).then(data => {
          AmosAlert.success('提示', '保存成功');
          this.cancel();
          reload();
        }, err => {
          AmosAlert.error('保存失败', err);
        }).catch(e => {
          AmosAlert.error('错误', '保存失败');
        });
      } else {
        console.log('error submit!!');
        this.cancel();
        return false;
      }
    });
  }

  getMajorHazardContext = () => {
    const { majorHazardId, toolbarFlag, searchCommonData } = this.state;
    return (<MajorHazardModel searchCommonData={searchCommonData} majorHazardId={majorHazardId} toolbarFlag={toolbarFlag} ref={component => this.model = component} />);
  }

  requestMethod =(activeKey)=>{
    this.questStatistiscData(this.pageConfig);
  }

  renderButton = (activeKey) => {
    let buttons = buttonMap;
    if (activeKey !== '7') {//非重大危险源标签
      buttons = buttonMap.filter(item => item.key === 'filter');
    }
    return (<div className='risk-list-operate-button'>
      {
        buttons.map(item => { return <Button title={item.label} icon={<BizIcon icon={item.icon} />} transparent onClick={() => this.onToolBarClick(item.key)} />;})
      }
    </div>);
  }

  renderTabPanel =(dataList,totalNum)=>{
    return tabs.map(item=>{
      if (item.id === '8') {
        return <TabPanel key={item.id} activeKey={item.id}> <RiskSourceQR dataList={dataList} totalNum={totalNum} fetchData={this.questStatistiscData} /></TabPanel>;
      } else {
        let isChecked = false;
        if (item.id === '7') {//重大危险源
          isChecked = true;
        }
        return <TabPanel key={item.id} activeKey={item.id}> <CommonBodyTable isChecked={isChecked} columns={item.header} dataList={dataList} totalNum={totalNum} fetchData={this.questStatistiscData} ref={node => this.table = node} /></TabPanel>;
      }
    });
  }

  queryRiskArea = (searchParam, pageNumber, pageSize) => {
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    queryRiskAreaListAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  queryRiskLocation = (searchParam, pageNumber, pageSize) => {
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    queryRiskLocationListAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  queryEquipmentSource = (searchParam, pageNumber, pageSize) => {
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    queryEquipHazardSourceListAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  queryControlObjFactor = (searchParam, pageNumber, pageSize) => {
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    queryControlObjFactorListAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  queryMajorHazardInstallation = (searchParam, pageNumber, pageSize) => {
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    queryMajorHazardInstallationListAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  queryMethodData = () => {
    getMethodDataAction().then(data => {
      let { searchCommonData } = this.state;
      searchCommonData.methodData = data;
      this.setState({ searchCommonData });
    });
  }

  queryUserByCompany = () => {
    getCompanyUserTreeAction().then(data => {
      let { searchCommonData } = this.state;
      searchCommonData.userData = this.parseTreeData(data);
      this.setState({ searchCommonData });
    });
  }

  queryRiskLevelData = () => {
    getRiskLevelTreeAction().then(data => {
      let { searchCommonData } = this.state;
      searchCommonData.riskLevelData = data;
      this.setState({ searchCommonData });
    });
  }

  queryRiskSource =(searchParam, pageNumber, pageSize)=>{
    fetchRiskSourceListAction(searchParam, pageNumber, pageSize).then(data=>{
      this.setState({ dataList: data.content,totalNum: data.totalElements });
    });
  }

  queryRegionData = () => {
    getRegionDepartmentTreeAction().then(data => {
      let { searchCommonData } = this.state;
      let regions = data.firstDepartments;
      let regionData = [];
      regions && regions.map(item => {
        let regionObj = {};
        regionObj.id = item.sequenceNbr;
        regionObj.name = item.departmentName;
        regionData.push(regionObj);
      });
      searchCommonData.regionData = regionData;
      searchCommonData.regionDepartmentTree = data;
      this.setState({ searchCommonData });
    });
  }

  // 解析返回的部门人员树，供TreeSelect使用
  parseTreeData = (treeList) => {
    return parseTreeData(treeList);
  }

  render() {
    let { activeKey, dataList, totalNum, showQuery, modalEnable } = this.state;
    return (
      <div className="tabs-outside-precontrol">
        <SplitterLayout open={showQuery} callback={this.changeStatus}>
          {this.getSearchView(activeKey)}
        </SplitterLayout>
        <Tabs activeKey={activeKey} onChange={(index, key) => this.onTabClick(key)} destroyContent closeAnimate cardMode>
          <TabList>
            {tabs.map(item => (
              <Tab key={item.id} activeKey={item.id} closable={item.closable}>
                {item.title}
              </Tab>
            ))}
            {this.renderButton(activeKey)}
          </TabList>
          {this.renderTabPanel(dataList,totalNum)}
        </Tabs>
        <Modal
          className='major-hazard-model'
          header={this.getHead()}
          visible={modalEnable}
          width='40%'
          destroyContent
          onCancel={() => this.cancel()}
          content={this.getMajorHazardContext()}
          onOk={(e) => this.submit(e)}
          outterClosable={false}
        />
      </div>
    );
  }
}

RiskList.propTypes = {};

export default RiskList;
