/* eslint-disable */
/* eslint-disable function-paren-newline */
import React, { Component } from 'react';
import { BankOutlined, CloseOutlined, FolderFilled, FolderOpenFilled } from '@ant-design/icons';
import { Layout, Card, Checkbox, Button, Table, Menu, Tabs, message, Tree, Input } from 'antd-v4';
import logo from '@/assets/foot_logo.png';
import config from '@/utils/config';
import * as commonUtils from '@/utils/utils'; /* 通用方法 */
import stylesIndex from '@/index.less';
import CommonChar from '@/components/CommonChar/CommonChar';
import * as commonFunc from '@/components/Common/commonFunc';
import lodash from 'lodash';
import styles from './index.less';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import file_single from "@/assets/file_single.svg";
import defaultApp from "@/assets/index/default-app.svg";
import kaoqin from "@/assets/index/kaoqin.svg";
import OASys from "@/assets/index/oa.svg";
import caiwu from "@/assets/index/financialSystem.svg";
import crm from "@/assets/index/crm.svg";

const { Sider, Content, Footer } = Layout;
const { TabPane } = Tabs;
const { TreeNode } = Tree;

class IndexCenter extends Component {
  constructor(props) {
    super(props);
    const columnNo = commonFunc.showMessage(props.app.commonConst, 'columnNo');/* 编号 */
    let sChildFlow = commonFunc.showMessage(props.app.commonConst, 'sChildFlow');/* 子流程 */
    if (sChildFlow === undefined || sChildFlow === '') {
      sChildFlow = '子流程';
    }
    const columnDepartment = commonFunc.showMessage(props.app.commonConst, 'columnDepartment');/* 部门 */
    const TodayAffair = commonFunc.showMessage(props.app.commonConst, 'TodayAffair');/* 今日事务 */
    const unclearedTotal = commonFunc.showMessage(props.app.commonConst, 'unclearedTotal');/* 未清总数 */
    const columnPrescription = commonFunc.showMessage(props.app.commonConst, 'columnPrescription');/* 时效 */
    const columnWorkMatters = commonFunc.showMessage(props.app.commonConst, 'columnWorkMatters');/* 工作事项 */
    const columnContent = commonFunc.showMessage(props.app.commonConst, 'columnContent');/* 内容 */
    this.state = {
      loadings: false,
      columns: [{
        title: columnNo,
        dataIndex: 'iOrder',
        width: 40,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: sChildFlow,
        dataIndex: 'sChildFlow',
        width: 180,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: columnDepartment,
        dataIndex: 'sDepart',
        width: 80,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: TodayAffair,
        dataIndex: 'dToDayNum',
        width: 80,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: unclearedTotal,
        dataIndex: 'dTobeDone',
        width: 80,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: columnPrescription,
        dataIndex: 'dLimitation',
        width: 40,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: columnWorkMatters,
        dataIndex: 'sMenuUnMemo',
        width: 180,
        render: text => <div><span>{text}</span></div>,
      }, {
        title: columnContent,
        dataIndex: 'sMenuWorkFruit',
        render: text => <div><span>{text}</span></div>,
      }],
      comParameterList: [],
      dToDayNumSum: 0, /* 今日事务 */
      dTobeDoneSum: 0, /* 未制单 */
      tabsPanes: [],
      tableTreeData: [],
      tableData: [],
      bFilter: 'Pending,PendingCheck,MyWarning',
      app: props.app,
    };
    this.activeTree = '';
    this.treeId = '';
  }

  componentWillMount() {
    setTimeout(() => {
      this.handleGetModelCenter('init');
      const commonUrl = `${config.server_host}parameter/getParameter?sModelsId=100`;
      this.props.onGetComParameter(commonUrl);
    }, 0);
    // this.handleGetModelCenter();
  }

  componentWillReceiveProps(nextProps) {
    const { dispatch } = nextProps;
    const { modelCenter, comParameter:comParameterAll = [], dataCode, kpiData, logoImageInfo, userinfo, token } = nextProps.app;
    const comParameter =  comParameterAll.filter(item => item.sDisplayType ? item.sDisplayType !== 'LargeScreen' : !item.sFormUrl?.includes('http'));
    const commonThirdApp = comParameterAll.filter(item => item.sDisplayType ? item.sDisplayType === 'LargeScreen' : item.sFormUrl?.includes('http'));
    const { modelCenter: modelCenterOld } = this.props;

    const { sUserNo } = userinfo;
    const xlybusinessActiveTree = localStorage.getItem(`xlybusinessActiveTree_${sUserNo}`);
    if (xlybusinessActiveTree) {
      [this.curActiveTree, this.tableTreeScrollTop, this.kpiTableScrollTop] = xlybusinessActiveTree.split(',');
    }

    const { kpiData: kpiDataOld } = this.props.app;
    const bWebsocketData = commonUtils.isNotEmptyArr(kpiData) && JSON.stringify(kpiData) !== JSON.stringify(kpiDataOld);
    const bXiaoAiComputed = modelCenterOld?.dToDayNumSum !== modelCenter?.dToDayNumSum || modelCenterOld?.dTobeDoneSum !== modelCenter?.dTobeDoneSum;
    if (bWebsocketData || bXiaoAiComputed) {
      // this.curActiveTree = this.activeTree;
      this.treeId = '';
    }
    const { dToDayNumSum, dTobeDoneSum, model } = bWebsocketData ? kpiData : modelCenter;
    if (dataCode === 1) {
      this.setState({ loadings: false });
      dispatch({ type: 'app/saveModelCenter', payload: { modelCenter, dataCode: 0 } });
    }
    const comParameterList = [];
    comParameter.forEach((child) => {
      comParameterList.push(
        <Menu.Item key={child.sFormId} data-sname={child.sFormUrl} data-smodelstype={child.sModelType} data-sformname={child.sFormName} data-sprocname={child.sProcName}>
          <div className={styles.comParameter}>
            <div className={styles.comParameterTitle}>{child.sFormName}</div>
            <CloseOutlined className={styles.comParameterClose} onClick={e => this.handleDelCommonMenu(e, child)} />
          </div>
        </Menu.Item>);
    });
    const getIconSrc = (formName) => {
      if (formName.includes('考勤')) return kaoqin;
      if (formName.includes('财务')) return caiwu;
      if (formName.includes('CRM')) return crm;
      if (formName.includes('OA')) return OASys;
      return defaultApp;
    };
    const comThirdAppList = [];
    commonThirdApp.forEach((child) => {
      const dataUrl = child.sTitleLogoPath ? `${commonConfig.file_host}file/download?savePathStr=${child.sTitleLogoPath}&sModelsId=100&token=${token}` : '';
      comThirdAppList.push(
        <Menu.Item
          key={child.sFormId}
          style={{ height: '40px', lineHeight: '40px', marginBottom: '10px' }}
          data-sname={child.sFormUrl}
          data-smodelstype={child.sModelType}
          data-sformname={child.sFormName}
          data-sprocname={child.sProcName}
        >
          <div className={styles.comParameter} style={{ display: "flex", alignItems: "center" }}>
            {child.sTitleLogoPath ? (
              <img src={dataUrl} style={{ width: 30, height: 30, marginRight: 15 }} />
            ) : (
              <img src={getIconSrc(child.sFormName)}  style={{ width: 30, height: 30, marginRight: 15 }} />
            )}
            <div className={styles.comParameterTitle} style={{ flex: 1, textAlign: "left" }}>
              {child.sFormName}
            </div>
            <CloseOutlined className={styles.comParameterClose} onClick={e => this.handleDelCommonMenu(e, child)} />
          </div>
        </Menu.Item>
      );
    });
    const columnNo = commonFunc.showMessage(nextProps.app.commonConst, 'columnNo');/* 编号 */
    let sChildFlow = commonFunc.showMessage(nextProps.app.commonConst, 'sChildFlow');/* 子流程 */
    const sNotShowChildFlow = commonFunc.showMessage(nextProps.app.commonConst, 'sNotShowChildFlow');/* 是否显示子流程 */
    if (sChildFlow === undefined || sChildFlow === '') {
      sChildFlow = '子流程';
    }
    const columnDepartment = commonFunc.showMessage(nextProps.app.commonConst, 'columnDepartment');/* 部门 */
    const TodayAffair = commonFunc.showMessage(nextProps.app.commonConst, 'TodayAffair');/* 今日事务 */
    const unclearedTotal = commonFunc.showMessage(nextProps.app.commonConst, 'unclearedTotal');/* 未清总数 */
    const columnPrescription = commonFunc.showMessage(nextProps.app.commonConst, 'columnPrescription');/* 时效 */
    const columnWorkMatters = commonFunc.showMessage(nextProps.app.commonConst, 'columnWorkMatters');/* 工作事项 */
    const columnContent = commonFunc.showMessage(nextProps.app.commonConst, 'columnContent');/* 内容 */

    const ByRole = commonUtils.isNotEmptyObject(commonFunc.showMessage(nextProps.app.commonConst, 'ByRole')) ?
      commonFunc.showMessage(nextProps.app.commonConst, 'ByRole') : '按角色';/* 按角色 */
    const ByFlow = commonUtils.isNotEmptyObject(commonFunc.showMessage(nextProps.app.commonConst, 'ByFlow')) ?
      commonFunc.showMessage(nextProps.app.commonConst, 'ByFlow') : '按流程';/* 按流程*/
    const OtherFlow = commonUtils.isNotEmptyObject(commonFunc.showMessage(nextProps.app.commonConst, 'OtherFlow')) ?
      commonFunc.showMessage(nextProps.app.commonConst, 'OtherFlow') : '其它流程';/* 其它流程*/

    const tabsPanes = [];
    const tableTreeData = [{
      showName: ByRole,
      sId: 'tableTreeData_0',
      children: [],
      disabled: true,
    }];

    if (model !== undefined && !this.treeId) {
      // if (this.tableTree) {
      //   this.tableTree.scrollTop = 0;
      // }
      const addState = {};
      Object.keys(model).forEach((child, index) => {
        const name = child.split('_')[0];
        // const num = child.split('_')[1];
        let num = 0;
        // const key = name;
        const data = model[child];
        data.forEach((item, index) => {
          let { dToDayNum } = item;
          dToDayNum = Number(dToDayNum);
          dToDayNum = dToDayNum === dToDayNum ? dToDayNum : 0;
          num += dToDayNum;
        });
        const columns = [{
          title: columnDepartment,
          dataIndex: 'sDepart',
          width: '14%',
          render: text => (
            <div
              style={{
                display: 'grid',
              }}
            >
              <span
                style={{
                  textOverflow: 'ellipsis',
                  overflow: 'hidden',
                  whiteSpace: 'nowrap',
                }}
                title={text}
              >{text}</span>
            </div>
          ),
        }, {
          title: columnWorkMatters,
          dataIndex: 'sMenuUnMemo',
          width: '30%',
          render: (text, record) => <div><a
            onClick={() => {
              this.handleDoubleClick(record);
            }}
            style={{ color: '#006d75' }}
          >{text}</a></div>,
        }, {
          title: columnContent,
          dataIndex: 'sMenuWorkFruit',
          width: '30%',
          render: (text, record) => {
            const { sResultModelId } = record;
            if (commonUtils.isNotEmptyArr(sResultModelId)) {
              return <div><a
                onClick={() => {
                  this.handleJumpToResultModel(record);
                }}
                style={{ color: '#2f54eb' }}
              >{text}</a></div>
            } else {
              return <div><span>{text}</span></div>
            }
          },
        }, {
          title: TodayAffair,
          dataIndex: 'dToDayNum',
          width: '7%',
          render: text => <div className={styles.divSpan}><span className={styles.tdSpan1}>{text}</span></div>,
        }, {
          title: unclearedTotal,
          dataIndex: 'dTobeDone',
          width: '6%',
          render: text => <div className={styles.divSpan}><span className={styles.tdSpan2}>{text}</span></div>,
        }, {
          title: sChildFlow,
          dataIndex: 'sChildFlow',
          width: '10%',
          render: (text, record, index) => {
            const obj = {
              children: text !== null ? <div><span className={styles.tdSpan}>{text}</span></div> : '',
              props: {},
            };
            obj.props.rowSpan = this.mergeCells(text, data, 'sChildFlow', index);
            return obj;
          },
        }];
        if (sNotShowChildFlow) {
          // columns.pop();
        }
        // tabsPanes.push(
        //   <TabPane tab={<div style={{ fontSize: '13px' }} className={styles.tabsNative}>{name}<span>({num})</span></div>} key={key}>
        //     <Table
        //       columns={columns}
        //       dataSource={data}
        //       size="middle"
        //       pagination={false}
        //       id="kpiTable"
        //       scroll={{ x: 'max-content', y: 'calc(72vh - 66px)' }}
        //       onRow={(record) => { return { onDoubleClick: () => { this.handleDoubleClick(record); } }; }}
        //       rowClassName={this.getRowClassName}
        //     />
        //   </TabPane>);
        tableTreeData[0].children.push({
          showName: name,
          sId: `tableTreeData_0_${index}`,
          data,
          columns,
          count: num,
        });
        if (this.curActiveTree === `tableTreeData_0_${index}`) {
          addState.tableData = data;
          addState.columns = columns;
        }
      });

      if (commonUtils.isNotEmptyArr(tableTreeData[0].children)) {
        const { sId: activeTree, data: tableData, columns } = tableTreeData[0].children[0];
        this.treeId = 'treeId_' + activeTree;
        if (this.curActiveTree) {
          this.activeTree = this.curActiveTree;
        } else {
          this.activeTree = activeTree;
        }

        if (!sNotShowChildFlow) {
          const flowJson = {};
          tableData.forEach((item, flowIndex) => {
            let sChildFlow = item.sChildFlow;
            if (!sChildFlow) {
              sChildFlow = OtherFlow;
            }
            const count = Number(item.dToDayNum);
            if (!Object.keys(flowJson).includes(sChildFlow)) {
              const columnsNew = lodash.cloneDeep(columns);
              columnsNew[columnsNew.length - 1].render = (text, record, index) => {
                const { sChildDetailFlow, sId } = record;
                const textNew = sChildDetailFlow;
                const obj = {
                  children: textNew !== null ? <div><span className={styles.tdSpan}>{textNew}</span></div> : '',
                  props: {},
                };
                obj.props.rowSpan = this.mergeCells1(textNew, tableData, 'sChildDetailFlow', sId, record);
                return obj;
              }
              // columnsNew.pop();
              flowJson[sChildFlow] = {
                showName: sChildFlow,
                sId: `tableTreeData_1_${flowIndex}`,
                data: [item],
                count: count === count ? count : 0,
                columns: columnsNew,
              };
            } else if (!flowJson[sChildFlow].data.some(data => data.sId === item.sId)) {
              flowJson[sChildFlow].data.push(item);
              flowJson[sChildFlow].count += count ? count : 0;
            }
          });

          if (commonUtils.isNotEmptyObject(flowJson)) {
            for (const key in flowJson) {
              if (Object.hasOwnProperty.call(flowJson, key)) {
                const item = flowJson[key];
                const { data, sId, columns } = item;
                const sChildDetailFlowData = data.filter(child => child.sChildDetailFlow);
                if (sChildDetailFlowData.length) {
                  const groupArr = sChildDetailFlowData.reduce((result, current) => {
                    if (!result.some(child => child.showName === current.sChildDetailFlow)) {
                      result.push({
                        data: [],
                        count: 0,
                        showName: current.sChildDetailFlow,
                      });
                    }

                    const iIndex = result.findIndex(child => child.showName === current.sChildDetailFlow);
                    result[iIndex].data.push({ ...current, bLastLevel: true });
                    let dToDayNum = Number(current.dToDayNum);
                    dToDayNum = dToDayNum === dToDayNum ? dToDayNum : 0;
                    result[iIndex].count += dToDayNum;
                    return result;
                  }, []);

                  item.children = groupArr.map(({
                    count,
                    showName,
                    data,
                  }, index) => {
                    const childSId = `${sId}_${index}`;
                    if (this.curActiveTree === childSId) {
                      addState.tableData = data;
                      addState.columns = columns
                    }
                    return {
                      showName: showName,
                      sId: childSId,
                      data,
                      count: count === count ? count : 0,
                      columns,
                    }
                  });
                }
              }
            }

            Object.values(flowJson).forEach(item => {
              if (this.curActiveTree === item.sId) {
                addState.tableData = item.data;
                addState.columns = item.columns
              }
            })

            tableTreeData.push({
              showName: ByFlow,
              sId: 'tableTreeData_1',
              children: Object.values(flowJson),
              disabled: true,
            });
          }
        }
        if (!addState.tableData) {
          addState.tableData = tableData;
          addState.columns = columns;
          this.tableTreeScrollTop = 0;
          this.kpiTableScrollTop = 0;
          localStorage.removeItem(`xlybusinessActiveTree_${sUserNo}`);
        }
      }
      this.setState({
        tabsPanes, tableTreeData, ...addState
      });
    }
    this.setState({ comParameterList, comThirdAppList,  dToDayNumSum, dTobeDoneSum, logoImageInfo });
  }
  componentDidMount() {
    if (this.kpiTable && this.kpiTable.querySelector('.ant-table-body')) {
      this.kpiTable.querySelector('.ant-table-body')
        .addEventListener('scroll', this.scrollLoading);
    }
    if (this.tableTree) {
      this.tableTree.addEventListener('scroll', this.scrollTreeLoading);
    }

    // 监听全局ctrl+alt+M事件
    document.addEventListener('keydown', this.handleGlobalCtrlAltM);
  }

  componentWillUnmount() {
    if (this.kpiTable && this.kpiTable.querySelector('.ant-table-body')) {
      this.kpiTable.querySelector('.ant-table-body')
        .removeEventListener('scroll', this.scrollLoading);
    }
    if (this.tableTree) {
      this.tableTree.removeEventListener('scroll', this.scrollTreeLoading);
    }

    // 卸载全局ctrl+alt+M事件
    document.removeEventListener('keydown', this.handleGlobalCtrlAltM);
  }

  handleGlobalCtrlAltM = (e) => {
    if (e.ctrlKey && (e.altKey || e.metaKey) && e.keyCode === 77) {
      const itemName = `${commonConfig.prefix}TableMax`;
      const xlyTableMax = localStorage.getItem(itemName);
      if (!xlyTableMax) {
        localStorage.setItem(itemName, 'max');
      } else {
        localStorage.removeItem(itemName);
      }
      this.props.dispatch({ type: "app/refreshPage" });
    }
  }

  scrollLoading = () => {
    this.kpiTableScrollTop = this.kpiTable.querySelector('.ant-table-body').scrollTop;
    clearTimeout(this.tableTimer);
    this.tableTimer = setTimeout(this.recordTableTreeState, 20);
  }

  scrollTreeLoading = () => {
    this.tableTreeScrollTop = this.tableTree.scrollTop;
    clearTimeout(this.treeTimer);
    this.treeTimer = setTimeout(this.recordTableTreeState, 20);
  }

  recordTableTreeState = () => {
    const { sUserNo } = this.props.app.userinfo;
    localStorage.setItem(`xlybusinessActiveTree_${sUserNo}`, `${this.activeTree},${this.tableTreeScrollTop || 0},${this.kpiTableScrollTop || 0}`);
  }

  handleDoubleClick = (record) => {
    const newsId = record.sId; /* 表格行的sId */
    const newKey = new Date().getTime().toString();
    const route = record.sName;
    const title = record.sMenuName;
    const pane = {
      title, route, formId: newsId, key: newKey, sModelsType: record.sModelType, fromKey: "1", sSrcModelsId: '1',
      currentIndex: 0,
    };
    this.props.onAddPane(pane);
  };

  handleJumpToResultModel = (record) => {
    const newsId = record.sResultModelId; /* 表格行的sId */
    const newKey = new Date().getTime().toString();
    const route = record.sResultModelName;
    const title = record.sResultModelMenuName;
    const pane = {
      title, route, formId: newsId, key: newKey, sModelsType: record.sResultModelType, fromKey: "1",
      currentIndex: 0,
    };
    this.props.onAddPane(pane);
  };

  /* 根据传参 点开界面 */
  handleOpenTab = async () => {
    /* 点击有sName的菜单，增加标签页 */
    const { app } = this.props;
    const { token } = app;
    const paneKey = new Date().getTime().toString();
    // /* Tab标签Id */
    // const formId = commonUtils.isNotEmptyObject(sFormId) ? sFormId : '101251240115016086186007360'; /* 窗体Id */
    // const checkedId = commonUtils.isNotEmptyObject(sId) ? sId : '16662449420009255659985908760000';

    // const formId = commonUtils.isNotEmptyObject(sFormId) ? sFormId : ''; /* 窗体Id */
    // const checkedId = commonUtils.isNotEmptyObject(sId) ? sId : '';
    const formId = commonUtils.isNotEmptyObject(document.getElementById('sFormId')) ? document.getElementById('sFormId').value : '';
    const checkedId = commonUtils.isNotEmptyObject(document.getElementById('sBillId')) ? document.getElementById('sBillId').value : '';
    const bFlowValue = commonUtils.isNotEmptyObject(document.getElementById('bFlow')) ? document.getElementById('bFlow').value : ''; /* 是否有审核流程 */
    let sFlowData = commonUtils.isNotEmptyObject(document.getElementById('sFlowData')) ? document.getElementById('sFlowData').value : ''; /* 业务数据 */
    console.log('窗体id:', formId);
    console.log('主表id:', checkedId);
    if (commonUtils.isEmpty(formId) || commonUtils.isEmpty(checkedId)) {
      message.error('没有入参Id');
      return;
    }
    let sModelsType = '';
    let title = '单据页';
    let sProcName = '';
    let route = '/indexPage/commonBill';
    console.log('bFlowValue', bFlowValue);
    let bFlow = bFlowValue === 'true'; /* 默认没有审批流程信息 */
    const configUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${formId}?sModelsId=${formId}`;
    const configReturn = (await commonServices.getService(token, configUrl)).data;
    if (configReturn.code === 1) {
      const dataReturn = configReturn.dataset.rows;
      if (commonUtils.isNotEmptyArr(dataReturn) && commonUtils.isNotEmptyObject(dataReturn[0])) {
        const config = dataReturn[0];
        sModelsType = commonUtils.isNotEmptyObject(config.sModelType) ? config.sModelType.toString() : '';
        title = commonUtils.isNotEmptyObject(config.sMenuName) ? config.sMenuName.toString() : '';
        route = commonUtils.isNotEmptyObject(config.sName) ? config.sName.toString() : '';
        sProcName = commonUtils.isNotEmptyObject(config.sProcName) ? config.sProcName.toString() : '';
      }
    } else {
      this.getServiceError(configReturn);
    }
    const pane = {
      formId,
      key: paneKey,
      route,
      title,
      sModelsType,
      checkedId,
      sProcName,
      bFlow,
      sFlowData,
    };
    console.log('pane', pane);
    this.props.onAddPane(pane);
  };

  handleGetModelCenter = (type) => {
    this.curActiveTree = this.activeTree;
    this.treeId = '';
    let value = {
      bFilter: this.state.bFilter,
    };
    let centerUrl = '';
    if (type === 'init') {
      value = {
        bFilter: '',
      };
      centerUrl = `${config.server_host}modelCenter/getModelCenter?sModelsId=100`;
    } else {
      this.setState({ loadings: true });
      centerUrl = `${config.server_host}modelCenter/getModelCenterCalculation?sModelsId=100`;
    }
    this.props.onGetModelCenter(value, centerUrl);
  };

  handleDelCommonMenu = (e, child) => {
    e.stopPropagation();
    const { sFormId } = child;
    const value = { sFormId };
    const delUrl = `${config.server_host}parameter/deleteParameter?sModelsId=${sFormId}`;
    this.props.onDelParameter(value, delUrl);
    setTimeout(() => {
      const url = `${config.server_host}business/getBuMenu?sModelsId=100`;
      this.props.dispatch({ type: 'menuPanel/getMenuPanel', payload: { url } });
    }, 300);
  };

  handleTabClick = (e) => {
    /* 点击有sName的菜单，增加标签页 */
    const paneKey = new Date().getTime().toString();
    /* Tab标签Id */
    const formId = e.key;
    /* 窗体Id */
    const route = e.item.props['data-sname'];
    const sModelsType = e.item.props['data-smodelstype'];
    const title = e.item.props['data-sformname'];
    const sProcName = e.item.props['data-sprocname'];
    const pane = {
      title, route, formId, key: paneKey, sModelsType, sProcName,
    };
    let routeNew = route;
    if (route && route.includes('http')) {
      console.log('route', route);
      console.log('sModelsType:', sModelsType);
      const sModelsTypeNew = sModelsType !== undefined ? sModelsType : '';
      const { userinfo } = this.props.app;
      routeNew = route.replace('{sBrandsId}', userinfo.sBrandsId).replace('{sSubsidiaryId}', userinfo.sSubsidiaryId).replace('{sUserName}', userinfo.sUserName)
        .replace('{sUserNo}', userinfo.sUserNo);
      const parameter = sModelsTypeNew.replace('{sBrandsId}', userinfo.sBrandsId).replace('{sSubsidiaryId}', userinfo.sSubsidiaryId).replace('{sUserName}', userinfo.sUserName)
        .replace('{sUserNo}', userinfo.sUserNo);
      window.open(routeNew, parameter);
      return;
    }
    this.props.onAddPane(pane);
  };

  handleCheckBoxChange = (checkedValues) => {
    const bFilter = checkedValues.join(',');
    this.setState({
      bFilter,
    });
  };

  mergeCells = (text, data, key, index) => {
    // 上一行该列数据是否一样
    if (index !== 0 && text === data[index - 1][key]) {
      return 0;
    }
    let rowSpan = 1;
    // 判断下一行是否相等
    for (let i = index + 1; i < data.length; i++) {
      if (text !== data[i][key]) {
        break;
      }
      rowSpan++;
    }
    return rowSpan;
  }

  mergeCells1 = (text, data, key, sId, record) => {
    try {
      const filterData = data.filter(item => item[key] === text);
      const indexNew = filterData.findIndex(item => item.sId === sId);

      let filterDataAll;
      let index;
      if (record.bLastLevel) {
        filterDataAll = filterData;
        index = indexNew;
      } else {
        filterDataAll = data.filter(item => item.sChildFlow === filterData[0].sChildFlow);
        index = filterDataAll.findIndex(item => item.sId === sId);
      }

      if (indexNew !== 0 && text === filterDataAll[index - 1][key]) {
        return 0;
      }

      let rowSpan = 1;
      // 判断下一行是否相等
      for (let i = index + 1; i < filterDataAll.length; i++) {
        if (text !== filterDataAll[i][key]) {
          break;
        }
        rowSpan++;
      }
      return rowSpan;
    } catch (error) {
      return 1;
    }
  }
  /* 奇行、偶行变色 */
  getRowClassName = (record, index) => {
    let className = '';
    className = record.sColor;
    return className
  }
  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children && item.children.length > 0) {
        return (
          <TreeNode
            switcherIcon={<><FolderFilled /><FolderOpenFilled /></>}
            title={
              <>
                <span>{item.showName}</span>
                {!item.disabled ?
                  <span>
                    <span>{'('}</span>
                    <span style={{ color: '#2f54eb', fontWeight: 'bold' }}>{item.count || 0}</span>
                    <span>{')'}</span>
                  </span>
                  : ''
                }
              </>
            }
            // title={`${item.showName}${!item.disabled ? `(${item.count || 0})` : ''}`}
            key={item.sId}
            treeNode={item}
            isLeaf={item.isLeaf}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          switcherIcon={<img src={file_single} width={13} alt="svg" />}
          title={
            <>
              <span>{item.showName}</span>
              <span>
                <span>{'('}</span>
                <span style={{ color: '#2f54eb', fontWeight: 'bold' }}>{item.count || 0}</span>
                <span>{')'}</span>
              </span>
            </>
          }
          // title={`${item.showName}(${item.count || 0})`}
          key={item.sId}
          treeNode={item}
        // switcherIcon={<FolderFilled />}
        />
      );
    });
  };
  render() {
    const {
      comParameterList, comThirdAppList, dToDayNumSum, dTobeDoneSum, tabsPanes, loadings, tableTreeData, columns, tableData, logoImageInfo = [],
    } = this.state;
    const { app } = this.props;
    const KPIMonitor = commonFunc.showMessage(app.commonConst, 'KPIMonitor');/* KPI监控 */
    const toDoTask = commonFunc.showMessage(app.commonConst, 'toDoTask');/* 待处理 */
    const ToDoAudited = commonFunc.showMessage(app.commonConst, 'ToDoAudited');/* 待审核 */
    const MyWarning = commonFunc.showMessage(app.commonConst, 'MyWarning');/* 我的预警 */
    const CalculateWorkload = commonFunc.showMessage(app.commonConst, 'CalculateWorkload');/* 计算工作量 */
    const TodayAffair = commonFunc.showMessage(app.commonConst, 'TodayAffair');/* 今日事务:  */
    const unclearedTotal = commonFunc.showMessage(app.commonConst, 'unclearedTotal');/* 未清总数: */
    const CommonOperation = commonFunc.showMessage(app.commonConst, 'CommonOperation');/* 常用操作 */
    const CommonThirdAppTitle = commonFunc.showMessage(app.commonConst, 'thirdAppList') || '第三方应用列表';/* 第三方应用 */
    const Copyright = commonFunc.showMessage(app.commonConst, 'Copyright');/* Copyright */
    const AddrOne = commonFunc.showMessage(app.commonConst, 'AddrOne');/* 小羚羊软件 */
    const AddrTwo = commonFunc.showMessage(app.commonConst, 'AddrTwo');/*  印刷智慧工厂 */
    const AddrThree = commonFunc.showMessage(app.commonConst, 'AddrThree');/*  印刷MES */
    const AddrFour = commonFunc.showMessage(app.commonConst, 'AddrFour');/* 印刷ERP */
    const AddrFive = commonFunc.showMessage(app.commonConst, 'AddrFive');/* 印刷电商平台 */
    const AddrSix = commonFunc.showMessage(app.commonConst, 'AddrSix');/* 文件智能处理 */
    const AddrSeven = commonFunc.showMessage(app.commonConst, 'AddrSeven');/* 印前自动化 */
    const AddrEight = commonFunc.showMessage(app.commonConst, 'AddrEight');/* 地址 */
    const AddrIcp = '沪ICP备14034791号-1';/* 备案号 */
    //
    const NavigationType = commonUtils.isNotEmptyObject(commonFunc.showMessage(app.commonConst, 'NavigationType')) ? commonFunc.showMessage(app.commonConst, 'NavigationType')
      : '导航类型';/* 导航类型 */

    const { currentPane, userinfo, token, footer } = app;
    let sModelsType = '';
    /* 判断当前打开界面是不是外嵌的url */
    if (currentPane !== undefined) {
      // eslint-disable-next-line prefer-destructuring
      sModelsType = currentPane.sModelsType;
    }
    let addressStr = location.protocol + '//' + location.host;
    if (sModelsType && sModelsType.includes('http')) {
      addressStr = location.host;
    }
    // addressStr = 'http://172.19.18.21/';
    const ipPadAddress = 'https://172.19.18.21:8443';
    const iframeUrl = sModelsType !== undefined ? sModelsType.replace('{sBrandsId}', userinfo.sBrandsId).replace('{sSubsidiaryId}', userinfo.sSubsidiaryId).replace('{sUserName}', userinfo.sUserName).replace('{sUserId}', userinfo.sId)
      .replace('{token}', token)
      .replace('{ipAddress}', addressStr)
      .replace('{ipPadAddress}', ipPadAddress) : '';


    const ExtraWrap = (
      <div className={styles.extraWrap}>
        {/*<Checkbox.Group*/}
        {/*  className={styles.extraCheckBox}*/}
        {/*  onChange={this.handleCheckBoxChange}*/}
        {/*  defaultValue={['Pending', 'PendingCheck', 'MyWarning']}*/}
        {/*>*/}
        {/*  <Checkbox value="Pending">{toDoTask}</Checkbox>*/}
        {/*  <Checkbox value="PendingCheck">{ToDoAudited}</Checkbox>*/}
        {/*  <Checkbox value="MyWarning">{MyWarning}</Checkbox>*/}
        {/*</Checkbox.Group>*/}
        <Button type="primary" icon={<BankOutlined />} loading={loadings} onClick={this.handleGetModelCenter}>{CalculateWorkload}</Button>
      </div>
    );
    // 修改foot的logo
    const xlyFootLogo = logoImageInfo[3] === '' ? logo : logoImageInfo[3];
    return (
      <div className={styles.indexCenter}>
        {
          sModelsType && (sModelsType.includes('ipAddress') || sModelsType.includes('ipPadAddress') || sModelsType.includes('indexPad')) ?
            <div>
              <Button id="btnOpenDetail" style={{ display: 'none' }} type="primary" icon={<BankOutlined />} loading={loadings} onClick={() => this.handleOpenTab('', '')}>待办</Button>
              <Button id="btnOpenDetailHand" style={{ display: 'none' }} type="primary" icon={<BankOutlined />} loading={loadings} onClick={() => this.handleOpenTab('', '')}>办理</Button>
              <input id="sFormId" value="" style={{ display: ' none' }} />
              <input id="sBillId" value="" style={{ display: ' none' }} />
              <input id="bFlow" value="" style={{ width: '300px', display: 'none' }} />
              <textarea id='sFlowData' rows="10" cols="30" style={{ width: '300px', display: 'none' }} />

              {/*<Button id="btnOpenDetail" style={{ display: 'block' }} type="primary" icon={<BankOutlined />} loading={loadings} onClick={() => this.handleOpenTab('', '')}>待办</Button>*/}
              {/*<Button id="btnOpenDetailHand" style={{ display: 'block' }} type="primary" icon={<BankOutlined />} loading={loadings} onClick={() => this.handleOpenTab('', '')}>办理</Button>*/}

              {/*<input id="sFormId" value="12710101117014147688950" style={{ display: ' block' }} />*/}
              {/*<input id="sBillId" value="17657164930008384898449554260000" style={{ display: ' block' }} />*/}

              {/*<input id="bFlow" value="true" style={{ width: '300px', display: 'block' }} />*/}
              {/*<textarea id='sFlowData' rows="10" cols="30" style={{ width: '300px', display: 'block' }} />*/}

              {/* eslint-disable-next-line jsx-a11y/iframe-has-title */}
              <iframe id="iframe1" src={iframeUrl} style={{ width: '100%', height: '85vh' }} frameBorder="0" />
            </div> :
            <div>
              <Layout id={styles.kpi}>
                <Content className={styles.kpi}>
                  <Card title={KPIMonitor} extra={ExtraWrap}>
                    <div className={styles.extraCalc}>
                      <p>{TodayAffair}：<span style={{ fontWeight: 'bolder', color: '#ff0000' }} className={dToDayNumSum === 0 ? '' : styles.blink}>{dToDayNumSum}</span>|</p>
                      <p>{unclearedTotal}：<span>{dTobeDoneSum}</span></p>
                    </div>
                    <div className={styles.indexTabs}>
                      <div className={styles.navType}>
                        <div className={styles.tableTreeTitle}>{NavigationType}</div>
                        <div className={styles.tableTree} ref={(ref) => {
                          this.tableTree = ref;
                          if (this.tableTree && this.tableTreeScrollTop) {
                            this.tableTree.scrollTop = this.tableTreeScrollTop;
                          }
                        }}>
                          <Tree
                            key={
                              commonUtils.isNotEmptyArr(tableTreeData) ? this.treeId : Math.random()
                            }
                            className={"hide-file-icon"}
                            // switcherIcon={<img src={file} alt="svg" />}
                            onSelect={(e, select) => {
                              try {
                                let treeNode = '';
                                for (let i = 0; i < 10; i++) {
                                  treeNode = i === 0 ? select.nativeEvent.target : treeNode.parentNode;
                                  if (treeNode.classList.contains('ant-tree-treenode')) {
                                    treeNode.querySelector('.ant-tree-switcher').click();
                                    break;
                                  };
                                }
                              } catch (error) { }
                              if (!e[0]) {
                                return;
                              }
                              const { treeNode } = select.selectedNodes[0];
                              const { sId, data, columns } = treeNode;
                              if (commonUtils.isEmptyObject(data)) {
                                return;
                              }
                              this.activeTree = sId;
                              this.tableTreeScrollTop = this.tableTree.scrollTop;
                              this.kpiTableScrollTop = 0;
                              if (this.kpiTable && this.kpiTable.querySelector('.ant-table-body')) {
                                this.kpiTable.querySelector('.ant-table-body').scrollTop = 0;
                              }
                              this.recordTableTreeState();
                              this.setState({
                                columns,
                                tableData: data
                              })
                            }}
                            defaultSelectedKeys={[this.activeTree]}
                            defaultExpandAll={true}
                          >
                            {this.renderTreeNodes(tableTreeData)}
                          </Tree>
                        </div>
                      </div>
                      {/* {tableTree} */}
                      <div
                        className={styles.indexPageTable}
                        ref={(ref) => {
                          this.kpiTable = ref;
                          if (this.kpiTable && this.kpiTable.querySelector('.ant-table-body') && this.kpiTableScrollTop) {
                            this.kpiTable.querySelector('.ant-table-body').scrollTop = this.kpiTableScrollTop;
                          }
                        }}
                      >
                        <Table
                          columns={columns}
                          dataSource={tableData.map((item, index) => ({ ...item, sColor: index % 2 ? 'evenRow' : 'oddRow' }))}
                          size="middle"
                          pagination={false}
                          id="kpiTable"
                          scroll={{ x: 'max-content', y: 'calc(100vh - 235px)' }}
                          onRow={(record) => { return { onDoubleClick: () => { this.handleDoubleClick(record); } }; }}
                          rowClassName={this.getRowClassName}
                        />
                      </div>
                      {/* <Tabs className={styles.indexTabs}>
                        {tabsPanes}
                      </Tabs> */}
                    </div>
                  </Card>
                </Content>
                <Sider width={230} style={{ background: '#888888' }} className={styles.commonOpt} id="commonOpt">
                  <Card title={CommonOperation} style={{ height: '60%' }}>
                    <Menu
                      onClick={this.handleTabClick}
                      mode="inline"
                    >
                      {comParameterList}
                    </Menu>
                  </Card>
                  <Card title={CommonThirdAppTitle}
                  headStyle={{ fontWeight: 'bold', fontSize: '16px' }}
                  style={{ height: '40%', color: '#888888', fontWeight:'bold', fontSize: '16px' }}>
                    <Menu
                      onClick={this.handleTabClick}
                      mode="inline"
                    >
                      {comThirdAppList}
                      </Menu>
                  </Card>
                </Sider>
              </Layout>
              <CommonChar {...this.props} indexCenter />
            </div>
        }
        <Footer className={styles.indexFooter}>
          {xlyFootLogo && <img alt="logo" src={xlyFootLogo} style={{ marginRight: 10, maxWidth: 20, maxHeight: 20 }} />}
          ©{Copyright} <span className={styles.linkStyle}><a href="http://www.xlyprint.com/" target="_blank" rel="noopener noreferrer">{AddrOne}</a> </span>
          {
            commonUtils.isNotEmptyArr(footer) ? (
              <>
                {footer.map(item => {
                  const { sIcon, sLink, sName } = item;
                  let sPart = '';
                  const sIconPart = sIcon ? <img src={sIcon} alt="" /> : '';
                  if (sLink) {
                    sPart = <> | <span className={styles.linkStyle}><a href={sLink} target="_blank" rel="noopener noreferrer"> {sIconPart} {sName}</a></span></>;
                  } else {
                    sPart = <> | <span>{sIconPart}{sName}</span></>;
                  }
                  return sPart;
                })}
              </>
            ) : <> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/zngc.html" target="_blank" rel="noopener noreferrer">{AddrTwo}</a> </span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/znwl.html" target="_blank" rel="noopener noreferrer">{AddrThree}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yb.html" target="_blank" rel="noopener noreferrer" >{AddrFour}</a></span> |  <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yshlw.html" target="_blank" rel="noopener noreferrer">{AddrFive}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/znwj.html" target="_blank" rel="noopener noreferrer">{AddrSix}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yqzdh.html" target="_blank" rel="noopener noreferrer">{AddrSeven}</a></span> | {AddrEight}| <span className={styles.linkStyle}><a href="http://beian.miit.gov.cn" target="_blank" rel="noopener noreferrer"> <img src="//gw.alicdn.com/tfs/TB1jwakrbH1gK0jSZFwXXc7aXXa-20-20.png" alt="" /> {AddrIcp}</a></span></>
          }
          {/* ©{Copyright} <span className={styles.linkStyle}><a href="http://www.xlyprint.com/" target="_blank" rel="noopener noreferrer">{AddrOne}</a> </span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/zngc.html" target="_blank" rel="noopener noreferrer">{AddrTwo}</a> </span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/znwl.html" target="_blank" rel="noopener noreferrer">{AddrThree}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yb.html" target="_blank" rel="noopener noreferrer" >{AddrFour}</a></span> |  <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yshlw.html" target="_blank" rel="noopener noreferrer">{AddrFive}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/znwj.html" target="_blank" rel="noopener noreferrer">{AddrSix}</a></span> | <span className={styles.linkStyle}><a href="http://www.xlyprint.com/yqzdh.html" target="_blank" rel="noopener noreferrer">{AddrSeven}</a></span> | {AddrEight}| <span className={styles.linkStyle}><a href="http://beian.miit.gov.cn"> <img src="//gw.alicdn.com/tfs/TB1jwakrbH1gK0jSZFwXXc7aXXa-20-20.png" alt="" /> {AddrIcp}</a></span> */}
        </Footer>
      </div>
    );
  }
}

export default IndexCenter;
