/* eslint-disable prefer-destructuring */
/**
 * Created by mar105 on 2019-02-15.
 */

import React, { Component } from 'react';
import moment from 'moment';
import { Modal, Toast } from 'antd-mobile-v2';
import { addResult } from '@/utils/common/calcuate';
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import * as commonServices from '../../services/services';
import * as commonFunc from '../../components/Common/commonFunc';
import * as commonBusiness from '../../components/Common/commonBusiness';
// import * as commonFunc from './commonFunc'; /* 通用单据方法 */

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        pageLoading: true,
        token: props.app.token,
        sModelsId: props.sModelsId, /* 获取配置数据用的modelId */
        formRoute: props.formRoute, /* 组件名： 路由名称 */
        sModelsType: props.sModelsType, /* 组件名： 路由名称 */
        formData: [], /* 所有配置 */
        gdsformconst: [], /* 获取配置常量 */
        gdsjurisdiction: [], /* 获取配置权限 */
        currentId: props.checkedId, /* 当前数据的Id */
        selectedRowKeys: [], /*   已选择的数据行(数据格式:数组)   */
        clearArray: [], /*   table清除数组   */
      };
      this.sDateFormat = 'YYYY-MM-DD';
    }

    async componentWillMount() {
      /* 获取配置 */
      this.mounted = true;
      const { token, sModelsId } = this.state;
      const config = await commonUtils.getStoreDropDownData(sModelsId, '', '');
      if (commonUtils.isEmpty(config)) {
        const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
        const configReturn = (await commonServices.getService(token, configUrl)).data;
        if (configReturn.code === 1) {
          const [configData] = configReturn.dataset.rows;
          // const { formData, gdsformconst, gdsjurisdiction, report, billnosetting } = configData;
          if (this.mounted) {
            // commonUtils.setStoreDropDownData(sModelsId, '', '', configData);
            this.setState({ ...configData });
          }
        } else {
          this.getServiceError(configReturn);
        }
      } else {
        this.setState({ ...config });
      }
    }

    shouldComponentUpdate(nextProps, nextState) {
      const { formData } = nextState;
      return (formData.length > 0);
    }

    componentWillUnmount() {
      const {
        currentId,
      } = this.state;
      const { copyTo } = this.props;
      const { userinfo } = this.props.app;
      if (commonUtils.isNotEmptyObject(copyTo)) {
        const { slaveData } = copyTo;
        if (commonUtils.isNotEmptyArr(slaveData)) {
          const sIdArray = [];
          slaveData.forEach((item) => {
            const redisKey = item.sSlaveId;
            sIdArray.push(redisKey);
          });
          const sId = sIdArray.toString();
          this.handleSendSocketMessage('copyfinish', 'noAction', sId, userinfo.sId, null, null);
        }
      }
      this.handleSendSocketMessage('release', 'noAction', currentId, userinfo.sId, null, null);
    }

    /**   sql条件   */
    getSqlCondition = (showConfig, name, record) => {
      const conditonValues = {};
      if (commonUtils.isNotEmptyStr(showConfig.sSqlCondition)) {
        const conditon = showConfig.sSqlCondition.split(',');
        conditon.forEach((item) => {
          if (item.indexOf('.') > -1) {
            const tableName = item.split('.')[0];
            let fieldName = item.split('.')[1];
            let fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName;
            // master.sId 作为参数   master.sId.sId 作为filterDropdown过滤参数
            if (showConfig.sDropDownType === 'picArr') {
              fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName;
              if (fieldName.indexOf('&Search') > -1) {
                // 参数为&Search时认为是查找数据集中取数据
                const data = this.state[`${tableName}Data`];
                if (typeof data === 'object' && data.constructor === Object) {
                  Object.keys(data).forEach((dataItem) => {
                    if (`&Search${data[dataItem]}` === fieldName) {
                      let sTmpName = dataItem;
                      sTmpName = sTmpName.replace('First', 'Third');
                      if (data[dataItem].substring(0, 1) === 't') {
                        fieldName = `p${sTmpName.substring(1, dataItem.length)}`;
                      } else {
                        fieldName = data[dataItem].substring(0, 1) + sTmpName.substring(1, sTmpName.length);
                      }
                    }
                  });
                }
              } else if (fieldName.indexOf('&') > -1) {
                fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName;
                conditonValues[fieldNameFilter] = fieldName.replace('&', '');
                return;
              }
            }
            if (fieldName !== '') {
              if (name === tableName && !commonUtils.isEmpty(record)) {
                const data = record;
                conditonValues[fieldNameFilter] = data[fieldName];
              } else {
                const data = this.state[`${tableName}Data`];
                const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
                if (typeof data === 'object' && data.constructor === Object) {
                  conditonValues[fieldNameFilter] = data[fieldName];
                } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
                  let iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]);
                  iIndex = iIndex > -1 ? iIndex : data.findIndex(itemData => itemData.sSlaveId === selectedRowKeys[0]);
                  if (iIndex > -1) {
                    conditonValues[fieldNameFilter] = data[iIndex][fieldName];
                  }
                } else if (commonUtils.isNotEmptyArr(data)) {
                  conditonValues[fieldNameFilter] = data[0][fieldName];
                }
              }
            }
          }
        });
      }
      return conditonValues;
    };

    /**   获取sql下拉数据   */
    getSqlDropDownData = async (formId, name, showConfig, record, platform) => {
      /*   地址   */
      if (commonUtils.isEmpty(showConfig.sFieldToContent)) {
        const url = `${commonConfig.server_host}business/getSelectDataBysControlId/${showConfig.sId}?sModelsId=${this.state.sModelsId}`;
        /*   参数   */
        const conditonValues = this.getSqlCondition(showConfig, name, record);
        const body = {
          sKeyUpFilterName: '', /*   边输入边过滤,暂时没用1   */
          sSqlCondition: commonUtils.isEmptyObject(conditonValues) ? '' : conditonValues, /*   查询条件   */
        };
        /*   获取数据   */
        const json = await commonServices.postValueService(this.props.app.token, body, url);
        /*   code为1代表获取数据成功   */
        if (json && commonUtils.isNotEmptyArr(json.data.dataset) && json.data.code === 1) {
          /*   获取数据集   */
          const { rows } = json.data.dataset;
          return rows;
        } else {
          if (['pda'].includes(platform)) {
            // Modal.alert('温馨提示', json?.data?.msg || '出错了', [
            //   { text: '确认' },
            // ]);
            const msg = json?.data?.msg || '出错了';
            Toast.fail(msg, 1);
            throw new Error();
          }
          return [];
        }
      } else {
        const returnData = [];
        if (showConfig.sFieldToContent === '1') {
          if (name === 'master') {
            const { [`${name}Data`]: data } = this.state;
            const sName = `sParamDropDown${showConfig.sName.replace('sParamValue', '')}`;
            returnData.push(...commonUtils.objectToArr(data[sName]));
          } else {
            const { [`${name}Data`]: data, [`${name}SelectedRowKeys`]: selectedRowKeys } = this.state;
            const sName = `sParamDropDown${showConfig.sName.replace('sParamValue', '')}`;
            if (commonUtils.isNotEmptyObject(record)) {
              returnData.push(...commonUtils.objectToArr(record[sName]));
            } else if (commonUtils.isNotEmptyArr(data) && commonUtils.isNotEmptyArr(selectedRowKeys)) {
              const iIndex = data.findIndex(item => item.sId === selectedRowKeys.toString());
              if (iIndex > -1) {
                returnData.push(...commonUtils.objectToArr(data[iIndex][sName]));
              }
            }
          }
        } else {
          const unionCondition = showConfig.sFieldToContent.split('&&');
          unionCondition.forEach((unionItem) => {
            const conditon = unionItem.split(',');
            const tableNameContent = conditon[0].split('.')[0];
            let data = this.state[`${tableNameContent}Data`];
            if (commonUtils.isNotEmptyArr(data)) {
              if (showConfig.sSqlCondition !== '') {
                const sSqlCondition = showConfig.sSqlCondition;
                const sqlConditon = sSqlCondition.split(',');
                sqlConditon.forEach((item) => {
                  const tableName = item.split('.')[0];
                  const fieldName = item.split('.')[1];
                  const fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName;
                  const dataCondition = this.state[`${tableName}Data`];
                  const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
                  if (typeof dataCondition === 'object' && dataCondition.constructor === Object) {
                    data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[fieldName], ''));
                  } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
                    let iIndex = dataCondition.findIndex(itemData => itemData.sId === selectedRowKeys[0]);
                    iIndex = iIndex > -1 ? iIndex : dataCondition.findIndex(itemData => itemData.sSlaveId === selectedRowKeys[0]);
                    if (iIndex > -1) {
                      data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[iIndex][fieldName], ''));
                    }
                  } else if (commonUtils.isNotEmptyArr(data)) {
                    data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[0][fieldName], ''));
                  }
                });
              }
              data.forEach((itemDataRow) => {
                const dataRow = {};
                conditon.forEach((item) => {
                  const fieldName = item.split('.')[1];
                  const fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName;
                  if (fieldName.indexOf('-') >= 0) {
                    fieldName.split('-').forEach((itemField) => {
                      const sFieldValue = commonUtils.isEmpty(itemDataRow[itemField]) ? '' : itemDataRow[itemField].toString();
                      dataRow[fieldNameFilter] = commonUtils.isEmpty(dataRow[fieldNameFilter]) ? sFieldValue : `${dataRow[fieldNameFilter]}-${sFieldValue}`;
                    });
                  } else {
                    dataRow[fieldNameFilter] = commonUtils.isEmpty(itemDataRow[fieldName]) ? '' : itemDataRow[fieldName].toString();
                  }
                });

                returnData.push(dataRow);
              });
            }
          });
        }
        return returnData;
      }
    };
    /*   获取数字格式化规范   */
    getFloatNum = (sName) => {
      if (sName.toLowerCase().endsWith('price')) { /*   价格   */
        return this.props.app.decimals.dNetPrice;
      } else if (sName.toLowerCase().endsWith('money')) { /*   金额   */
        return this.props.app.decimals.dNetMoney;
      } else { /*   其它   */
        return 6;
      }
    };

    /**   获取sql下拉数据   */
    getServiceError = async (returnData) => {
      this.props.dispatch({ type: 'app/throwErrorMobile', payload: returnData });
    };

    /*   获取数字格式化规范   */
    getDateFormat = () => {
      return this.props.app.dateFormat;
    };

    /* 获取配置数据用的sTabId,formId,formRoute */
    handleConfigValue = (value) => {
      const { secondppopupPane, ppopupPane, currentPane } = this.props.app;
      return commonUtils.isNotEmptyObject(secondppopupPane)
        ? secondppopupPane[value]
        : commonUtils.isNotEmptyObject(ppopupPane)
          ? ppopupPane[value] : currentPane[value];
    };

    /* 获取后台数据（单条） */
    handleGetDataOne = async (params) => {
      const { token, sModelsId } = this.state;
      const {
        name, configData, condition, isWait,
      } = params;

      const lockUrl = `${commonConfig.server_host}business/addSysLocking?sModelsId=${sModelsId}`;

      const configDataId = configData.sId;
      const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      if (dataReturn.code === 1) {
        const [returnData] = dataReturn.dataset.rows[0].dataSet;
        const addState = {};
        const value = {
          tableName: configData.sTbName,
          sId: [returnData.sId],
        };
        const { data } = await commonServices.postValueService(token, value, lockUrl);
        if (data.code === 1) { /*   失败   */
          addState.sUseInfo = '';
        } else { /*   失败   */
          addState.sUseInfo = data.msg;
        }
        addState[`${name}Data`] = returnData;
        if (isWait) {
          return addState;
        } else if (this.mounted) {
          this.setState({ ...addState });
        }
      } else {
        this.getServiceError(dataReturn);
      }
    };

    /* 获取后台数据（数据集） */
    handleGetDataSet = async (params) => {
      const {
        name, configData, condition, isWait,
      } = params;
      const {
        token, sModelsId, [`${name}SelectedRowKeys`]: tableSelectedRowKeys,
      } = this.state;
      const friendlyReminder = commonFunc.showLocalMessage(this.props, 'FriendlyReminder', '温馨提示');

      const btnSure = commonFunc.showLocalMessage(this.props, 'BtnSure', '确认');

      const configDataId = configData.sId;
      const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      if (dataReturn.code === 1) {
        const returnData = dataReturn.dataset.rows[0].dataSet;
        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 : '';
        let addState = {
          [`${name}Data`]: returnData, [`${name}Pagination`]: returnPagination, [`${name}FilterCondition`]: filterCondition, [`${name}OrderBy`]: orderBy, [`${name}SelectedRowKeys`]: tableSelectedRowKeys,
        };
        if (dataReturn.dataset.currentPageNo === 1) {
          addState = { ...addState, [`${name}Total`]: totalData };
        }
        if (isWait) {
          return addState;
        } else if (this.mounted) {
          this.setState(addState);
        }
      } else if (dataReturn.code === -8) {
        Modal.alert(friendlyReminder, dataReturn.msg || '出错了', [
          { text: btnSure },
        ]);
      } else {
        this.getServiceError(dataReturn);
      }
    };

    /* 数据保存到state */
    handleSaveState = (values) => {
      if (this.mounted) {
        this.setState(values);
      }
    };

    /** 修改主表数据 */
    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait, masterDataNew) => {
      const { masterData: masterDataOld } = this.state;
      const { sModelsId, masterConfig } = this.state;
      let masterData = masterDataNew === undefined ? masterDataOld === undefined ? {} : masterDataOld : masterDataNew;
      let { handleType } = masterData;
      handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
      if (sFieldName.substring(0, 1).toLowerCase() === 'c') {
        const sAllField = sFieldName.substring(1, sFieldName.length);
        const allField = sAllField.split('_');
        const value = changeValue[sFieldName];
        allField.forEach((item, iArr) => {
          if (value.length > iArr) {
            changeValue[item] = value[iArr];
          }
        });
      }
      if (!commonUtils.isEmpty(masterConfig.gdsconfigformslave) && commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave) && !commonUtils.isEmpty(sFieldName)) {
        masterConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) &&
          (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) &&
          (item.sSqlCondition.includes(sFieldName) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => {
          commonUtils.setStoreDropDownData(sModelsId, name, item.sName, []);
        });
      }
      masterData = { ...masterData, ...changeValue, handleType };
      if (isWait) {
        return { masterData, sUseInfo: '' };
      } else if (this.mounted) {
        this.setState({ masterData, sUseInfo: '' });
        return { masterData };
      }
    };

    /**   添加表格空行   */
    handleTableAdd = (name, isWait) => {
      /*   外置处理业务   */
      const {
        [`${name}Config`]: tableConfig, masterData, slaveData, slaveSelectedRowKeys,
      } = this.state;
      let { [`${name}Data`]: tableData } = this.state;
      tableData = commonUtils.isEmptyObject(tableData) ? [] : tableData;
      const allTableData = {};
      allTableData.master = masterData;
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys.toString());
        allTableData.slave = slaveData[iSlaveIndex];
      } else {
        allTableData.slave = slaveData[0];
      }
      const iOrderArr = [];
      tableData.forEach((item) => {
        const iOrder = commonUtils.isNotEmptyNumber(item.iOrder) ? item.iOrder : 0; /* 获取tableData中iOrder最大值 */
        iOrderArr.push(iOrder);
      });
      const iOrderMax = Math.max(...iOrderArr);
      const tableDataRow = commonFunc.getDefaultData(tableConfig, allTableData);
      tableDataRow.handleType = 'add';
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.sParentId = masterData && masterData.sId ? masterData.sId : null;
      tableDataRow.key = tableDataRow.sId;
      tableDataRow.bDefault = false;
      tableDataRow.iOrder = commonUtils.isNotEmptyArr(tableData) ? iOrderMax + 1 : 0;

      const iIndex = this.props.app.systemData.findIndex(item => item.sName === 'CbxMaterialsDefine');
      if (iIndex > -1) {
        const sCbxMaterialsDefine = this.props.app.systemData[iIndex].sValue;
        if (sCbxMaterialsDefine === 'datenum') {
          tableDataRow.sDefineNo = moment(new Date()).format('YYYYMMDD');
        } else if (sCbxMaterialsDefine === 'datetimenum') {
          tableDataRow.sDefineNo = moment(new Date()).format('YYYYMMDDHHmm');
        } else if (sCbxMaterialsDefine === 'yearnum') {
          tableDataRow.sDefineNo = moment(new Date()).format('YYYY');
        } else if (sCbxMaterialsDefine === 'yearmonthnum') {
          tableDataRow.sDefineNo = moment(new Date()).format('YYYYMM');
        } else if (sCbxMaterialsDefine === 'worknum') {
          tableDataRow.sDefineNo = tableDataRow.sWorkOrderNo;
        } else if (sCbxMaterialsDefine === 'manuualno') {
          tableDataRow.sDefineNo = tableDataRow.sManualNo;
        } else if (sCbxMaterialsDefine === 'createnownum') { /* 批号根据生产日期+当前日期 */
          tableDataRow.sDefineNo = moment(tableDataRow.tProductionDate).format('YYYYMMDDHHmm') + moment(new Date()).format('YYYYMMDDHHmm');
        }
      }

      if (isWait) {
        return tableDataRow;
      } else {
        // tableData.splice(index, 1, tableDataRow);  /* 该处会导致新增时删除首行 */
        tableData.push(tableDataRow);
        if (this.mounted) {
          this.setState({ [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: [tableDataRow.sId] });
        }
      }
    };

    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const {
        [`${name}Data`]: tableData, [`${name}Config`]: tableConfig, sModelsId, masterData, slaveData, controlData,
      } = this.state;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      let { handleType } = tableData[iIndex];
      handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
      if (sFieldName.substring(0, 1).toLowerCase() === 'c') {
        const sAllField = sFieldName.substring(1, sFieldName.length);
        const allField = sAllField.split('_');
        const value = changeValue[sFieldName];
        allField.forEach((item, iArr) => {
          if (value.length > iArr) {
            changeValue[item] = value[iArr];
          }
        });
      }
      if (!commonUtils.isEmpty(tableConfig.gdsconfigformslave) && commonUtils.isNotEmptyArr(tableConfig.gdsconfigformslave) && !commonUtils.isEmpty(sFieldName)) {
        tableConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && item.sSqlCondition.includes(sFieldName)).forEach((item) => {
          commonUtils.setStoreDropDownData(sModelsId, name, item.sName, []);
        });
      }
      const tableAllData = {
        master: masterData,
        slave: slaveData,
        control: controlData,
      };
      const tableDataRowNew = { ...tableData[iIndex], ...changeValue, handleType };
      const tableDataAfter = commonBusiness.getKeyUpEvent(name, sFieldName, tableConfig, tableDataRowNew, tableDataRowNew, true, tableAllData);
      console.log('tableDataAfter::', tableDataAfter);
      if (commonUtils.isNotEmptyObject(tableDataAfter)) {
        changeValue = { ...tableDataAfter };
      }
      if (isWait) {
        return { ...tableData[iIndex], ...changeValue, handleType };
      } else {
        tableData[iIndex] = { ...tableData[iIndex], ...changeValue, handleType };
        if (this.mounted) {
          this.setState({ [`${name}Data`]: tableData, sUseInfo: '' });
        }
      }
    };

    handleSendSocketMessage = (flag, showType, sId, sendTo, msgInfo, param) => {
      const { token } = this.props.app;
      const sendws = this.handleSendWebSocketMsg;
      const { dispatch } = this.props;
      if (commonUtils.isNotEmptyObject(token)) {
        if (this.props.app.webSocket !== null && this.props.app.webSocket.readyState === WebSocket.OPEN) {
          sendws(flag, showType, msgInfo, sId, sendTo, param);
        } else {
          this.props.dispatch({ type: 'app/createWebSocket', payload: { reStart: true, dispatch } });
          setTimeout(() => {
            console.log('====== reStart ======');
            sendws(flag, showType, msgInfo, sId, sendTo, param);
          }, 30000);
        }
      }
    };

    handleSendWebSocketMsg = (flag, showType, msgInfo, sId, sendTo, param) => {
      const { app } = this.props;
      const { webSocket, userinfo, currentPane } = app;
      const { key } = currentPane;
      commonFunc.sendWebSocketMessage(webSocket, key, flag, showType, userinfo.sId, msgInfo, sId, sendTo, param);
    }

    handleFilterDropDownData = (dropDownData, showConfig, name, record) => {
      if (!commonUtils.isEmptyArr(dropDownData)) {
        const conditon = showConfig.sSqlCondition.split(',');
        let orTableName;
        let orFieldName;
        let orFieldNameFilter;
        let orValue;
        conditon.forEach((item) => {
          if (item.indexOf('.') > -1) {
            const tableName = item.split('.')[0];
            const fieldName = item.split('.')[1];
            const fieldNameFilter = item.split('.')[2];
            if (tableName.indexOf('|') > -1) {
              orTableName = tableName.replace('|', '');
              orFieldName = fieldName;
              orFieldNameFilter = fieldNameFilter;
              if (orFieldName.indexOf('&') > -1) {
                orValue = orFieldName.replace('&', '');
              } else if (!commonUtils.isEmpty(orFieldNameFilter)) {
                if (name === orTableName && !commonUtils.isEmpty(record)) {
                  const data = record;
                  orValue = data[orFieldName];
                } else {
                  const data = this.state[`${orTableName}Data`];
                  const selectedRowKeys = this.state[`${orTableName}SelectedRowKeys`];
                  if (typeof data === 'object' && data.constructor === Object) {
                    orValue = data[orFieldName];
                  } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
                    const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]);
                    if (iIndex > -1) {
                      orValue = data[iIndex][orFieldName];
                    }
                  } else if (commonUtils.isNotEmptyArr(data)) {
                    orValue = data[0][orFieldName];
                  }
                }
              }
              orValue = orValue.toString();
            } else if (!commonUtils.isEmpty(orFieldName)) {
              // master.sId 作为参数   control.sId.sControlId 作为filterDropdown过滤参数
              if (!commonUtils.isEmpty(fieldNameFilter)) {
                if (name === tableName && !commonUtils.isEmpty(record)) {
                  const data = record;
                  dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName] || itemDrop[orFieldNameFilter] === orValue);
                } else {
                  const data = this.state[`${tableName}Data`];
                  const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
                  if (typeof data === 'object' && data.constructor === Object) {
                    dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName] || itemDrop[orFieldNameFilter] === orValue);
                  } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
                    const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]);
                    if (iIndex > -1) {
                      dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[iIndex][fieldName] || itemDrop[orFieldNameFilter] === orValue);
                    }
                  } else if (commonUtils.isNotEmptyArr(data)) {
                    dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[0][fieldName] || itemDrop[orFieldNameFilter] === orValue);
                  }
                }
              }
            } else if (!commonUtils.isEmpty(fieldNameFilter)) {
              if (name === tableName && !commonUtils.isEmpty(record)) {
                const data = record;
                dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName]);
              } else {
                const data = this.state[`${tableName}Data`];
                const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
                if (typeof data === 'object' && data.constructor === Object) {
                  dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName]);
                } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
                  const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]);
                  if (iIndex > -1) {
                    dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[iIndex][fieldName]);
                  }
                } else if (commonUtils.isNotEmptyArr(data)) {
                  dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[0][fieldName]);
                }
              }
            }
          }
        });
      }

      // let dropDownData = dropDownDataOld;
      // const data = this.state[`${tableName}Data`];
      // const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
      // if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
      //   const SelectedData = data.filter(item => item.sId === selectedRowKeys[0]);
      //   if (SelectedData.length > 0 && commonUtils.isNotEmptyStr(SelectedData[0][fieldName])) {
      //     if (commonUtils.isNotEmptyArr(dropDownData)) {
      //       dropDownData = dropDownData.filter(item => item[fieldName] === SelectedData[0][fieldName]);
      //     }
      //   }
      // }
      return dropDownData;
    };

    /* 增加通用的tmpInfobySql功能 */
    handleTmpInfoBySql = async (copyToConfig, sRowData, copyTo) => {
      const returnObj = commonUtils.isNotEmptyObject(copyTo) ? copyTo : {};
      const { token, sModelsId } = this.state;
      const sControlName = copyToConfig[0].sControlName;
      if (commonUtils.isNotEmptyObject(sControlName) && sControlName.toLowerCase().includes('tmpinfobysql')) { /* 根据配置下拉sql获取数据源 */
        const dataUrl = `${commonConfig.server_host}salesorder/getTmpInfoBySql/?sModelsId=${sModelsId}`;
        const sConfigformId = commonUtils.isEmpty(copyToConfig) ? '' : copyToConfig[0].sParentId;
        const sControlNameNew = commonUtils.isNotEmptyObject(sControlName) ? sControlName : 'BtnCopyTo.tmpInfoBySql';
        const values = { sConfigformId, sControlName: sControlNameNew, sRowData };
        const dataReturn = (await commonServices.postValueService(token, values, dataUrl)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows[0];
          if (commonUtils.isNotEmptyObject(returnData)) {
            for (const key of Object.keys(returnData)) {
              const sName = `${key}Data`;
              const masterName = sControlName.replace('BtnCopyTo.', '').trim();
              if (key === masterName) {
                returnObj.masterData = returnData[key][0];
              } else {
                returnObj[sName] = returnData[key];
              }
            }
            if (commonUtils.isNotEmptyArr(returnObj.masterData) && Array.isArray(returnObj.masterData)) {
              returnObj.masterData = returnObj.masterData[0];
            }
          }
        } else {
          this.getServiceError(dataReturn);
        }
      }
      return returnObj;
    }

    /**
     * 增加，删除, pda, copyto, onChange
     * @param {*} data
     * @param {*} isOutsourcedProcesses
     * @param {*} tabPage
     * @param {*} masterData
     * @returns
     */
    handleMasterDefaultData = (data, isOutsourcedProcesses, tabPage, masterData, {
      masterConfig, slaveChildConfig, slave0Config, slaveConfig,
    } = {}) => {
      let iTypeConfig = this.state.slaveChildConfig || slaveChildConfig;
      const config = this.state.masterConfig || masterConfig;
      if (config) {
        const value = config.gdsconfigformslave?.find(i => i &&
          ((['sDefaultQty'].includes(i.sName) && !isOutsourcedProcesses) ||
          (isOutsourcedProcesses && ['sDefaultSlaveChild', 'sDefaultSlave0'].includes(i.sName))));
        if (!value) return masterData;
      } else {
        return masterData;
      }

      let sDefaultQty = 'sDefaultQty';
      let sSlaveLength = 'sSlaveLength';
      // 外发区分配置
      if (isOutsourcedProcesses) {
        iTypeConfig = ({
          1: slave0Config || this.state.slave0Config,
        }[tabPage]) || slaveConfig || this.state.slaveConfig;

        sDefaultQty = {
          0: 'sDefaultSlaveChild',
          1: 'sDefaultSlave0',
        }[tabPage] || 'sDefaultSlave';
        sSlaveLength = {
          0: 'sSlaveLengthSlaveChild',
          1: 'sSlaveLengthSlave0',
        }[tabPage] || 'sSlaveLengthSlave';
      } else if (typeof tabPage === 'undefined') {
        if (!commonUtils.isNotEmptyObject(this.state.slaveChildConfig || slaveChildConfig)) {
          iTypeConfig = slaveConfig;
        }
      }

      const hasiType = iTypeConfig?.gdsconfigformslave?.find(item => ['itype', 'iType'].includes(item?.sName));
      const iType = hasiType?.sDefault;
      const type = iType !== undefined ? iType : 11;
      let name = 'dAuxiliaryQty';
      if (['10', '12'].includes(type)) {
        name = 'dProductQty';
      }

      const result = data.reduce((a, b) => {
        return addResult(a, (Number(b?.[name]) || 0));
      }, 0);

      return {
        ...masterData || {},
        [sSlaveLength]: data.length,
        [sDefaultQty]: result,
      };
    }

    render() {
      return (
        <ChildComponent
          style={{ height: '100%' }}
          {...this.props}
          {...this.state}
          getSqlDropDownData={this.getSqlDropDownData}
          getSqlCondition={this.getSqlCondition}
          getServiceError={this.getServiceError}
          onDataRowAdd={this.handleTableAdd}
          getFloatNum={this.getFloatNum}
          getDateFormat={this.getDateFormat}
          handleGetDataOne={this.handleGetDataOne}
          handleGetDataSet={this.handleGetDataSet}
          onSaveState={this.handleSaveState}
          onChange={this.handleMasterChange}
          onDataChange={this.handleTableChange}
          handleSendSocketMessage={this.handleSendSocketMessage}
          onFilterDropDownData={this.handleFilterDropDownData}
          onTmpInfoBySql={this.handleTmpInfoBySql}
          handleMasterDefaultData={this.handleMasterDefaultData}
        />
      );
    }
  };
};
