/* eslint-disable object-curly-newline */
import React, { Component } from 'react';
import { message } from 'antd-v4';
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import * as commonServices from '../../services/services';

export default (ChildComponent) => {
  return class Base extends Component {
    constructor(props) {
      super(props);
      this.state = {
        pageLoading: true,
        token: props.app.token,
        sTabId: this.handleConfigValue(props, 'key'),
        sModelsId: props.routing ? props.sModelsId : this.handleConfigValue(props, 'formId'), /* 获取配置数据用的modelId */
        formRoute: props.routing ? props.routing.pathname.replace('/', '') : props.formRoute !== undefined ? props.formRoute : '',
        formSrcRoute: props.routing ? props.routing.pathname.replace('/', '') : '',
        // this.handleConfigValue('formId')
        charConfigAndData: [], /* 总图表配置及数据 */
        charConfigList: [], /* 配置集 */
        gdsformconst: [], /* 常量 */
        charMenu: [], /* 图表右查询菜单 */
        labelConfigData: [], /* 标签总数据 */
      };
    }

    async componentWillMount() {
      // eslint-disable-next-line no-unused-vars
      const { token } = this.state;
      const pathname = commonUtils.isNotEmptyObject(this.props) && commonUtils.isNotEmptyObject(this.props.location) ? this.props.location.pathname : '';
      if (pathname === '/commonAuto') {
        const formObj = await this.handleGetModule(this.props);
        let sModelsId = '';
        let sBackgroundImage = '';
        if (commonUtils.isNotEmptyObject(formObj)) {
          sModelsId = formObj.formId;
          sBackgroundImage = formObj.sTitleLogoPath;
        }
        this.setState({ sModelsId, sBackgroundImage });
      }
      /* 获取配置 */
      this.handleCharConfig();
    }

    /* 获取配置数据用的sTabId,formId */
    handleConfigValue = (props, value) => {
      const { secondppopupPane, ppopupPane, currentPane, panes } = this.props.app;
      const { indexCenter } = this.props;

      let data = '';
      if (indexCenter === 'indexCenter') {
        const iIndex = panes.findIndex(item => item.route === '/indexPage');
        if (iIndex > -1) {
          data = panes[iIndex][value];
        }
      } else if (commonUtils.isNotEmptyStr(props.sModelsId)) {
        data = props.sModelsId;
      } else {
        data = commonUtils.isNotEmptyObject(secondppopupPane)
          ? secondppopupPane[value]
          : commonUtils.isNotEmptyObject(ppopupPane)
            ? ppopupPane[value] : currentPane[value];
      }
      return data;
    };

    /* 获取commonAuto大屏sFormId */
    handleGetModule = async (props) => {
      const search = commonUtils.isNotEmptyObject(props) ? props.location.search : '';
      const configUrl = `${commonConfig.server_host}getModleByType${search}`;
      const { data } = await commonServices.getService('', configUrl);
      const formObj = {};
      if (data.code === 1) {
        formObj.formId = data.dataset.rows[0].sId;
        formObj.sTitleLogoPath = data.dataset.rows[0].sTitleLogoPath;
      } else {
        message.error(data.msg);
      }
      return formObj;
    }
    /* 获取图表配置 */
    handleCharConfig = async () => {
      const { token, sModelsId, formRoute } = this.state;
      const configUrl = `${commonConfig.server_host}char/getCharConfig/${sModelsId}?sModelsId=${sModelsId}&sName=${formRoute}`;
      const { data } = await commonServices.getService(token, configUrl);
      if (data.code === 1) {
        const [configData] = data.dataset.rows;
        if (commonUtils.isNotEmptyArr(configData)) {
          this.handleGetData(configData);
        }
      } else {
        message.error(data.msg);
      }
    };

    /* 获取数据 */
    handleGetData = (configData, pageNum) => {
      const { charConfigList } = configData; /* 图标配置集 */
      // const charConfigAndData = [];
      const { charConfigAndData, formRoute, formSrcRoute } = this.state;
      const addState = commonUtils.isEmpty(pageNum) ? {} : { pageNum };
      const charMenu = [];
      if (commonUtils.isNotEmptyArr(charConfigList)) {
        for (const each of charConfigList) {
          const { sId } = each;
          const childConfig = commonUtils.isNotEmptyArr(each.childConfig) ? each.childConfig : [];
          const radioType = commonUtils.isNotEmptyArr(childConfig) ? childConfig[0].sTypeValue : null;
          charMenu.push({ sId, childConfig, radioType });
          if (each.sCharType === 'Div' && commonUtils.isEmpty(each.sCharParentId)) { /* 拿到后台顶元素配置的刷新时间 */
            const dRefreshTime = commonUtils.isNotEmptyNumber(each.dRefreshTime) && each.dRefreshTime !== 0 ? each.dRefreshTime * 1000 : 100000;
            addState.dRefreshTime = dRefreshTime;
          }
          const iIndex = charConfigAndData.findIndex(item => item.sId === sId);
          if (iIndex > -1) {
            charConfigAndData[iIndex] = { ...each, child: {} };
          } else {
            charConfigAndData.push({ ...each, child: {} });
          }
          if (each.sCharType === 'commonList' || each.sCharType === 'Div' || each.sCharType === 'sLabel' || each.sCharType === 'Progress') {
          // this.handleEachChar(each);
          } else {
            this.handleEachChar(each);
          }
        }
        /* 通用滚动大屏界面根据存储过程名称获取sLabel所有数据 */
        if (formRoute === '/commonAuto' || formSrcRoute === '/commonAuto') {
          const filterData = charConfigList.filter(item => commonUtils.isEmptyObject(item.sCharParentId));
          if (commonUtils.isNotEmptyArr(filterData)) {
            const rootDiv = filterData[0];
            if (commonUtils.isNotEmptyObject(rootDiv) && rootDiv.sCharType === 'Div') {
              let proName = 'Sp_title_CommonModel1';
              proName = rootDiv.sProcedureName;
              let prodParamsMap = {};
              if (commonUtils.isNotEmptyObject(rootDiv.prodParamsMap)) {
                // eslint-disable-next-line prefer-destructuring
                prodParamsMap = rootDiv.prodParamsMap;
              }
              this.handleGetLabelData(proName, prodParamsMap);
            }
          }
        }
      }
      this.setState({ ...configData, charMenu, ...addState });
    };

    handleToFirst = () => {
      this.setState({ pageNum: 0 });
    }

    /* 获取单个图表数据 */
    /*
   handleEachChar = async (each) => {
     const { token, sModelsId, charConfigAndData } = this.state;
     const sSqlCondition = commonUtils.isNotEmptyObject(each.sSqlCondition) ? each.sSqlCondition : {};
     const value = { sProcedureNo: each.sProcedureNo, sSqlCondition };
     const url = `${commonConfig.server_host}char/getCharData?sModelsId=${sModelsId}`;
     const { data } = await commonServices.postValueService(token, value, url);
     let child = [];
     if (data.code === 1) {
       [child] = data.dataset.rows;
       const index = charConfigAndData.findIndex(item => item.sProcedureNo === each.sProcedureNo);
       if (index > -1) {
         charConfigAndData[index].child = child;
       }
     } else {
       message.error(data.msg);
     }
     this.setState({ charConfigAndData });
   };
  */
    handleEachChar = async (each) => {
      const { token, sModelsId, charConfigAndData, formRoute } = this.state;
      const value = { sProName: each.sProcedureName, paramsMap: each.prodParamsMap };
      const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}&sName=${formRoute}`;
      const { data: returnData } = await commonServices.postValueService(token, value, url);
      if (returnData.code === 1) {
        const { dataset } = returnData;
        if (commonUtils.isNotEmptyObject(dataset)) {
          const outData = returnData.dataset.rows[0].dataSet.outData[0];
          if (outData.sCode === -1) {
            message.error(outData.sReturn);
          } else {
            const xyData = commonUtils.isEmpty(outData.sReturn) ? [] : JSON.parse(outData.sReturn);
            const index = charConfigAndData.findIndex(item => item.sProcedureName === each.sProcedureName && item.sId === each.sId);
            if (index > -1) {
              charConfigAndData[index].child = xyData;
            }
          }
        }
      } else {
        message.error(returnData.msg);
      }
      this.setState({ charConfigAndData });
    };
    handleGetLabelData = async (name, prodParamsMap) => {
      const { app } = this.props;
      const { sModelsId } = this.state;
      let { labelConfigData } = this.state;
      const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}&sName=commonAuto`;
      const value = {
        sProName: name,
        paramsMap: prodParamsMap,
      };
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      if (returnData.code === 1) {
        if (commonUtils.isNotEmptyObject(returnData.dataset)) {
          const labelReturnData = returnData.dataset.rows[0].dataSet.proData;
          if (commonUtils.isNotEmptyArr(labelReturnData)) {
            labelConfigData = labelReturnData;
          }
        }
      } else {
        message.error(returnData.msg);
      }
      this.setState({ labelConfigData });
    };
    //
    // /* 获取后台数据（数据集） */
    // handleGetDataSet = async (params) => {
    //   const {
    //     name, configData, condition, flag, isWait, clearSelectData,
    //   } = params;
    //   const {
    //     token, sModelsId, formRoute, [`${name}SelectedData`]: tableSelectedData,
    //   } = this.state;
    //   let {
    //     [`${name}SelectedRowKeys`]: tableSelectedRowKeys,
    //   } = this.state;
    //   const configDataId = configData.sId;
    //   const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}&sName=${formRoute}`;
    //   const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
    //   if (dataReturn.code === 1) {
    //     const returnData = dataReturn.dataset.rows[0].dataSet;
    //     if (commonUtils.isNotEmptyObject(returnData)) {
    //       if (commonUtils.isEmptyArr(tableSelectedData)) {
    //         if (formRoute !== '/materialRequirementsPlanning' && formRoute !== '/commonClassify') {
    //           if (commonUtils.isNotEmptyStr(returnData[0].sSlaveId)) {
    //             const keys = [];
    //             keys.push(returnData[0].sSlaveId);
    //             tableSelectedRowKeys = keys;
    //           } else {
    //             const keys = [];
    //             keys.push(returnData[0].sId);
    //             tableSelectedRowKeys = keys;
    //           }
    //         }
    //         if (flag) {
    //           tableSelectedRowKeys = [];
    //         }
    //       }
    //     }
    //     if (clearSelectData) {
    //       tableSelectedRowKeys = [];
    //     }
    //     const returnPagination = {
    //       total: dataReturn.dataset.totalCount,
    //       current: dataReturn.dataset.currentPageNo,
    //     };
    //     const { sumSet } = dataReturn.dataset.rows[0];
    //     const totalData = sumSet !== undefined ? sumSet : [];
    //     const filterCondition = commonUtils.isNotEmptyObject(condition) ? condition.bFilter : '';
    //     const orderBy = commonUtils.isNotEmptyObject(condition) ? condition.sFilterOrderBy : '';
    //     /* 去除树搜索filterCondition */
    //     const filterConditionNew = commonUtils.isNotEmptyObject(filterCondition) ? filterCondition.filter(item => item.bFilterType !== 'tree') : '';
    //     let addState = {
    //       [`${name}Data`]: returnData, [`${name}Pagination`]: returnPagination, [`${name}FilterCondition`]: filterConditionNew, [`${name}OrderBy`]: orderBy, [`${name}SelectedRowKeys`]: tableSelectedRowKeys,
    //     };
    //     if (dataReturn.dataset.currentPageNo === 1) {
    //       addState = { ...addState, [`${name}Total`]: totalData };
    //     }
    //     const slaveSelectedData = [];
    //     if ((formRoute === '/commonList' || formRoute === '/materialRequirementsPlanning') && name === 'slave' && commonUtils.isNotEmptyArr(tableSelectedRowKeys) && !clearSelectData) {
    //       tableSelectedRowKeys.forEach((item) => {
    //         const iPageIndex = returnData.findIndex(pageItem => pageItem.sSlaveId === item);
    //         if (iPageIndex > -1) {
    //           slaveSelectedData.push(returnData[iPageIndex]);
    //         } else if (commonUtils.isNotEmptyArr(tableSelectedData)) {
    //           const iIndex = tableSelectedData.findIndex(pageItem => pageItem.sSlaveId === item);
    //           if (iIndex > -1) {
    //             slaveSelectedData.push(tableSelectedData[iIndex]);
    //           }
    //         }
    //       });
    //     }
    //     addState[`${name}SelectedData`] = slaveSelectedData;
    //     if (isWait) {
    //       return addState;
    //     } else if (this.mounted) {
    //       this.setState(addState);
    //     }
    //   } else {
    //     this.getServiceError(dataReturn);
    //   }
    // };

    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onEachChar={this.handleEachChar}
          onGetData={this.handleGetData}
          onToFirst={this.handleToFirst}
        />
      );
    }
  };
};

