/* eslint-disable no-mixed-operators,function-paren-newline,no-eval,radix */
import moment from 'moment';
import lodash from 'lodash';
import * as commonUtils from '@/utils/utils';
import config from '@/utils/config';
import React from 'react';

/* 根据控件名 通过配置 得到是否显示与是否有权限 */
// type control, field 控件、字段
// name 名称
// config 单表配置数据
// gdsformconst 未配置值时取常量
// gdsjurisdiction 看是否有权限功能
// sDefault 默认中文 可不传.
export function getConfig(type, name, config, gdsformconst, gdsjurisdiction, sDefault) {
  let returnConfig = {};
  returnConfig.bVisible = true;
  if (config !== undefined) {
    let nameConfig;
    if (type === 'control') {
      nameConfig = config.findIndex(item => item.sControlName === name) > -1 ? config.filter(item => item.sControlName === name)[0] : returnConfig;
    } else {
      nameConfig = config.findIndex(item => item.sName === name) > -1 ? config.filter(item => item.sName === name)[0] : returnConfig;
    }
    if (Object.keys(nameConfig).length > 0) {
      returnConfig = nameConfig;
    }
  }
  if (!(returnConfig.showName !== undefined && returnConfig.showName !== '')) {
    const nameConst = gdsformconst.findIndex(item => item.sName === name) > -1 ? gdsformconst.filter(item => item.sName === name)[0] : {};
    if (Object.keys(nameConst).length > 0) {
      returnConfig.showName = nameConst.showName;
    } else {
      returnConfig.showName = sDefault;
    }
  }
  /* const nameJurisdiction = gdsjurisdiction.findIndex(
   item => item.sName === name) > -1 ? gdsjurisdiction.filter(
   item => item.sName === name)[0] : {};
   if (Object.keys(nameJurisdiction).length > 0) {
   config.bVisible = config.bVisible && nameJurisdiction.bVisible;
   } */
  return returnConfig;
}

export function getDateFormat(systemData) {
  const iIndex = systemData.findIndex(item => (item.sName === 'CbxDateTime'));
  const sCbxDateTime = iIndex > -1 ?
    systemData[iIndex].sValue === '1' ? 'YYYY-MM-DD HH:mm:ss' :
      systemData[iIndex].sValue === '2' ? 'YYYY-MM-DD' :
        systemData[iIndex].sValue === '3' ? 'HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss';
  const sReturn = commonUtils.isEmpty(sCbxDateTime) ? 'YYYY-MM-DD HH:mm:ss' : sCbxDateTime;
  return sReturn;
}

/** 结算日期计算 */
export function getGeyPayDate(data, mainData, dateFormat, sType, value) {
  const sGetPayTypeData = data.filter(item => item.key === 'sGetPayType');
  const { tCreateDate } = mainData;
  const tDeliverDate = sType === 'deliver' ? value.tDeliverDate : mainData.tDeliverDate;
  const tCreateDateValue = tCreateDate !== undefined && tCreateDate !== null ? moment(tCreateDate).format(dateFormat) : moment().format(dateFormat);
  const tDeliverDateValue = tDeliverDate !== undefined && tDeliverDate !== null ? moment(tDeliverDate).format(dateFormat) : tCreateDateValue;
  if (sGetPayTypeData.length > 0) {
    const sGetPayType = sGetPayTypeData[0].value;
    if (sGetPayType === 'now') {
      mainData.tGetPayDate = tCreateDateValue;
    } else if (sGetPayType === 'month') {
      const iMonth = data.filter(item => item.key === 'iMonth')[0].value;
      const iDay = data.filter(item => item.key === 'iDay')[0].value;
      const tCreateValue = moment(tCreateDate).set('date', iDay);
      if (iMonth === '0') {
        const tCurrentDay = moment(tCreateDate).get('date');
        if (tCurrentDay < iDay) {
          mainData.tGetPayDate = moment(tCreateValue).format(dateFormat);
        } else {
          mainData.tGetPayDate = moment(tCreateValue).add(1, 'months').format(dateFormat);
        }
      } else {
        mainData.tGetPayDate = moment(tCreateValue).add(iMonth, 'months').format(dateFormat);
      }
    } else if (sGetPayType === 'deliver') {
      const iAfterDeliverDay = data.filter(item => item.key === 'iAfterDeliverDay')[0].value;
      mainData.tGetPayDate = moment(tDeliverDateValue).add(iAfterDeliverDay, 'days').format(dateFormat);
    }
  }
  return mainData;
}


// ----------------------新记录-------------------------------------------------------------------------
/** 根据表配置获取表头 */
export function getHeaderConfig(config) {
  const tableConfig = config.gdsconfigformslave;
  const column = [];
  for (const child of tableConfig) {
    if (child.sName !== '' && child.bVisible && child.showName !== '') {
      column.push({
        title: child.showName,
        dataIndex: child.sName.trim(),
        width: child.iFitWidth,
        bFind: child.bFind,
        bNotEmpty: child.bNotEmpty, /* 设置表格必填项*号 */
        sTitleBgColor: child.sFontBgColor, /* 设置表格标题背景颜色 */
        sTitleColor: child.sFontColor, /* 设置表格标题字体颜色 */
        bCheckBox: child.bCheckBox, /* 是否支持表头多选 */
        bReadonly: child.bReadonly, /* 是否只读 */
      });
    }
  }
  return column;
}


/** 把主表字段绑定要相应的控件上 */
export function mapPropsToFields(masterData, form, masterConfig) {
  const result = {};
  if (commonUtils.isNotEmptyObject(masterData)) {
    Object.keys(masterData).forEach((child) => {
      const firstKey = child.substring(0, 1);
      if (firstKey === 'c') {
        const value = commonUtils.isUndefined(masterData[child]) ? [] : typeof masterData[child] === 'string' ?
          masterData[child].split(',') : commonUtils.convertUndefinedToEmptyArr(masterData[child]);
        result[child] = form.createFormField({ value });
      } else if (!['t', 'm'].includes(firstKey)) {
        let value = masterData[child];
        if (commonUtils.isNotEmptyObject(masterConfig)) {
          const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === child && item.bMultipleChoice);
          if (iIndex > -1 && typeof masterData[child] === 'string' && !commonUtils.isEmpty(masterData[child])) {
            value = masterData[child].split(',');
          } else if (iIndex > -1 && masterData[child] === '') {
            /** 当多选下拉为空时 */
            value = [];
          }
        }
        // eslint-disable-next-line no-self-compare
        if (typeof value === 'number' && value !== value) {
          value = undefined;
        }
        result[child] = form.createFormField({ value });
      } else {
        const dateFormat = firstKey === 'm' ? 'YYYY-MM' : 'YYYY-MM-DD HH:mm:ss';
        /* 日期控件显示格式 */
        const value = masterData[child] !== null && masterData[child] !== undefined ? moment(masterData[child], dateFormat) : null;
        result[child] = form.createFormField({ value });
      }
    });
  }
  return result;
}

/**
 * 处理用户信息
 */
const handleDefaultSName = (itemConfig) => {
  const { sControlName, sDefault, sName } = itemConfig || {};
  const key = sControlName?.split('-')?.[1];
  if (!key || sDefault) return false;
  try {
    let userinfo = localStorage.getItem(`${config.prefix}userinfo`);
    userinfo = JSON.parse(userinfo);
    const userinfoKey = Object.keys(userinfo);
    if (userinfoKey.includes(key)) {
      if (sName?.substring(0, 1) === 't') {
        return moment(userinfo[key]);
      }
      return userinfo[key];
    }
  } catch (error) {
    return false;
  }
  return false;
};

/** 获取数据默认值  取消其他表值数据时  sTaxId:master.sTaxId */
export function getDefaultData(config, allTableData = {}, extraData = {}) {
  const { newSid } = extraData;
  const returnData = {};
  if (commonUtils.isNotEmptyObject(config) && commonUtils.isNotEmptyObject(config.gdsconfigformslave)) {
    config.gdsconfigformslave.forEach((childConfig) => {
      const { sDefault, sName } = childConfig;
      if (typeof sDefault === 'string' && sDefault !== '' && sName && sDefault !== undefined && sDefault.indexOf(':') > -1 && sDefault.indexOf('.') > -1) {
        const oldFieldName = sDefault.split(':')[1];
        const tableName = oldFieldName.split('.')[0];
        if (sDefault && sDefault.includes('Fx')) { /* 默认值支持自定义函数 */
          let result = '';
          const indexOf = tableName.indexOf('(');
          const tbName = tableName.substring(indexOf + 1, tableName.length);
          const fxName = oldFieldName.replace('Fx_', '').trim();
          const tableData = allTableData[tbName];
          const tbField1 = fxName.substring(fxName.indexOf('.') + 1, fxName.indexOf(',')).trim(); /* 第一个参数名称: master.[字段] */
          const tbField2 = fxName.substring(fxName.indexOf(',') + 1, fxName.indexOf(')')).trim(); /* 第二个参数名称: 格式YYYY-MM-DD */
          let tbFieldValue1 = '';
          if (!Array.isArray(tableData)) {
            tbFieldValue1 = tableData[tbField1];
          }
          if (sDefault.includes('getDate')) {
            result = commonUtils.getDate(tbFieldValue1, tbField2);
          }
          returnData[sName] = result;
          return returnData;
        }
        const oldTableFieldName = oldFieldName.split('.')[1];
        if (oldTableFieldName === 'sId' && newSid) {
          returnData[sName] = newSid;
        } else if (!commonUtils.isEmptyObject(allTableData[tableName])) {
          if (oldFieldName.includes('+') || oldFieldName.includes('-') || oldFieldName.includes('*') ||
            oldFieldName.includes('/') || oldFieldName.includes('(') || oldFieldName.includes(')')) {
            let sFormula = oldFieldName;
            let sFormulaSplit = oldFieldName;
            sFormulaSplit = sFormulaSplit.split('+').join('$');
            sFormulaSplit = sFormulaSplit.split('-').join('$');
            sFormulaSplit = sFormulaSplit.split('*').join('$');
            sFormulaSplit = sFormulaSplit.split('/').join('$');
            sFormulaSplit = sFormulaSplit.split('(').join('$');
            sFormulaSplit = sFormulaSplit.split(')').join('$');
            sFormulaSplit.split('$').forEach((oldFieldNameItem) => {
              const oldFieldItem = oldFieldNameItem.trim();
              if (oldFieldItem.indexOf('.') > -1) {
                const tableName = oldFieldItem.split('.')[0].trim();
                const oldTableFieldName = oldFieldItem.split('.')[1].trim();
                if (!commonUtils.isEmptyObject(allTableData[tableName]) && allTableData[tableName][oldTableFieldName] !== undefined) {
                  sFormula = sFormula.replace(oldFieldItem, allTableData[tableName][oldTableFieldName]);
                }
              } else {
                const oldTableFieldName = oldFieldItem.trim();
                if (allTableData[tableName][oldTableFieldName] !== undefined) {
                  sFormula = sFormula.replace(oldTableFieldName, `(${allTableData[tableName][oldTableFieldName]})`); /* 加括号处理当值为负数时的异常 */
                }
              }
            });
            returnData[sName] = oldTableFieldName.substring(0, 1) === '&' ? sFormula.split('+').join('') : commonUtils.convertFixNum(eval(sFormula), 6);
          } else if (sDefault.split(',').length > 1 && sDefault.split(':').length > 1) {
            sDefault.split(',').forEach(item => {
              const oldFieldName = item.split(':')[1];
              const [tableName, oldTableFieldName] = oldFieldName.split('.');
              const newFieldName = item.split(':')[0];
              returnData[newFieldName] = allTableData[tableName][oldTableFieldName];
            });
          } else {
            returnData[sName] = allTableData[tableName][oldTableFieldName];
          }
        }
      } else if (sName && sDefault !== '' && sDefault !== undefined) {
        if (sName.substring(0, 1) === 'b') {
          returnData[sName] = commonUtils.converNumStrToBoolean(sDefault);
        } else if (sName.substring(0, 1) === 't' && (sDefault === 'today' || sDefault === 'now')) {
          if (sDefault === 'now') {
            returnData[sName] = moment().format('YYYY-MM-DD HH:mm:ss');
          } else {
            returnData[sName] = moment().format('YYYY-MM-DD');
          }
        } else if (sName.substring(0, 1) === 'i') {
          returnData[sName] = parseInt(sDefault);
        } else if (sName.substring(0, 1) === 'd') {
          returnData[sName] = parseFloat(sDefault);
        } else if (sDefault === '&+') {
          returnData[sName] = '';
        } else {
          returnData[sName] = sDefault;
        }
      } else if (sName) {
        const value = handleDefaultSName(childConfig);
        if (value) {
          returnData[sName] = value;
        }
      }
    });
  }
  return returnData;
}

export function clearJsonStringFields(obj, excludeFields = []) {
  if (!commonUtils.isNotEmptyObject(obj)) {
    return obj;
  }
  
  const processedObj = lodash.cloneDeep(obj);
  
  Object.keys(processedObj).forEach(key => {
    // 跳过排除字段
    if (excludeFields.includes(key)) {
      return;
    }
    
    const value = processedObj[key];
    
    // 智能检测JSON字符串
    if (typeof value === 'string' && commonUtils.isJSON(value)) {
      processedObj[key] = '';
    }
  });
  
  return processedObj;
}


/** 获取数据默认值 */
export function getAssignFieldValue(sAssignField, srcData, allTableData = {}, bMultiTable, bCrossTable, tableNames) {
  const returnData = {};
  if (!commonUtils.isEmpty(sAssignField)) {
    /* 赋值数组 */
    const sAssignFieldObj = sAssignField.split(',');
    if (commonUtils.isNotEmptyObject(srcData)) {
      let strVar = '';
      if (sAssignField && sAssignField.includes('var') && bCrossTable) {
        console.log('sAssignFiel:d', sAssignField);
        if (sAssignField.includes('slave.') || sAssignField.includes('slave.') || sAssignField.includes('control.')
          || sAssignField.includes('materials.') || sAssignField.includes('process.') || sAssignField.includes('master.')) { /* var表格对象 */
          // 第一步：统一转为key数组（核心优化）
          const allKeys = Object.keys(allTableData); // 先拿到原对象所有key
          const matchedKeys = commonUtils.isNotEmptyArr(tableNames)
            ? allKeys.filter(key => tableNames.includes(key)) // 筛选匹配的key
            : allKeys; // 未筛选时直接用所有key

          for (const row of matchedKeys) {
            const srcData = allTableData[row];
            const srcNewData = clearJsonStringFields(srcData);
            const field = `var ${row}=${JSON.stringify(srcNewData)};`;
            strVar += field;
          }
        }
        for (const key of Object.keys(srcData)) {
          if (srcData[key] !== undefined || srcData[key] || srcData[key] === 0 || typeof srcData[key] === 'boolean') {
            let varValue = srcData[key];
            const firstDataIndex = key.substring(0, 1);
            let field = '';
            if (firstDataIndex === 's' || firstDataIndex === 't' || firstDataIndex === 'h' || key === 'maxBillNo') {
              if (commonUtils.isNotEmptyObject(varValue) && typeof varValue === 'string') {
                varValue = varValue.replace(/'/mg, '');
                varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
              }
              varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
              field = `var ${key}='${varValue}';`;
            } else {
              let finalValue = varValue;
              // 1. 先判断类型：非数字类型且无法转为数字 → 设为0
              if (typeof finalValue !== 'number' && isNaN(Number(finalValue))) {
                finalValue = 0;
              }
              // 2. 处理特殊异常值（NaN/undefined/"NaN"）
              else if (finalValue === 'NaN' || finalValue === undefined || Number.isNaN(finalValue)) {
                finalValue = 0;
              }
              // 3. 空对象特殊处理（仅当值是对象且为空时设为0）
              else if (typeof finalValue === 'object' && finalValue !== null && commonUtils.isEmptyObject(finalValue)) {
                finalValue = 0;
              }
              // 4. 合法数字（包括0/222等）保留原值
              field = `var ${key}=${finalValue};`;
            }
            strVar += field;
          }
        }
      } else if (sAssignField && sAssignField.includes('var') && !bMultiTable) {
        if (sAssignField.includes('master.')) { /* var表格对象 */
          for (const row of Object.keys(allTableData)) {
            if (row === 'master') {
              const srcData = allTableData[row];
              const field = `var ${row}=${JSON.stringify(srcData)};`;
              strVar += field;
            }
          }
        }
        for (const key of Object.keys(srcData)) {
          if (srcData[key] !== undefined || srcData[key] || srcData[key] === 0 || typeof srcData[key] === 'boolean') {
            let varValue = srcData[key];
            const firstDataIndex = key.substring(0, 1);
            let field = '';
            if (firstDataIndex === 's' || firstDataIndex === 't' || firstDataIndex === 'h' || key === 'maxBillNo') {
              if (commonUtils.isNotEmptyObject(varValue) && typeof varValue === 'string') {
                varValue = varValue.replace(/'/mg, '');
                varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
              }
              varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
              field = `var ${key}='${varValue}';`;
            } else {
              varValue = varValue === 'NaN' || isNaN(varValue) || varValue === undefined ? 0 : varValue;
              field = `var ${key}=${varValue};`;
            }

            strVar += field;
          }
        }
      } else if (sAssignField && sAssignField.includes('var') && bMultiTable) {
        for (const row of Object.keys(allTableData)) {
          if (sAssignField.includes(`${row}.`)) {
            const srcData = allTableData[row];
            const field = `var ${row}=${JSON.stringify(srcData)};`;
            strVar += field;
          }
          const srcData = allTableData[row];
          for (const key of Object.keys(srcData)) {
            if (srcData[key] !== undefined || srcData[key] || srcData[key] === 0 || typeof srcData[key] === 'boolean') {
              let varValue = srcData[key];
              const firstDataIndex = key.substring(0, 1);
              let field = '';
              if (firstDataIndex === 's' || firstDataIndex === 't' || firstDataIndex === 'h' || key === 'maxBillNo') {
                if (commonUtils.isNotEmptyObject(varValue) && typeof varValue === 'string') {
                  varValue = varValue.replace(/'/mg, '');
                  varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
                }
                varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;
                field = `var ${key}='${varValue}';`;
              } else {
                varValue = varValue === 'NaN' || isNaN(varValue) || varValue === undefined ? 0 : varValue;
                field = `var ${key}=${varValue};`;
              }
              strVar += field;
            }
          }
        }
      }
      if (commonUtils.isNotEmptyObject(strVar)) {
        strVar = strVar.replace(/\n/mg, ' '); /* 去除换行 */
        strVar = strVar.replace(/\\/mg, ' '); /* 去除\ */
      }
      sAssignFieldObj.forEach((item) => {
        if (item.indexOf(':') > -1) {
          const newFieldName = item.split(':')[0].trim();
          const oldFieldNameTmp = item.split(':')[1].trim();
          const oldFieldName = oldFieldNameTmp.substring(0, 1) === '&' ? oldFieldNameTmp.substring(1, oldFieldNameTmp.length).trim() : oldFieldNameTmp.trim();
          if (oldFieldName.includes('+') || oldFieldName.includes('-') || oldFieldName.includes('*') ||
            oldFieldName.includes('/') || oldFieldName.includes('(') || oldFieldName.includes(')') || oldFieldName.includes('%')) {
            let sFormula = oldFieldName.trim();
            let sFormulaSplit = oldFieldName.trim();
            sFormulaSplit = sFormulaSplit.split('+').join('$');
            sFormulaSplit = sFormulaSplit.split('-').join('$');
            sFormulaSplit = sFormulaSplit.split('*').join('$');
            sFormulaSplit = sFormulaSplit.split('/').join('$');
            sFormulaSplit = sFormulaSplit.split('(').join('$');
            sFormulaSplit = sFormulaSplit.split(')').join('$');
            sFormulaSplit = sFormulaSplit.split('%').join('$');
            if (commonUtils.isNotEmptyObject(strVar)) { /* 声明srcData中变量 */
              sFormula = sFormula.replace(/#/g, ':');
              sFormula = strVar + sFormula;
            } else {
              sFormulaSplit.split('$').forEach((oldFieldNameItem) => {
                const oldFieldItem = oldFieldNameItem.trim();
                if (oldFieldItem.indexOf('.') > -1) {
                  const tableName = oldFieldItem.split('.')[0].trim();
                  const oldTableFieldName = oldFieldItem.split('.')[1].trim();
                  if (commonUtils.isNotEmptyObject(allTableData) && !commonUtils.isEmptyObject(allTableData[tableName]) && allTableData[tableName][oldTableFieldName] !== undefined) {
                    sFormula = sFormula.replace(oldFieldItem, allTableData[tableName][oldTableFieldName]);
                  }
                } else {
                  const oldTableFieldName = oldFieldItem.trim();
                  if (srcData[oldTableFieldName] !== undefined) {
                    sFormula = sFormula.replace(oldTableFieldName, `(${srcData[oldTableFieldName]})`); /* 加括号处理当值为负数时的异常 */
                  } else if (oldTableFieldName.substring(0, 1).toLowerCase() === 'd') {
                    sFormula = sFormula.replace(oldTableFieldName, 0); /* 处理字段值为空时异常 */
                  }
                }
              });
            }
            try {
              let res = '';
              if (oldFieldNameTmp.substring(0, 1) === '&') {
                res = sFormula.split('+').join('');
              } else if (typeof res === 'string' && newFieldName.substring(0, 1).toLowerCase() !== 'd') {
                res = eval(sFormula);
              } else {
                res = commonUtils.convertFixNum(eval(sFormula), 6);
              }
              res = res === 'NaN' ? '' : res;
              returnData[newFieldName] = res;
              // returnData[newFieldName] = oldFieldNameTmp.substring(0, 1) === '&' ? sFormula.split('+').join('') : commonUtils.convertFixNum(eval(sFormula), 6);
              // srcData[newFieldName] = returnData[newFieldName];
              const firstDataIndex = newFieldName.substring(0, 1);
              if (firstDataIndex === 't') {
                if (!sFormula.includes('var')) {
                  if (returnData[newFieldName] && returnData[newFieldName].includes(':')) {
                    returnData[newFieldName] = moment(returnData[newFieldName]).format('YYYY-MM-DD HH:mm:ss');
                  } else {
                    returnData[newFieldName] = moment(returnData[newFieldName]).format('YYYY-MM-DD');
                  }
                }
              }
              console.log('运算结果为：', res);
            } catch (e) {
              console.log('逻辑表达式1：', sFormula);
              console.log('逻辑表达式报错！', e.messages);
              returnData[newFieldName] = 0;
            }
          } else if (oldFieldName.indexOf('.') > -1) {
            const tableName = oldFieldName.split('.')[0].trim();
            const oldTableFieldName = oldFieldName.split('.')[1].trim();
            if (!commonUtils.isEmptyObject(allTableData[tableName]) && allTableData[tableName][oldTableFieldName] !== undefined && allTableData[tableName][oldTableFieldName] !== null) {
              if (newFieldName.substring(0, 1) === 't') {
                if (allTableData[tableName][oldTableFieldName] && allTableData[tableName][oldTableFieldName].includes(':')) {
                  returnData[newFieldName] = moment(allTableData[tableName][oldTableFieldName]).format('YYYY-MM-DD HH:mm:ss');
                } else {
                  returnData[newFieldName] = moment(allTableData[tableName][oldTableFieldName]).format('YYYY-MM-DD');
                }
              } else if (newFieldName.substring(0, 1) === 'i') {
                returnData[newFieldName] = parseInt(allTableData[tableName][oldTableFieldName]);
              } else if (newFieldName.substring(0, 1) === 'd') {
                returnData[newFieldName] = parseFloat(allTableData[tableName][oldTableFieldName]);
              } else {
                returnData[newFieldName] = allTableData[tableName][oldTableFieldName];
              }
            }
          } else if (srcData[oldFieldName] !== undefined && srcData[oldFieldName] !== null) {
            if (newFieldName.substring(0, 1) === 't') {
              if (srcData[oldFieldName] && srcData[oldFieldName].includes(':')) {
                returnData[newFieldName] = moment(srcData[oldFieldName]).format('YYYY-MM-DD HH:mm:ss');
              } else {
                returnData[newFieldName] = moment(srcData[oldFieldName]).format('YYYY-MM-DD');
              }
            } else if (newFieldName.substring(0, 1) === 'i') {
              returnData[newFieldName] = parseInt(srcData[oldFieldName]);
            } else if (newFieldName.substring(0, 1) === 'd') {
              returnData[newFieldName] = parseFloat(srcData[oldFieldName]);
            } else {
              returnData[newFieldName] = srcData[oldFieldName];
            }
          }
        }
      });
    }
  }
  return returnData;
}

export function getAssignFieldV2(sAssignField, srcData) {
  if (commonUtils.isEmpty(sAssignField)) return '';

  if (!commonUtils.isNotEmptyObject(srcData)) return '';

  let strVar = '';
  if (sAssignField && sAssignField.includes('var')) {
    for (const key of Object.keys(srcData)) {
      if (srcData[key] !== undefined || srcData[key] === 0) {
        let varValue = srcData[key];
        const firstDataIndex = key.substring(0, 1);
        let field = '';
        if (firstDataIndex === 's' || firstDataIndex === 't' || firstDataIndex === 'h' || key === 'maxBillNo') {
          varValue = varValue === 'NaN' || varValue === undefined ? '' : varValue;

          field = `var ${key}='${varValue}';`;
        } else {
          varValue = varValue === 'NaN' || isNaN(varValue) || varValue === undefined ? 0 : varValue;
          field = `var ${key}=${varValue};`;
        }
        strVar += field;
      }
    }
  }
  if (commonUtils.isNotEmptyObject(strVar)) {
    strVar = strVar.replace(/\n/mg, ' '); /* 去除换行 */
    strVar = strVar.replace(/\t/mg, ' '); /* 去除换行 */
  }

  if (commonUtils.isNotEmptyObject(sAssignField)) {
    sAssignField = sAssignField.replace(/\n/mg, ' '); /* 去除换行 */
    sAssignField = sAssignField.replace(/\t/mg, ' '); /* 去除换行 */
  }

  try {
    return eval(strVar + sAssignField);
  } catch (e) {
    console.log('=====逻辑表达式报错！', {
      e, strVar, sAssignField,
    });
  }
}
/** 获取数据默认值 */
export function getFilterConditon(sAssignField, allTableData) {
  const returnData = {};
  let strVar = '';
  if (!commonUtils.isEmpty(sAssignField)) {
    /* 赋值数组 */
    if (commonUtils.isNotEmptyObject(allTableData)) {
      if (sAssignField && sAssignField.includes('var')) {
        for (const row of Object.keys(allTableData)) {
          const srcData = allTableData[row];
          const srcNewData = lodash.cloneDeep(srcData);
          if (srcNewData.sCombinedMemo) {
            srcNewData.sCombinedMemo = '';
          }
          if (srcNewData.sPositiveColor) {
            srcNewData.sPositiveColor = '';
          }
          const field = `var ${row}=${JSON.stringify(srcNewData)};`;
          strVar += field;
        }
      }
    }
    if (commonUtils.isNotEmptyObject(strVar)) {
      strVar = strVar.replace(/\n/mg, ' '); /* 去除换行 */
      strVar = strVar.replace(/\\/mg, ' '); /* 去除\ */
    }
    let sFormula = '';
    if (commonUtils.isNotEmptyObject(strVar)) { /* 声明srcData中变量 */
      sFormula = sFormula.replace(/#/g, ':');
      sFormula = strVar + sFormula;
    }
    sFormula = `${sFormula + sAssignField}; s`;
    try {
      let res = '';
      if (typeof res === 'string') {
        res = eval(sFormula);
      } else {
        res = commonUtils.convertFixNum(eval(sFormula), 6);
      }
      return res;
    } catch (e) {
      console.log('逻辑表达式报错！', e);
    }
  }
  return returnData;
}
export function showLocalMessage(props, sName, sChineseName) {
  let sTitle = '';
  if(commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(props.app) && commonUtils.isNotEmptyArr(props.app.commonConst)) {
    const gdsformconst = props.app.commonConst;
    sTitle = showMessage(gdsformconst, sName)
  } else {
    sTitle = sChineseName;
  }
  if (sTitle === '') {
    sTitle = sChineseName
  }
  return sTitle;
}
/** 获取常量数据 */
export function showMessage(gdsformconst, sName) {
  const iIndex = gdsformconst.findIndex(item => item.sName === sName);
  if (iIndex > -1) {
    return gdsformconst[iIndex].showName;
  }
  return '';
}

export function getReturnMsg(str) {
  const msgArr = commonUtils.isNotEmptyObject(str) ? str.split('xpm') : '';
  const divStr = [];
  if (commonUtils.isNotEmptyArr(msgArr)) {
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < msgArr.length; i++) {
      divStr.push(<p>{msgArr[i]}</p>);
    }
  }
  return divStr;
}

/** 获取配置showName1 */
export function getConfigShowName(config, sName) {
  const iIndex = config.gdsconfigformslave.findIndex(item => item.sName === sName);
  if (iIndex > -1) {
    return config.gdsconfigformslave[iIndex].showName;
  }
  return '';
}

/* 根据配置取到 快捷过滤的字段 */
export function getConfigFieldNameData(config, sFieldName) {
  const allFilterConfig = [];
  const filterConfig = config.gdsconfigformslave.filter(item => (item.sName !== '' && item[sFieldName] && item.showName !== ''));
  allFilterConfig.push(...filterConfig);
  // let proConditionfilterConfig = {};
  // proConditionfilterConfig = config.gdsconfigformslave.filter(item => (item.sName !== '' && item.sName.indexOf('_pro') > -1 && item.bFind));
  // if (commonUtils.isNotEmptyObject(proConditionfilterConfig) && proConditionfilterConfig.length > 0) {
  //   allFilterConfig.push(...proConditionfilterConfig);
  // }
  return allFilterConfig;
}

/** 获取系统设定的值 */
export function getSystemSettingValue(sName) {
  // const systemSettings = commonUtils.getSystemSettings();
  // const iIndex = systemSettings.findIndex(item => item.sName === sName);
  // if (iIndex > -1) {
  //   return systemSettings[iIndex].sValue;
  // }
  return '';
}

export function getImitateGdsconfigTypes(showName, sControlName, sName, bNotEmpty, sDropDownType, showDropDown, upload) {
  const returnTypes = {
    bCanInput: false,
    bFilter: false,
    bFind: false,
    bFirstEmpty: false,
    bIsOther: false,
    bNewRecord: false,
    bNotEmpty: false,
    bNotRepeat: false,
    bReadonly: false,
    bSum: false,
    bTree: false,
    bVisible: true,
    iColValue: 1,
    iFitWidth: 120,
    iIncrement: 25502,
    iOrder: 0,
    iTag: 0,
    iVisCount: 0,
    sActiveKey: '',
    sAssignField: '',
    sBig5: '',
    sBig5DropDown: '',
    sBrandsId: '1111111111',
    sChinese: showName,
    sChineseDropDown: '',
    sControlName,
    sDefault: '',
    sDropDownType,
    sEnglish: '',
    sEnglishDropDown: '',
    sFilterSql: '',
    sId: commonUtils.createSid(),
    sKeyUpFilter: '',
    sMaxValue: '',
    sMinValue: '',
    sName: sName === undefined ? '' : sName,
    sNotRepeatColumn: '',
    sParentId: '19211681019715560848632490',
    sRelation: '',
    sSelectRelation: '',
    sSqlCondition: '',
    sSubsidiaryId: '1111111111',
    showDropDown,
    showName,
    needUpload: upload, // 选择的同时并上传 默认不上传 false， true表示上传
  };
  return returnTypes;
}

export function onWebSocketClose(ws, restart, wsUrl) {
  let newWs = null;
  if (ws !== null && ws !== undefined) {
    ws.close();
    ws.onclose = function (e) {
      console.log('关闭了 webscoket 服务端了', e);
      if (restart) {
        newWs = new WebSocket(wsUrl);
      }
    };
  }
  return newWs;
}

export function sendWebSocketMessage(ws, key, flag, showType, currUserId, msgInfo, sId, sendTo, param) {
  if (ws !== null && ws !== undefined) {
    // const d = { userIds: '19211681019715435405071690,15565055340009061165063169802000' };
    const arr = commonUtils.isNotEmptyObject(sId) ? sId.split(',') : [];
    const num = 1000;
    if (sId && arr.length > num) {
      const message = { ...param }; // param 存放其它参数  keyName 需要放入Redis的数据key,keyValue 需要放入Redis的数据key 的值
      message.key = key; // 操作tab页 key
      message.flag = flag; // 目前主要操作有：update 对数据进行更新，release：释放对某条数据的操作限制，loginOut：账号退出，清除所有操作限制 copyClear: 复制清空 sendMsg
      message.sendFrom = currUserId; // 消息发送人
      message.sendTo = sendTo; // 消息接收人
      message.msg = msgInfo;
      message.sId = sId; // 操作数据主表数据ID
      message.showType = showType;
      let sAllId = sId;
      const loop = Math.ceil(arr.length / num);
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < loop; i++) {
        const start = i * num;
        let end = num;
        if (i === (loop.length - 1)) {
          end = arr.length - 1;
        } else {
          end = (i + 1) * num;
        }
        sAllId = arr.slice(start, end).toString();
        if (sAllId !== '') {
          const sSendId = sAllId;
          message.sId = sSendId;
          sAllId = sAllId.replace(sSendId, '');
          message.sendStage = 'stageType';
          message.sendType = sAllId !== '' ? 'stage' : 'stageEnd';
          ws.send(JSON.stringify(message));
        }
      }
    } else {
      const message = { ...param }; // param 存放其它参数  keyName 需要放入Redis的数据key,keyValue 需要放入Redis的数据key 的值
      message.key = key; // 操作tab页 key
      message.flag = flag; // 目前主要操作有：update 对数据进行更新，release：释放对某条数据的操作限制，loginOut：账号退出，清除所有操作限制 copyClear: 复制清空 sendMsg
      message.sendFrom = currUserId; // 消息发送人
      message.sendTo = sendTo; // 消息接收人
      message.msg = msgInfo;
      message.sId = sId; // 操作数据主表数据ID
      message.showType = showType;
      ws.send(JSON.stringify(message));
    }
  }
}

// 获取props中所有表数据
export function getAllTableData(props) {
  const allTableData = {};
  Object.keys(props)
    .filter((key) => {
      if (!key) return false;
      const bEndWithConfig = key.endsWith('Config');
      if (!bEndWithConfig) return false;
      const config = props[key];
      return commonUtils.isNotEmptyArr(config) && config.gdsconfigformslave;
    })
    .forEach((key) => {
      const tableName = key.substring(0, key.length - 6);
      allTableData[tableName] = props[`${tableName}Data`];
    });
  return allTableData;
}

// 获取props中所有选中数据
export function getAllTableSelectedData(props) {
  const allTableData = getAllTableData(props);
  return Object.keys(allTableData).reduce((result, tableName) => {
    const tableData = allTableData[tableName];
    if (!Array.isArray(tableData)) {
      result = {
        ...result,
        [tableName]: tableData,
      };
    } else {
      const { [`${tableName}SelectedRowKeys`]: selectedRowKeys = [] } = props;
      result = {
        ...result,
        [tableName]: tableData.filter(item => selectedRowKeys.includes(item.sSlaveId) || selectedRowKeys.includes(item.sId)),
      };
    }
    return result;
  }, {});
}

// 获取props中所有表配置
export function getAllTableConfig(props) {
  const allTableConfig = {};
  Object.keys(props)
    .filter((key) => {
      if (!key) return false;
      const bEndWithConfig = key.endsWith('Config');
      if (!bEndWithConfig) return false;
      const config = props[key];
      return commonUtils.isNotEmptyArr(config) && config.gdsconfigformslave;
    })
    .forEach((key) => {
      const tableName = key.substring(0, key.length - 6);
      allTableConfig[tableName] = props[`${tableName}Config`];
    });
  return allTableConfig;
}

/* 找到触发行 所关联的所有子表数据 */
export function getChildData(sParentId, tableData) {
  let children = [];

  const filterData = tableData.filter(item => item.sFatherSlaveId === sParentId);
  if (commonUtils.isNotEmptyArr(filterData)) {
    filterData.forEach((rowData) => {
      const sFatherSlaveId = rowData.sId;
      if (commonUtils.isNotEmptyObject(sParentId) && commonUtils.isNotEmptyArr(tableData)) {
        const childData = commonUtils.isNotEmptyArr(tableData) ? tableData.filter(item => item.sFatherSlaveId === sFatherSlaveId) : [];
        if (commonUtils.isNotEmptyArr(childData)) {
          childData.forEach((child) => {
            const { sId } = child;
            children.push(child);
            const data = this.getChildData(sId, tableData);
            if (commonUtils.isNotEmptyArr(data)) {
              children = children.concat(data);
            }
          });
        } else {
          children.push(rowData);
        }
      }
    });
  }

  return children;
}

export function getEvalResult(params) {
  const {
    props,
    str,
    defaultValue = false,
    reocrdRules = false,
  } = params;
  let strNew = str.replace(/\s+/g, '');
  let result = defaultValue;

  const tempData = getAllTableSelectedData(props);
  tempData.props = {
    enabled: !!props.enabled,
  };
  const tempData1 = getAllTableData(props);
  tempData1.props = {
    enabled: props.enabled,
  };
  Object.keys(tempData).forEach((key) => {
    const reg = new RegExp(`${key}\\.`, 'g');
    strNew = strNew.replace(reg, `tempData["${key}"].`);
  });

  const matchResultFunc = (rowData, sFileName, conditionStr, conditionValue) => {
    let rowDataValue = rowData[sFileName];
    try {
      if (rowDataValue === undefined || rowDataValue === null || rowData === 'null') {
        rowDataValue = '';
      } else {
        rowDataValue = rowDataValue.toString();
      }
    // eslint-disable-next-line no-empty
    } catch (error) {}
    switch (conditionStr) {
      case '===':
        return rowDataValue === conditionValue;
      case '==':
        return rowDataValue === conditionValue;
      case '>=':
        return rowDataValue >= conditionValue;
      case '<=':
        return rowDataValue <= conditionValue;
      case '>':
        return rowDataValue > conditionValue;
      case '<':
        return rowDataValue < conditionValue;
      case '!=':
        // eslint-disable-next-line eqeqeq
        return rowDataValue != conditionValue;
      case '!==':
        return rowDataValue !== conditionValue;
      default:
        throw new Error('conditionStr is not valid');
    }
  };

  const sRulesTableList = [];
  try {
    // 截取字符串中 ${tableName@all.fieldName.判断符号.判断内容} 格式的内容
    // eslint-disable-next-line no-useless-escape
    const reg1 = /\$\{[^{}@]+@[^{}\.]+\.[^{}\.]+\.[^{}\.]+\.[^{}\.]*\}/g;
    // 截取字符串中 ${tableName@@all.fieldName.判断符号.判断内容} 格式的内容
    // eslint-disable-next-line no-useless-escape
    const reg2 = /\$\{[^{}@]+@@[^{}\.]+\.[^{}\.]+\.[^{}\.]+\.[^{}\.]*\}/g;
    strNew = strNew.replace(reg2, (matchStr) => {
      const matchStrNew = matchStr.substring(2, matchStr.length - 1);
      const [tableName, restStr] = matchStrNew.split('@@');
      const [filterType, sFileName, conditionStr, conditionValue] = restStr.split('.');
      let matchResult = matchStr;
      if (reocrdRules && !sRulesTableList.includes(tableName)) {
        sRulesTableList.push(tableName);
      }
      const tableData = tempData1[tableName] || [];
      if (filterType === 'all') {
        matchResult = !tableData.some(rowData => !matchResultFunc(rowData, sFileName, conditionStr, conditionValue));
      } else if (filterType === 'one') {
        matchResult = tableData.some(rowData => matchResultFunc(rowData, sFileName, conditionStr, conditionValue));
      }
      return matchResult;
    });
    strNew = strNew.replace(reg1, (matchStr) => {
      const matchStrNew = matchStr.substring(2, matchStr.length - 1);
      const [tableName, restStr] = matchStrNew.split('@');
      const [filterType, sFileName, conditionStr, conditionValue] = restStr.split('.');
      let matchResult = matchStr;
      if (reocrdRules && !sRulesTableList.includes(tableName)) {
        sRulesTableList.push(tableName);
      }
      const tableData = tempData[tableName] || [];
      const selectedRowKeys = props[`${tableName}SelectedRowKeys`] || [];
      const selectedData = tableData.filter(rowData => selectedRowKeys.includes(rowData.sSlaveId) || selectedRowKeys.includes(rowData.sId));
      if (commonUtils.isEmptyObject(selectedData)) return false;
      if (filterType === 'all') {
        matchResult = !selectedData.some(rowData => !matchResultFunc(rowData, sFileName, conditionStr, conditionValue));
      } else if (filterType === 'one') {
        matchResult = selectedData.some(rowData => matchResultFunc(rowData, sFileName, conditionStr, conditionValue));
      }
      return matchResult;
    });

    const evalStr = eval("`" + strNew + "`"); // eslint-disable-line
    result = !!eval(evalStr);
  } catch (error) {
    console.log('=====指令集错误', error, { tempData, str, strNew }); // eslint-disable-line
    return defaultValue;
  }

  if (sRulesTableList.length && params.onSaveState) {
    params.onSaveState({ sRulesTableList });
  }

  return result;
}

export function getControlConfig() {}
