/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
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'; /*   服务类   */
import * as commonFunc from '../Common/commonFunc';

// const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {};
      this.form = {};
      /*   表单对象   */
    }
    componentWillReceiveProps(nextProps) {
      const { isReceive, formData, app } = nextProps;

      if (!isReceive && formData.length > 0) {
        const templateConfig = formData.filter(item => item.bGrd);
        let selectOptions = '{';
        templateConfig.forEach((item, i) => {
          if (i !== 0) { selectOptions = selectOptions.concat(','); }
          selectOptions = selectOptions.concat(`"${item.sId}"`).concat(':').concat(`"${item.showName}"`);
        });
        selectOptions = selectOptions.concat('}');

        const importConfigTypes = [];

        const DataTemplate = commonFunc.showMessage(app.commonConst, 'DataTemplate');/* 数据模板 */
        const BtnUploadCheck = commonFunc.showMessage(app.commonConst, 'BtnUploadCheck');/* 上传校验 */
        const importData = commonFunc.showMessage(app.commonConst, 'importData');/* 导入数据 */
        const BtnExportTemplate = commonFunc.showMessage(app.commonConst, 'BtnExportTemplate');/* 导出模板 */
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes(DataTemplate, 'sMasterId', 'sMasterId', false, 'const', selectOptions, false));
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes(BtnUploadCheck, 'btnUpload', '', false, '', '', true));
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes(importData, 'btnSave', '', false, '', '', false));
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes(BtnExportTemplate, 'btnExport', '', false, '', '', false));

        const currConfig = {};
        currConfig.rowGdsconfig = [{ gdsconfigformslave: importConfigTypes }];

        const masterData = {};
        masterData.handleType = '';
        masterData.sId = commonUtils.createSid();

        this.props.onSaveState({
          masterData,
          templateConfig,
          isReceive: true,
          masterConfig: currConfig,
          pageLoading: false,
          enabled: true,
        });
        this.handleGetChangeData({ name: 'importMenu' }, 'importMenu');
      }
    }

    shouldComponentUpdate(nextProps, nextState) {
      let flag = true;
      /* 追加弹出框数值回填放行判断ppopupPane */
      if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
          && nextProps.app.ppopupPane.mainConfig !== undefined)
        ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
        if (nextState.disabled !== this.state.disabled) {
          return true;
        }
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    }

    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /** 主表控件是否全部显示 */
    handleToggle = () => {
      const { expand } = this.props;
      this.props.onSaveState({ expand: !expand });
    };
    /* save */
    handleValidateSave = async () => {
      const {
        token, sModelsId, sJurisdictionClassifyId, sUserId, treeSaveParams, app,
      } = this.props;
      const value = {};
      if ((commonUtils.isEmptyArr(sJurisdictionClassifyId) || commonUtils.isEmptyArr(sUserId)) && commonUtils.isEmptyArr(treeSaveParams)) {
        message.warn(commonFunc.showMessage(app.commonConst, 'NotEmptyJurisdictionGroup'));
        return;
      }
      value.data = treeSaveParams;
      const dataUrl = `${commonConfig.server_host}/sysjurisdiction/addSysjurisdiction?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      /*   成功的话返回数据   */
      if (dataReturn.code === 1) { /*   成功   */
        message.success(dataReturn.msg);
        return dataReturn;
      } else { /*   失败   */
        this.props.getServiceError(dataReturn);
        return false;
      }
    }

    /* get */
    handleGetChangeData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const { name, gdsconfigformmasterId } = params; // name,
      let dataUrl = '';// ImportMenu
      if (urlKey === 'importMenu') { // yw_获取导入模板菜单
        dataUrl = `${commonConfig.server_host}import/getImportMenu?sModelsId=${sModelsId}`;
      } else if (urlKey === 'exportTemplet') { // yw_导出将要导入的模板execl
        dataUrl = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${gdsconfigformmasterId}&token=${token}`;
      }
      const dataReturn = (await commonServices.getService(token, dataUrl)).data;
      if (dataReturn.code === 1) {
        const returnData = dataReturn.dataset.rows;
        this.props.onSaveState({ [`${name}Data`]: returnData });
      } else {
        this.props.getServiceError(dataReturn);
      }
    }

    /* post */
    handlePostData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const {
        name, gdsconfigformmasterId, file, execlData, sTableName,
      } = params; // name,
      let dataUrl = '';
      const value = {};
      if (urlKey === 'checkExcel') { // yw_校验导入模板数据
        value.gdsconfigformmasterId = gdsconfigformmasterId;
        value.file = file;
        dataUrl = `${commonConfig.server_host}import/checkExcel?sModelsId=${sModelsId}`;
      } else if (urlKey === 'addImport') {
        dataUrl = `${commonConfig.server_host}import/addImport?sModelsId=${sModelsId}`;
        value.sTableName = sTableName;
        value.execlData = execlData;
      }
      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      if (dataReturn.code === 1) {
        if (urlKey === 'checkExcel') {
          const returnData = dataReturn.dataset.rows;
          const allInitArr = [];
          const allInitMap = new Map();
          this.handleAllCheckKeys(allInitArr, allInitMap, returnData);
          this.props.onSaveState({ [`${name}Data`]: returnData, treeAllCheckKeys: allInitArr, treeAllNodes: allInitMap });
        } else if (urlKey === 'addImport') {
          this.props.onSaveState({ nocanbeInsertData: [], canbeInsertData: [] });
          message.info(dataReturn.msg);
        }
      } else {
        this.props.getServiceError(dataReturn);
      }
    }

    /** 修改主表数据 */
    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData) => {
      const addState = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
      const gdsconfigformmasterId = {};
      const { templateConfig } = this.props;
      if (sFieldName === 'sMasterId') {
        addState.gdsconfigformmasterId = changeValue[sFieldName];
        const iIndex = templateConfig.findIndex(item => item.sId === changeValue[sFieldName]);
        const configTypes = [];// importMenuData
        configTypes.push(commonFunc.getImitateGdsconfigTypes('原因', 'sReason', 'sReason', false, '', '', false));

        const canbeInsertConfig = templateConfig[iIndex];
        const canbeInsertColumn = commonFunc.getHeaderConfig(canbeInsertConfig);

        const nocanbeInsertConfig = { gdsconfigformslave: configTypes.concat(templateConfig[iIndex].gdsconfigformslave) };
        const nocanbeInsertColumn = commonFunc.getHeaderConfig(nocanbeInsertConfig);

        addState.nocanbeInsertConfig = nocanbeInsertConfig;
        addState.nocanbeInsertColumn = nocanbeInsertColumn;
        addState.canbeInsertConfig = canbeInsertConfig;
        addState.canbeInsertColumn = canbeInsertColumn;
        addState.nocanbeInsertData = [];
        addState.canbeInsertData = [];
      }
      this.props.onSaveState({ gdsconfigformmasterId, ...addState });
    };

    handleUploadChange = (sControlName, info) => {
      /* 获取上传后的一些信息 */
      const { file } = info;
      let { [`${sControlName}UploadInfo`]: uploads } = this.props;
      if (commonUtils.isEmptyArr(uploads)) {
        uploads = [];
        uploads.push(file);
      } else {
        uploads.push(file);
      }
      this.props.onSaveState({ [`${sControlName}UploadInfo`]: uploads });
    };

    /* 按钮点击功能  */
    handleBtnClick = (e, btnName) => {
      const {
        masterData, app, canbeInsertData, nocanbeInsertData,
      } = this.props;
      const { token } = app;
      const { sMasterId, sTableName } = masterData;
      if (btnName === 'btnExport') {
        if (commonUtils.isNotEmptyObject(masterData) && commonUtils.isNotEmptyObject(sMasterId)) {
          // window.location.href = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${sMasterId}&token=${token}`;
          const url = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${sMasterId}&token=${token}`;
          window.open(url);
        } else {
          const chooseImprtTemplete = commonFunc.showMessage(app.commonConst, 'chooseImprtTemplete');/* 请选择要导出的模板 */
          message.error(chooseImprtTemplete);
        }
      } else if (btnName === 'btnSave') {
        if (commonUtils.isNotEmptyArr(nocanbeInsertData) && commonUtils.isNotEmptyArr(canbeInsertData) && commonUtils.isNotEmptyObject(sTableName) && nocanbeInsertData.length === canbeInsertData.length) {
          this.handlePostData({ name: 'addImport', execlData: canbeInsertData, sTableName }, 'addImport');
        } else {
          message.error(commonFunc.showMessage(app.commonConst, 'ErrorImport')); /* 有错误数据，不能导入 */
        }
      }
    };

    /* 按钮点击功能  */
    handleShowUploadData = (response) => {
      const { masterData } = this.props;

      if (response.code === 1) {
        const returnData = response.dataset.rows[0];
        const {
          nocanbeInsert, canbeInsert, sTableName,
        } = returnData;

        masterData.sTableName = sTableName;
        this.props.onSaveState({
          masterData,
          nocanbeInsertData: nocanbeInsert.concat(canbeInsert),
          canbeInsertData: canbeInsert,
        });
      } else {
        message.error(response.msg);
      }
    };

    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onToggle={this.handleToggle}
          onSubmit={this.handleValidateSave}
          onDataChange={this.handleTableChange}
          onChange={this.handleMasterChange}
          onUploadChange={this.handleUploadChange}
          onBtnClick={this.handleBtnClick}
          onShowData={this.handleShowUploadData}
        />
      );
    }
  };
};
