/**
 * Created by mar105 on 2019-02-25.
 */
/* eslint-disable */
import { Modal } from 'antd';
import { Modal as mobileModal } from 'antd-mobile-v2';

import { message } from '@/utils/common/message';
import moment from 'moment';
import * as commonUtils from '../../utils/utils';
import * as commonFunc from './commonFunc'; /* 通用单据方法 */
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import imgCheck from '../../assets/hasChecked.svg'; /* 已审核ICON */
import imgInvalid from '../../assets/haveCancel.png'; /* 已作废ICON */
import imgChecking from '../../assets/haveChecking.svg'; /* 审核中 */
import imgCheckPerson from '../../assets/personChecked1.png'; /* 审核中 */
import imgSubmit from '../../assets/haveSubmited.svg'; /* 已提交 */
import { cloneDeep } from 'lodash';

// -----------------------------------------------------------------------

const antdMobileAlert = mobileModal.alert;

/** 验证表格数据是否正确 */
export function validateTable(configDataOld, validateData, props, key) {
  const configData = props?.onMergeSlaveConfig ? props.onMergeSlaveConfig(configDataOld) : configDataOld;
  let bResult = true;
  if (commonUtils.isNotEmptyObject(configData)  && commonUtils.isNotEmptyArr(configData) && commonUtils.isNotEmptyArr(validateData)) {
    const notEmptyConfigData = configData.gdsconfigformslave.filter(item => item.bNotEmpty && item.sName !== '');
    const notZeroConfigData = configData.gdsconfigformslave.filter(item => item.bNotZero && item.sName !== '');
    for (const row of validateData) {
      const { verificationFailed, verificationFailedMsg } = row;
      if (verificationFailed) {
        message.error(verificationFailedMsg);
        bResult = false;
      }
      for (const item of notEmptyConfigData) {
        if (commonUtils.isEmpty(row[item.sName])) {
          message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotNull')); // 从表不能为空！
          if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
            props.onSaveState({ activeKey: key, loading: false });
          }
          bResult = false;
          break;
        } else if (commonUtils.isNotEmptyObject(item.sName) && item.sName === 'dSinglePQty' && commonUtils.isNotEmptyNumber(row.iPrintMode) && row.iPrintMode !== 4) {
          const { masterData } = props;
          if (row[item.sName] === 0 && commonUtils.isNotEmptyObject(masterData) && !masterData.bBillOutside) {
            message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotZero')); // 不能为0！
            if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
              props.onSaveState({ activeKey: key, loading: false });
            }
            bResult = false;
            break;
          }
        }
      }
      for (const item of notZeroConfigData) {
        const firstDataIndex = commonUtils.isNotEmptyObject(item.sName) ? item.sName.substring(0, 1) : ''; /*   控件首字母(数据格式:字符串)   */
        if (bResult && (firstDataIndex === 'i' || firstDataIndex === 'd') && (commonUtils.isEmpty(row[item.sName]) || row[item.sName] === 0)) {
          message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotZeroNull')); // 数字型不能为空或为0！
          if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
            props.onSaveState({ activeKey: key, loading: false });
          }
          bResult = false;
          break;
        }
      }
      if (!bResult) break;
    }
  }
  return bResult;
}

/** 验证表格数据是否正确 */
export function validateMaster(configDataOld, validateObj, props, key) {
  const configData = props?.onMergeMasterConfig ? props.onMergeMasterConfig(configDataOld) : configDataOld;
  let bResult = true;
  const validateData = commonUtils.isNotEmptyObject(validateObj) ? [validateObj] : [];
  if (commonUtils.isNotEmptyArr(configData) && commonUtils.isNotEmptyArr(validateData)) {
    const notEmptyConfigData = configData.gdsconfigformslave.filter(item => item.bNotEmpty && item.bVisible && item.sName !== '');
    const notZeroConfigData = configData.gdsconfigformslave.filter(item => item.bNotZero && item.bVisible && item.sName !== '');
    for (const row of validateData) {
      for (const item of notEmptyConfigData) {
        if (commonUtils.isEmpty(row[item.sName])) {
          message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotNull')); // 从表不能为空！
          if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
            props.onSaveState({ activeKey: key, loading: false });
          }
          bResult = false;
          break;
        } else if (commonUtils.isNotEmptyObject(item.sName) && item.sName === 'dSinglePQty' && commonUtils.isNotEmptyNumber(row.iPrintMode) && row.iPrintMode !== 4) {
          const { masterData } = props;
          if (row[item.sName] === 0 && commonUtils.isNotEmptyObject(masterData) && !masterData.bBillOutside) {
            message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotZero')); // 不能为0！
            if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
              props.onSaveState({ activeKey: key, loading: false });
            }
            bResult = false;
            break;
          }
        }
      }
      for (const item of notZeroConfigData) {
        const firstDataIndex = commonUtils.isNotEmptyObject(item.sName) ? item.sName.substring(0, 1) : ''; /*   控件首字母(数据格式:字符串)   */
        if (bResult && (firstDataIndex === 'i' || firstDataIndex === 'd') && (commonUtils.isEmpty(row[item.sName]) || row[item.sName] === 0)) {
          message.error(item.showName + commonFunc.showMessage(props.app.commonConst, 'isNotZeroNull')); // 数字型不能为空或为0！
          if (commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(key)) {
            props.onSaveState({ activeKey: key, loading: false });
          }
          bResult = false;
          break;
        }
      }
      if (!bResult) break;
    }
  }
  return bResult;
}

/** 验证字段是否合规 如身份号码、手机号码 */
export function validateField(values, props) {
  let bResult = true;
  const { sMobile, sIdCard } = values;
  if (commonUtils.isNotEmptyObject(sMobile) && !(/^1\d{10}$/.test(sMobile))) {
    message.error(commonFunc.showMessage(props.app.commonConst, 'phoneErr')); // 手机号码输入不合规！
    bResult = false;
  }
  const isIDCard2 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (commonUtils.isNotEmptyObject(sIdCard) && !isIDCard2.test(sIdCard)) {
    message.error(commonFunc.showMessage(props.app.commonConst, 'sIdCardErr')); /* 身份证号码输入不合规 */
    bResult = false;
  }
  if (!bResult) {
    props.onSaveState({ loading: false });
  }
  return bResult;
}
/** 添加审核或者作废图标 */
// eslint-disable-next-line no-unused-vars
export function handleAddIcon(masterData, sModelsType) {
  let imgSrc = '';
  if (commonUtils.isNotEmptyObject(masterData)) {
    const {
      bInvalid,
      bCheck,
      sStatus,
      bSubmit,
    } = masterData;
    if (bInvalid) {
      imgSrc = imgInvalid;
    } else if (bCheck) {
      if (commonUtils.isNotEmptyStr(sModelsType) && sModelsType.includes('element/')) {
        if (sModelsType.includes('element/customerInfo')) {
          imgSrc = imgCheck;
        } else {
          imgSrc = '';
        }
      } else {
        imgSrc = imgCheck;
      }
    } else if (sStatus === '2') {
      imgSrc = imgChecking;
    } else if (bSubmit) {
      imgSrc = imgSubmit;
    }
  }
  return imgSrc;
}


export function handleCheckIcon(masterData, sModelsType) {
  let imgCheckPersonSrc = '';
  if (commonUtils.isNotEmptyObject(masterData)) {
    const {
      bInvalid,
      // eslint-disable-next-line no-unused-vars
      bCheck,
      sStatus,
      bSubmit,
      sCheckPerson,
    } = masterData;
    if (bInvalid) {
      imgCheckPersonSrc = imgInvalid;
    } else if (bCheck && commonUtils.isNotEmptyObject(sCheckPerson)) {
      if (commonUtils.isNotEmptyStr(sModelsType) && sModelsType.includes('element/')) {
        if (sModelsType.includes('element/customerInfo')) {
          imgCheckPersonSrc = imgCheck;
        } else {
          imgCheckPersonSrc = '';
        }
      } else {
        imgCheckPersonSrc = imgCheckPerson;
      }
    } else if (sStatus === '2') {
      imgCheckPersonSrc = imgChecking;
    } else if (bSubmit) {
      imgCheckPersonSrc = imgSubmit;
    }
  }
  return imgCheckPersonSrc;
}

const queryWidth = () => {
  return document?.documentElement?.getBoundingClientRect()?.width <= 750 ? '80%' : 500;
}

/** 保存数据 */
export async function saveData(param) {
  const {
    token, value, sModelsId, baseSuccessFn,
  } = param;
  const { optName, data = [] } = value;

  // 表单修改或删除时候，主表加上修改人（sUpdatePerson）和修改时间（tUpdate）
  const masterDataIndex = data.findIndex(item => item.name === 'master' && commonUtils.isNotEmptyArr(item.column));
  if (masterDataIndex !== -1 && data[masterDataIndex].column[0].handleType !== 'add') {
    const { sUserName = '' } = commonUtils.convertStrToObj(localStorage.getItem('xlybusinessuserinfo'));
    data[masterDataIndex].column[0].sUpdatePerson = sUserName;
    data[masterDataIndex].column[0].tUpdate = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  const { sBillNo, sId } = data?.[masterDataIndex]?.column?.[0] || {};

  const dataReturn = (await commonServices.postValueService(
    token, value,
    `${commonConfig.server_host}business/addUpdateDelBusinessData?sModelsId=${sModelsId}&sBillNo=${sBillNo}&sSysLogSrcId=${sId}`,
  )).data;
  /*   成功的话返回数据   */
  if (dataReturn.code === 1) { /*   成功   */
    message.destroy();
    if (commonUtils.isEmpty(optName)) {
      message.success(dataReturn.msg);
    } else {
      message.success(optName + dataReturn.msg);
    }
    return dataReturn;
  } else if (dataReturn.code === 2) {
    if (location.pathname.toLocaleLowerCase().includes('mobile')) {
      antdMobileAlert('温馨提示', dataReturn.msg, [
        { text: '确认', onPress: () => baseSuccessFn?.() },
      ])
    } else {
      Modal.info({
        title: '温馨提示',
        width: queryWidth(),
        content: (
          // eslint-disable-next-line react/react-in-jsx-scope
          <div>
            {dataReturn.msg}
          </div>
        ),
        okText: '确认',
        onOk() {
          baseSuccessFn?.();
        },
      });
    }
    return dataReturn;
  } else if (dataReturn.code === -7) { /* 防呆校验 返回是-7 */
    return dataReturn;
  } else { /*   失败   */
    message.error(dataReturn.msg);
    return false;
  }
}


/** 处理数据格式
 * sTbName 表名
 * saveTmpData 表单数据
 * delTmpData 表单删除数据
 * bAll 不过滤增加数据还是修改数据 */
export function mergeData(name, sTbName, saveTmpData, delTmpData, bAll) {
  if (name === 'master' && commonUtils.isNotEmptyArr(saveTmpData)) {
    saveTmpData[0].handleType = saveTmpData[0].handleType ? saveTmpData[0].handleType : 'update';
  }
  const delData = commonUtils.isEmptyArr(delTmpData) ? [] : delTmpData;
  const savesData = commonUtils.isEmptyArr(saveTmpData) ? [] : saveTmpData;
  const returnData = bAll ? savesData : savesData.filter(item => item.handleType === 'add' || item.handleType === 'update');
  if (commonUtils.isNotEmptyArr(returnData)) {
    returnData.forEach((item) => { delete item.iIncrement; });
  }
  return { name, sTable: sTbName, column: [...returnData, ...delData] };
}

/** 处理表格传入数据格式 */
export function getTableTypes(name, props) {
  const returnTypes = {
    name,
    app: props.app,
    formId: props.sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onDataChange: props.onDataChange,
    onUploadChange: props.onUploadChange,
    onBeforeUpload: props.onBeforeUpload,
    onModalCancel: props.onModalCancel,
    onLookRow: props.onDataRowLook,
    onAddRow: props.onDataRowAdd,
    onModalRow: props.onDataRowModal,
    onBtnChoose: props.onBtnChoose,
    onCopyRow: props.onDataRowCopy,
    onCopyAllRow: props.onDataRowCopyAll,
    onDelRow: props.onDataRowDel,
    onDownloadRow: props.onDataRowDownload,
    onShowParamRow: props.onDataRowShowParam,
    onSelectRowChange: props.onTableSelectRowChange,
    onDoubleClick: props.onDoubleClick,
    onViewClick: props.onViewClick,
    onRightArrow: props.onRightArrow,
    onTabModalClick: props.onTabModalClick, /* 蓝色链接弹窗 */
    onFieldDoubleClick: props.onFieldDoubleClick, /* 字段双击弹出 */
    onDropDownBlur: props.onDropDownBlur,
    onViewChoose: props.onViewChoose,
    onContextMenu: props.onContextMenu,
    onExpand: props.onExpand,
    onRowMove: props.onRowMove,
    onReplaceRow:props.onReplaceRow,
    onSaveState: props.onSaveState,
    onSelectCommonPopup: props.onSelectCommonPopup,
    onSelectCommonPopupProduct: props.onSelectCommonPopupProduct,
    onSelectDialog: props.onSelectDialog,
    onPartNameClick: props.onPartNameClick, /* 生产排程工艺流程字段弹窗 - 生产进度详情 */
    onCheckChange: props.onCheckParamChange,
    onMergeSlaveConfig: props.onMergeSlaveConfig,
    // OnGetFilterData: props.OnGetFilterData,
    selectedRowKeys: props[`${name}SelectedRowKeys`],
    expKeys: props.expKeys,
    // headerColumn: props[`${name}Column`],
    headerColumn: commonUtils.isNotEmptyArr(props[`${name}GroupColumn`]) ? props[`${name}GroupColumn`] : props[`${name}Column`] ? props[`${name}Column`] : [],
    config: props[`${name}Config`],
    data: props[`${name}Data`],
    totalData: props[`${name}Total`],
    totalData1: props[`${name}Total1`],
    enabled: props.enabled,
    rowSelectionType: 'checkbox', // 表格选择是单选还是多选择
    tableProps: {}, // 表格属性
    isKeyUsesId: true, // 表格是否使用sId作为key 如果不传就是随机
    previewImage: props.previewImage, /* 预览图片地址 */
    previewVisible: props.previewVisible, /* 图片预览弹窗 */
    bMutiSelect: commonUtils.isEmptyArr(props[`${name}Config`]) ? false : props[`${name}Config`].bMutiSelect, /* 表格是否多选 */
    bisMutiSelect: commonUtils.isNotEmptyObject(props[`${name}Config`]) && commonUtils.isNotEmptyArr(props[`${name}Config`].gdsconfigformslave) && commonUtils.isNotEmptyArr(props[`${name}Config`].gdsconfigformslave.filter(item => item.sControlName === 'bisMutiSelect')) ? props[`${name}Config`].gdsconfigformslave.filter(item => item.sControlName === 'bisMutiSelect')[0].bVisible : false, /* 表格是否显示多选框 */
    isDragAndDrop: false, // 是否可以进行可以行移动
    onFilterDropDownData: props.onFilterDropDownData,
    sUseInfo: props.sUseInfo,
    dispatch: props.dispatch,
    sortedInfo: props.sortedInfo || {},
    bPagination: commonUtils.isEmptyArr(props[`${name}Config`]) ? true : props[`${name}Config`].bPagination, /* 表格是否分页 默认分页 */
    realizeHeight: commonUtils.isEmpty(props.realizeHeight) ? 0 : props.realizeHeight, /* Modal拖动向下偏移高度 */
    sTableType: props.sTableType,
    onBtnSearch: props.onBtnSearch,
    searchRowKeys: props.searchRowKeys,
    onChange: props.onChange,
    masterData: props.masterData,
    onGetParamsValue: props.onGetParamsValue,
    showTableName: props.showTableName,
    onExecInstructSet: props.onExecInstructSet,
    masterConfig: props.masterConfig || {},
    onKeyDown: props.onKeyDown,
    onInputClick: props.onInputClick,
  };
  return returnTypes;
}

/**   结算日期计算   */
export function getGeyPayDate(masterData) {
  /*   待用数据声明   */
  const {
    tDeliverDate, sGetPayType, iMonth, iDay, iAfterDeliverDay, tInvoiceDate,
  } = masterData; /*   再从主表中取到需要用的数据   */
  let { tCreateDate } = masterData;
  let tCreateDateValue = commonUtils.convertObjToMomentDefault(tCreateDate, commonUtils.dateFormatA); /*   格式化日期   */
  let tDeliverDateValue = commonUtils.convertObjToMomentDefault(tDeliverDate, commonUtils.dateFormatA); /*   格式化日期   */
  if (commonUtils.isNotEmptyObject(tInvoiceDate)) { /*  销售对账，采购对账若设置开票日期，则根据开票日期计算   */
    tCreateDateValue = tInvoiceDate;
    tDeliverDateValue = tInvoiceDate;
    tCreateDate = moment(tInvoiceDate).format(commonUtils.dateFormatA);
  }
  /*   存在结算类型,那么才做相应的处理   */
  if (commonUtils.isNotEmptyStr(sGetPayType)) {
    /*   待用数据声明   */
    let tGetPayDate = '';
    /*   结算方式   */
    if (sGetPayType === 'now') { /*   现结()   */
      tGetPayDate = tCreateDateValue;
    } else if (sGetPayType === 'month') { /*   月结(当前天大于月结天的向后顺延一个月)   */
      tGetPayDate = moment(tCreateDate).add(iMonth, 'months').format(commonUtils.dateFormatA);
      let tDate = commonUtils.convertObjToMomentDefault(tGetPayDate, commonUtils.dateFormatA);
      tDate = moment(tDate).add(1, 'months').format(commonUtils.dateFormatA);
      tDate = moment(tDate).set('date', 1).format(commonUtils.dateFormatA);
      tDate = moment(tDate).add(-1, 'days').format(commonUtils.dateFormatA);
      const iEndDay = moment(tDate).get('date');
      tGetPayDate = moment(tGetPayDate).set('date', iEndDay > iDay ? iDay : iEndDay);

      const tCurrentDay = moment(tCreateDate).get('date'); /* 当前Day */
      if (tCurrentDay <= iDay) {
        tGetPayDate = moment(tGetPayDate).format(commonUtils.dateFormatA);
      } else {
        tGetPayDate = moment(tGetPayDate).add(1, 'months').format(commonUtils.dateFormatA);
      }
    } else if (sGetPayType === 'deliver') { /*   按送货日期来   */
      tGetPayDate = moment(tDeliverDateValue).add(iAfterDeliverDay, 'days').format(commonUtils.dateFormatA);
    }
    return tGetPayDate;
  }
  /*   返回值   */
  return masterData.tGetPayDate;
}

/**   输入数量, 价格, 税码, 计算计算金额，不含税金额，不含税价格，税额，外币金额，外币税额   */
export function getCalculateByPrice(app, type, masterData, tableDataRow, sFieldName) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]); /* 数量 */
  let dProductPrice = commonUtils.convertToNum(tableDataRow[`d${type}Price`]); /* 价格 */
  let dProductForeignPrice = commonUtils.convertToNum(tableDataRow[`d${type}ForeignPrice`]); /* 外币单价 */
  let dNProductPrice = commonUtils.convertToNum(tableDataRow[`dN${type}Price`]); /* 产品价格 */
  let dProductForeignMoney = commonUtils.convertToNum(tableDataRow[`d${type}ForeignMoney`]); /* 外币金额 */
  let dProductMoney = commonUtils.convertToNum(tableDataRow[`d${type}Money`]); /* 本币金额 */
  const dLossMoney = commonUtils.convertToNum(tableDataRow.dLossMoney); /* 报损金额 */

  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率 */
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType)
    && (sModelsType.includes('manufacture/')
      || sModelsType.includes('quotation/')
      || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  if (sFieldName === `d${type}ForeignPrice`) { /* 输入外币单价 */
    dProductForeignMoney = commonUtils.convertFixNum(dProductQty * dProductForeignPrice, dNetMoney); /* 外币金额 */
    dProductPrice = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignPrice * dCurrencyRate : 0, dNetPrice); /* 本位币单价 */
    dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 金额 */
  }  else {
    if( dProductForeignPrice > 0 ) { /* 如果有外币情况 */
      dProductForeignMoney = commonUtils.convertFixNum(dProductQty * dProductForeignPrice, dNetMoney); /* 外币金额 */
      dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 金额 */
      if(sFieldName !== `d${type}Price`) {  /* 输入数量等 */
        dProductPrice = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignPrice * dCurrencyRate : 0, dNetPrice); /* 本位币单价 */
      }
    } else {
      dProductMoney = commonUtils.convertFixNum(dProductQty * dProductPrice, dNetMoney); /* 金额 */
      dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
    }
    if(sFieldName === `d${type}Price`) {
      dProductForeignPrice = dProductPrice !== 0 ? commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductPrice / dCurrencyRate : 0, dNetPrice) : 0;
    }
  }
  const dProductTaxMoney = commonUtils.convertFixNum((dProductMoney/(1 + (dTaxRate / 100))*(dTaxRate/ 100)), dNetMoney);/* 税额 */
  const dProductNoTaxMoney = dProductMoney - dProductTaxMoney; /* 不含税金额 */
  const dNProductMoney = commonUtils.convertFixNum(dProductQty * dNProductPrice, dNetMoney); /* 产品金额 */
  const dProductNoTaxPrice = dProductMoney !== 0 ? (commonUtils.convertFixNum(dProductQty !== 0 ? (dTaxRate === 0 ? dProductPrice: (dProductMoney/(1 + dTaxRate / 100))/ dProductQty): 0, dNetPrice)):  commonUtils.convertFixNum(dProductPrice/(1 + dTaxRate / 100), dNetPrice); /* 不含税价 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */

  /* 采购对账, 发外对账中改变数量与金额 同步dNSrcNoMoney = 单价*数量 */
  const dSrcNoCheckMoney = commonUtils.convertFixNum(dProductQty * dProductPrice, dNetMoney); /* 金额 */

  if (commonUtils.isNotEmptyNumber(dLossMoney) && dLossMoney > 0) { /* 减去报损 重新算金额 */
    tableDataRow = getCalculateMoneyByLossMoney(app, type, masterData, tableDataRow, dSrcNoCheckMoney, dLossMoney); /*  dSrcNoCheckMoney = dLossMoney 重新算外币金额 */
    dProductForeignMoney = tableDataRow[`d${type}ForeignMoney`];
    dProductMoney = tableDataRow[`d${type}Money`];
  }
  /*   数据赋值   */

  if (tableDataRow.bSalesMaterials) { /* 材料销售 */
    type = 'Product';
  }
  if (sFieldName !== `d${type}Money`) {
    tableDataRow[`d${type}Money`] = commonUtils.convertFixNum(dProductMoney, dNetMoney);
  }
  if (sFieldName !== `dN${type}Money`) {
    tableDataRow[`dN${type}Money`] = commonUtils.convertFixNum(dNProductMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}NoTaxMoney`) {
    tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}Price`) {
    tableDataRow[`d${type}Price`] = commonUtils.convertFixNum(dProductPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}ForeignPrice`) {
    tableDataRow[`d${type}ForeignPrice`] = commonUtils.convertFixNum(dProductForeignPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}NoTaxPrice`) {
    tableDataRow[`d${type}NoTaxPrice`] = commonUtils.convertFixNum(dProductNoTaxPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}TaxMoney`) {
    tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}ForeignMoney`) {
    tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}TaxForeignMoney`) {
    tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  }
  if (sFieldName !== 'dSrcNoCheckMoney') {
    tableDataRow.dSrcNoCheckMoney = commonUtils.convertFixNum(dSrcNoCheckMoney, dNetMoney);
  }
  /*   返回值   */
  return tableDataRow;
}

/**   输入数量, 价格, 税码, 计算计算金额，不含税金额，不含税价格，税额，外币金额，外币税额   */
export function getCalculateByPriceNew(app, type, masterData, tableDataRow, sFileName) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]); /* 数量 */
  const dProofingMoney = commonUtils.convertToNum(tableDataRow.dProofingMoney); /* 打样金额 */
  const dPlateMoney = commonUtils.convertToNum(tableDataRow.dPlateMoney); /* 制版金额 */
  const dKnifeMouldMoney = commonUtils.convertToNum(tableDataRow.dKnifeMouldMoney); /* 刀模金额 */
  let dProductForeignPrice = commonUtils.convertToNum(tableDataRow[`d${type}ForeignPrice`]); /* 外币单价 */
  let dNProductPrice = commonUtils.convertToNum(tableDataRow[`dN${type}Price`]); /* 产品价格 */
  let dProductPrice = commonUtils.convertToNum(tableDataRow[`d${type}Price`]); /* 本币单价 */
  let dProductForeignMoney = commonUtils.convertToNum(tableDataRow[`d${type}ForeignMoney`]);
  let dProductMoney = commonUtils.convertToNum(tableDataRow[`d${type}Money`]); /* 本币金额 */
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率 */
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  const dLossMoney = commonUtils.convertToNum(tableDataRow.dLossMoney); /* 报损金额 */
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && (sModelsType.includes('manufacture/') || sModelsType.includes('quotation/') || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  let dNProductMoney = commonUtils.convertFixNum(dProductQty * dNProductPrice, dNetMoney); /* 产品金额 */
  const dOtherMoney = commonUtils.convertFixNum(dProofingMoney + dPlateMoney + dKnifeMouldMoney, dNetMoney); /* 打样金额+制版金额+刀模金额 */
  if (sFileName === `dN${type}Price` || sFileName === `d${type}Qty`) {
    if (dProductQty === 0) {
      dProductForeignPrice = dNProductPrice !== 0 ? dNProductPrice : 0;
      dProductForeignMoney = 0;
    } else if (dOtherMoney > 0) {
      dProductForeignMoney = commonUtils.convertFixNum(dNProductMoney + dProofingMoney + dPlateMoney + dKnifeMouldMoney, dNetMoney); /* 外币金额 */
      dProductForeignPrice = dProductQty !== 0 ? commonUtils.convertFixNum(dProductForeignMoney / dProductQty, dNetPrice) : 0;
    } else if (dOtherMoney === 0) { /* 若其他费用为0 则产品单价=外币单价，产品金额=外币金额 */
      if (sFileName === `dN${type}Price`) {
        dProductForeignPrice = dNProductPrice;
      }
      dProductForeignMoney = commonUtils.convertFixNum(dProductQty * dProductForeignPrice, dNetMoney); /* 外币金额 */
    }
  } else if (sFileName === `d${type}ForeignPrice`) {
    dProductForeignMoney = commonUtils.convertFixNum(dProductQty * dProductForeignPrice, dNetMoney); /* 外币金额 */
    dNProductMoney = commonUtils.convertFixNum(dProductForeignMoney - dProofingMoney - dPlateMoney - dKnifeMouldMoney, dNetMoney);
    dNProductPrice = dProductQty !== 0 ? commonUtils.convertFixNum(dNProductMoney / dProductQty, dNetPrice) : dProductForeignPrice;
  } else if (sFileName === `d${type}Price`) {
    if (dProductQty === 0) {
      dProductForeignPrice = dProductPrice !== 0 ? commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductPrice / dCurrencyRate : 0, dNetPrice) : 0;
      dNProductPrice = dProductForeignPrice;
    } else {
      dProductMoney = commonUtils.convertFixNum(dProductQty * dProductPrice, dNetMoney);
      dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney);
      dProductForeignPrice = commonUtils.convertFixNum(dProductForeignMoney / dProductQty, dNetPrice);
      dNProductMoney = commonUtils.convertFixNum(dProductForeignMoney - dProofingMoney - dPlateMoney - dKnifeMouldMoney, dNetMoney);
      dNProductPrice = commonUtils.convertFixNum(dNProductMoney / dProductQty, dNetPrice);
    }
  }
  if (sFileName !== `d${type}Price` && sFileName !== `d${type}Money`) {
    dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 金额 */
    dProductPrice = dProductQty !== 0 && dOtherMoney > 0 ? commonUtils.convertFixNum(dProductMoney / dProductQty, dNetPrice) : commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignPrice * dCurrencyRate : 0, dNetPrice); /* 本位币单价 */
  }
  /* 销售对账 改变数量与金额 同步dNSrcNoMoney = 外币金额 */
  const dSrcNoCheckMoney = dProductForeignMoney; /* 金额 */
  if (commonUtils.isNotEmptyNumber(dLossMoney)) { /* 减去报损 重新算金额 */
    tableDataRow = getCalculateMoneyByLossMoney(app, type, masterData, tableDataRow, dSrcNoCheckMoney, dLossMoney); /*  dSrcNoCheckMoney = dLossMoney 重新算外币金额 */
    dProductForeignMoney = tableDataRow[`d${type}ForeignMoney`];
    dProductMoney = tableDataRow[`d${type}Money`];
  }

  const dProductNoTaxMoney = commonUtils.convertFixNum(dProductMoney / (1 + (dTaxRate / 100)), dNetMoney); /* 不含税金额 */
  const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetPrice); /* 不含税价 */
  const dProductTaxMoney = commonUtils.convertFixNum(dProductMoney - dProductNoTaxMoney, dNetMoney); /* 税额 */
  // dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */
  /*   数据赋值   */
  if (sFileName !== `d${type}Price`) {
    tableDataRow[`d${type}Price`] = dProductPrice;
  }
  if (sFileName !== `dN${type}Price`) {
    tableDataRow[`dN${type}Price`] = dNProductPrice;
  }
  if (sFileName !== `d${type}ForeignPrice`) {
    tableDataRow[`d${type}ForeignPrice`] = dProductForeignPrice;
  }
  if (sFileName !== `d${type}Money`) {
    tableDataRow[`d${type}Money`] = commonUtils.convertFixNum(dProductMoney, dNetMoney);
  }
  if (sFileName !== `dN${type}Money`) {
    tableDataRow[`dN${type}Money`] = commonUtils.convertFixNum(dNProductMoney, dNetMoney);
  }
  if (sFileName !== `d${type}NoTaxMoney`) {
    tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  }
  if (sFileName !== `d${type}NoTaxPrice`) {
    tableDataRow[`d${type}NoTaxPrice`] = commonUtils.convertFixNum(dProductNoTaxPrice, dNetPrice);
  }
  if (sFileName !== `d${type}TaxMoney`) {
    tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  }
  if (sFileName !== `d${type}ForeignMoney`) {
    tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  }
  if (sFileName !== `d${type}TaxForeignMoney`) {
    tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  }
  if (sFileName !== 'dSrcNoCheckMoney') {
    tableDataRow.dSrcNoCheckMoney = commonUtils.convertFixNum(dSrcNoCheckMoney, dNetMoney);
  }
  /*   返回值   */
  return tableDataRow;
}

/**   输入报损数量   */
export function getCalculatedLossMoney(app, masterData, tableDataRow, type) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetMoney } = app.decimals;
  const dLossQty = commonUtils.convertToNum(tableDataRow.dLossQty); /* 报损换算数量 */
  const dProductPrice = commonUtils.convertToNum(tableDataRow[`d${type}Price`]);
  const dLossMoney = commonUtils.convertFixNum(dLossQty * dProductPrice, dNetMoney);
  const dProductQty = commonUtils.convertToNum(tableDataRow.dProductQty); /* 数量 */
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率   */
  /*   数据赋值   */
  tableDataRow.dLossMoney = commonUtils.convertFixNum(dLossMoney, dNetMoney);
  const dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  const dSrcNoCheckMoney = commonUtils.isNull(tableDataRow.dSrcNoCheckMoney, 0);
  if (commonUtils.isNotEmptyNumber(dSrcNoCheckMoney) && commonUtils.isNotEmptyNumber(dLossMoney)) {
    const dMoney = commonUtils.convertFixNum(dSrcNoCheckMoney - dLossMoney, dNetMoney);
    if (type === 'Product') {
      const dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
      tableDataRow.dProductForeignMoney = dMoney;/* 产品外币金额 = 源单金额 - 报损金额 */
      tableDataRow.dProductMoney = dProductMoney;/* 产品金额 = 产品外币金额 * 汇率 */
      const dProductNoTaxMoney = commonUtils.convertFixNum(dProductMoney / (1 + (dTaxRate / 100)), dNetMoney); /* 不含税金额 */
      const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetMoney); /* 不含税价 */
      const dProductTaxMoney = commonUtils.convertFixNum(dProductMoney - dProductNoTaxMoney, dNetMoney); /* 税额 */
      const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */
      tableDataRow.dProductNoTaxMoney = dProductNoTaxMoney; /* 不含税金额 */
      tableDataRow.dProductNoTaxPrice = dProductNoTaxPrice; /* 不含税价 */
      tableDataRow.dProductTaxMoney = dProductTaxMoney; /* 税额 */
      tableDataRow.dProductTaxForeignMoney = dProductTaxForeignMoney; /* 外币税额 */
    } else if (type === 'Materials') {
      tableDataRow[`d${type}Money`] = dMoney;/* 产品金额 = 产品外币金额 * 汇率 */
      const dProductNoTaxMoney = commonUtils.convertFixNum(dMoney / (1 + (dTaxRate / 100)), dNetMoney); /* 不含税金额 */
      // const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetPrice); /* 不含税价 */
      const dProductTaxMoney = commonUtils.convertFixNum(dMoney - dProductNoTaxMoney, dNetMoney); /* 税额 */
      tableDataRow[`d${type}NoTaxMoney`] = dProductNoTaxMoney; /* 不含税金额 */
      // tableDataRow[`d${type}NoTaxPrice`] = dProductNoTaxPrice; /* 不含税价 */
      tableDataRow[`d${type}TaxMoney`] = dProductTaxMoney; /* 税额 */
    }
  }
  /*   返回值   */
  return tableDataRow;
}

// 由海口新明同步过来，按朱总需求修改2021.11.26
/**   输入数量, 计算箱包(反算）   */
export function getCalculatedReserveBags1(tableDataRow, sFieldName) {
  /*   执行条件  || sFieldName === 'dTrunkQty'  */
  if (sFieldName === 'dProductQty' || sFieldName === 'dPackQty' || sFieldName === 'dGiveQty') {
    /* 数量 */
    const dProductQty = commonUtils.convertToNum(tableDataRow.dProductQty) + commonUtils.convertToNum(tableDataRow.dGiveQty);
    /* 数量/箱 */
    const dPackQty = commonUtils.convertToNum(tableDataRow.dPackQty);
    /* 包数量 */
    const dTrunkQty = dPackQty !== 0 ? Math.floor(dProductQty / dPackQty) : 0;
    /* 零头数量 */
    const dFractionQty = dPackQty !== 0 ? dProductQty - (dPackQty * dTrunkQty) : 0;
    /*   数据赋值   */
    tableDataRow.dTrunkQty = commonUtils.convertStrToNumberUndefined(dTrunkQty);
    tableDataRow.dFractionQty = commonUtils.convertStrToNumberUndefined(dFractionQty);
  } else if (sFieldName === 'dTrunkQty') {
    /* 数量 */
    const dProductQty = commonUtils.convertToNum(tableDataRow.dProductQty) + commonUtils.convertToNum(tableDataRow.dGiveQty);
    /* 数量/箱 */
    const dTrunkQty = commonUtils.convertToNum(tableDataRow.dTrunkQty);
    /* 包数量 */
    const dPackQty = dTrunkQty !== 0 ? Math.floor(dProductQty / dTrunkQty) : 0;
    /* 零头数量 */
    const dFractionQty = dPackQty !== 0 ? dProductQty - (dPackQty * dTrunkQty) : 0;
    /*   数据赋值   */
    tableDataRow.dPackQty = commonUtils.convertStrToNumberUndefined(dPackQty);
    tableDataRow.dFractionQty = commonUtils.convertStrToNumberUndefined(dFractionQty);
  } else if (sFieldName === 'dFractionQty') {
    /* 数量/箱 */
    const dPackQty = commonUtils.convertToNum(tableDataRow.dPackQty);
    /* 包数量 */
    const dTrunkQty = commonUtils.convertToNum(tableDataRow.dTrunkQty);
    /* 零头数量 */
    const dFractionQty = commonUtils.convertToNum(tableDataRow.dFractionQty);
    /* 数量 */
    // eslint-disable-next-line no-mixed-operators
    const dProductQty = (dPackQty * dTrunkQty) + dFractionQty - commonUtils.convertToNum(tableDataRow.dGiveQty);
    /* 零头数量 */
    /*   数据赋值   */
    tableDataRow.dProductQty = commonUtils.convertStrToNumberUndefined(dProductQty);
  }
  /*   返回值   */
  return tableDataRow;
}

// 由海口新明同步过来，按朱总需求修改2021.11.26
/**   输入数量, 计算箱包   */
export function getCalculatedReserveBags(tableDataRow, sFieldName) {
  /*   执行条件  || sFieldName === 'dTrunkQty'  */
  if (sFieldName === 'dProductQty' || sFieldName === 'dGiveQty') { /* 输入数量,算包数 及零头 */
    /* 数量 */
    const dProductQty = commonUtils.convertToNum(tableDataRow.dProductQty) + commonUtils.convertToNum(tableDataRow.dGiveQty);
    /* 数量/箱 */
    const dPackQty = commonUtils.convertToNum(tableDataRow.dPackQty);
    /* 包数量 */
    const dTrunkQty = dPackQty !== 0 ? Math.floor(dProductQty / dPackQty) : 0;
    /* 零头数量 */
    const dFractionQty = dPackQty !== 0 ? dProductQty - (dPackQty * dTrunkQty) : 0;
    /*   数据赋值   */
    tableDataRow.dTrunkQty = commonUtils.convertStrToNumberUndefined(dTrunkQty);
    tableDataRow.dFractionQty = commonUtils.convertStrToNumberUndefined(dFractionQty);
  } else if (sFieldName === 'dTrunkQty' || sFieldName === 'dPackQty' || sFieldName === 'dFractionQty') { /* 输入包数或零头数量 算总数 */
    /* 数量/箱 */
    const dPackQty = commonUtils.convertToNum(tableDataRow.dPackQty);
    /* 包数量 */
    const dTrunkQty = commonUtils.convertToNum(tableDataRow.dTrunkQty);
    /* 零头数量 */
    const dFractionQty = commonUtils.convertToNum(tableDataRow.dFractionQty);
    /* 数量 */
    // eslint-disable-next-line no-mixed-operators
    const dProductQty = (dPackQty * dTrunkQty) + dFractionQty - commonUtils.convertToNum(tableDataRow.dGiveQty);
    /*   数据赋值   */
    tableDataRow.dProductQty = commonUtils.convertStrToNumberUndefined(dProductQty);
  }
  /*   返回值   */
  return tableDataRow;
}

/**   根据金额，具体计算价格，不含税金额，不含税价格，税额，外币金额，外币税额   */
export function getCalculateMoney(app, masterData, tableDataRow, type, sFieldName) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]); /* 数量 */
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率 */
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && (sModelsType.includes('manufacture/') || sModelsType.includes('quotation/') || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  let dProductForeignMoney = commonUtils.convertToNum(tableDataRow[`d${type}ForeignMoney`]); /* 外币金额 */
  const dProductMoney = commonUtils.convertToNum(tableDataRow[`d${type}Money`]); /* 金额 */
  /* 输入外币金额计算本位币 外币*汇率 =本位币金额 */
  if (sFieldName === `d${type}ForeignMoney`) {
    const dProductStandardMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
    tableDataRow[`d${type}Money`] = commonUtils.convertFixNum(dProductStandardMoney, dNetMoney);
  } else {
    dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  }
  const dProductPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductMoney / dProductQty : 0, dNetPrice); /* 价格 */
  const dProductNoTaxMoney = commonUtils.convertFixNum(dProductMoney / (1 + (dTaxRate / 100)), dNetMoney); /* 不含税金额 */
  const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetPrice); /* 不含税价 */
  const dProductTaxMoney = commonUtils.convertFixNum(dProductMoney - dProductNoTaxMoney, dNetMoney); /* 税额 */
  // const dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */
  /*   数据赋值   */
  if (sFieldName !== `d${type}Price`) {
    tableDataRow[`d${type}Price`] = commonUtils.convertFixNum(dProductPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}NoTaxMoney`) {
    tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}NoTaxPrice`) {
    tableDataRow[`d${type}NoTaxPrice`] = commonUtils.convertFixNum(dProductNoTaxPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}TaxMoney`) {
    tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}ForeignMoney`) {
    tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}TaxForeignMoney`) {
    tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  }
  return tableDataRow;
}

/**   根据金额，具体计算价格，不含税金额，不含税价格，税额，外币金额，外币税额   */
export function getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]); /* 数量 */
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率 */
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && (sModelsType.includes('manufacture/') || sModelsType.includes('quotation/') || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  let dProductMoney = commonUtils.convertToNum(tableDataRow[`d${type}Money`]); /* 本币金额 */
  let dProductForeignMoney = commonUtils.convertToNum(tableDataRow[`d${type}ForeignMoney`]); /* 外币金额 */
  let dNProductMoney = commonUtils.convertToNum(tableDataRow[`dN${type}Money`]); /* 产品金额 */
  let dNProductPrice = commonUtils.convertToNum(tableDataRow[`dN${type}Price`]); /* 产品价格 */
  const dProofingMoney = commonUtils.convertToNum(tableDataRow.dProofingMoney); /* 打样金额 */
  const dPlateMoney = commonUtils.convertToNum(tableDataRow.dPlateMoney); /* 制版金额 */
  const dKnifeMouldMoney = commonUtils.convertToNum(tableDataRow.dKnifeMouldMoney); /* 刀模金额 */
  /* 输入产品金额、打样金额、制版金额、刀模金额 计算外币金额 */
  if (sFieldName === `dN${type}Money` || sFieldName === 'dProofingMoney' || sFieldName === 'dPlateMoney' || sFieldName === 'dKnifeMouldMoney') {
    dProductForeignMoney = commonUtils.convertFixNum(dNProductMoney + dProofingMoney + dPlateMoney + dKnifeMouldMoney, dNetMoney); /* 外币金额 */
    dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
  } else if (sFieldName === `d${type}Money`) {
    dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /*  外币金额 */
    dNProductMoney = commonUtils.convertFixNum(dProductForeignMoney - dProofingMoney - dPlateMoney - dKnifeMouldMoney, dNetMoney); /* 产品金额 */
  } else {
    /* 输入外币金额计算本位币、产品金额 外币*汇率 =本位币金额 */
    dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
    dNProductMoney = commonUtils.convertFixNum(dProductForeignMoney - dProofingMoney - dPlateMoney - dKnifeMouldMoney, dNetMoney); /* 产品金额 */
  }
  dNProductPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dNProductMoney / dProductQty : dNProductPrice, dNetPrice); /* 产品价格 */
  const dProductForeignPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductForeignMoney / dProductQty : 0, dNetPrice); /* 外币价格 */
  const dProductPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductMoney / dProductQty : 0, dNetPrice); /* 本位币价格 */
  const dProductNoTaxMoney = commonUtils.convertFixNum(dProductMoney / (1 + (dTaxRate / 100)), dNetMoney); /* 不含税金额 */
  const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetPrice); /* 不含税价 */
  const dProductTaxMoney = commonUtils.convertFixNum(dProductMoney - dProductNoTaxMoney, dNetMoney); /* 税额 */
  // const dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */

  if (tableDataRow.bSalesMaterials) { /* 材料销售 */
    type = 'Product';
  }

  /*   数据赋值   */
  if (sFieldName !== `dN${type}Money`) {
    tableDataRow[`dN${type}Money`] = dNProductMoney; /* 产品金额 */
  }
  if (sFieldName !== `d${type}ForeignMoney`) {
    tableDataRow[`d${type}ForeignMoney`] = dProductForeignMoney; /* 外币金额 */
  }
  if (sFieldName !== `d${type}Money`) {
    tableDataRow[`d${type}Money`] = dProductMoney; /* 本币金额 */
  }
  if (sFieldName !== `dN${type}Price`) {
    tableDataRow[`dN${type}Price`] = commonUtils.convertFixNum(dNProductPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}ForeignPrice`) {
    tableDataRow[`d${type}ForeignPrice`] = commonUtils.convertFixNum(dProductForeignPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}Price`) {
    tableDataRow[`d${type}Price`] = commonUtils.convertFixNum(dProductPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}NoTaxMoney`) {
    tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  }
  if (sFieldName !== `d${type}NoTaxPrice`) {
    tableDataRow[`d${type}NoTaxPrice`] = commonUtils.convertFixNum(dProductNoTaxPrice, dNetPrice);
  }
  if (sFieldName !== `d${type}TaxMoney`) {
    tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  }
  // tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  if (sFieldName !== `d${type}TaxForeignMoney`) {
    tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  }
  return tableDataRow;
}


/**   输入不含税价格, 计算不含税金额，税额，金额，价格，外币金额，外币税额   */
export function getCalculateNoTaxPrice(app, masterData, tableDataRow, type) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]); /* 数量 */
  const dProductNoTaxPrice = commonUtils.convertToNum(tableDataRow[`d${type}NoTaxPrice`]); /* 不含税价 */
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate); /* 税率 */
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && (sModelsType.includes('manufacture/') || sModelsType.includes('quotation/') || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  const dProductNoTaxMoney = commonUtils.convertFixNum(dProductQty * dProductNoTaxPrice, dNetMoney); /* 不含税金额 */
  const dProductTaxMoney = commonUtils.convertFixNum(dProductNoTaxMoney * (dTaxRate / 100), dNetMoney); /* 税额 */
  const dProductMoney = commonUtils.convertFixNum(dProductNoTaxMoney + dProductTaxMoney, dNetMoney); /* 金额 */
  const dProductPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductMoney / dProductQty : 0, dNetPrice); /* 价格 */
  const dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  const dProductForeignPrice= commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductPrice / dCurrencyRate : 0, dNetPrice); /* 价格 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */
  /*   数据赋值   */
  tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  tableDataRow[`d${type}Money`] = commonUtils.convertFixNum(dProductMoney, dNetMoney);
  tableDataRow[`d${type}Price`] = commonUtils.convertFixNum(dProductPrice, dNetPrice);
  tableDataRow[`d${type}ForeignPrice`] = commonUtils.convertFixNum(dProductForeignPrice, dNetPrice);
  tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  /*   返回值   */
  return tableDataRow;
}

/**   输入不含税金额， 计算不含税价格，税额，金额，价格，外币金额，外币税额   */
export function getCalculateNoTaxMoney(app, masterData, tableDataRow, type) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetPrice, dNetMoney } = app.decimals;
  const { sModelsType } = app.currentPane;
  const dProductQty = commonUtils.convertToNum(tableDataRow[`d${type}Qty`]);
  const dProductNoTaxMoney = commonUtils.convertToNum(tableDataRow[`d${type}NoTaxMoney`]);
  const dTaxRate = commonUtils.convertToNum(tableDataRow.dTaxRate);
  let dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate);
  /* 报价单模块，工单模块、产品工艺卡 汇率取从表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && (sModelsType.includes('manufacture/') || sModelsType.includes('quotation/') || sModelsType.includes('processCard'))) {
    dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */
  }
  const dProductNoTaxPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductNoTaxMoney / dProductQty : 0, dNetPrice); /* 不含税价格 */
  const dProductTaxMoney = commonUtils.convertFixNum(dProductNoTaxMoney * (dTaxRate / 100), dNetMoney); /* 税额 */
  const dProductMoney = commonUtils.convertFixNum(dProductNoTaxMoney + dProductTaxMoney, dNetMoney); /* 金额 */
  const dProductPrice = commonUtils.convertFixNum(dProductQty !== 0 ? dProductMoney / dProductQty : 0, dNetPrice); /* 价格 */
  const dProductForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductMoney / dCurrencyRate : 0, dNetMoney); /* 外币金额 */
  const dProductTaxForeignMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductTaxMoney / dCurrencyRate : 0, dNetMoney); /* 外币税额 */
  /*   数据赋值   */
  tableDataRow[`d${type}NoTaxPrice`] = commonUtils.convertFixNum(dProductNoTaxPrice, dNetPrice);
  tableDataRow[`d${type}TaxMoney`] = commonUtils.convertFixNum(dProductTaxMoney, dNetMoney);
  tableDataRow[`d${type}Money`] = commonUtils.convertFixNum(dProductMoney, dNetMoney);
  tableDataRow[`d${type}Price`] = commonUtils.convertFixNum(dProductPrice, dNetPrice);
  tableDataRow[`d${type}ForeignMoney`] = commonUtils.convertFixNum(dProductForeignMoney, dNetMoney);
  tableDataRow[`d${type}TaxForeignMoney`] = commonUtils.convertFixNum(dProductTaxForeignMoney, dNetMoney);
  /*   返回值   */
  return tableDataRow;
}

/**   手动输入税额， 计算不含税金额，不含税金额为金额-税额   */
export function getCalculateTaxMoney(app, masterData, tableDataRow, type) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetMoney } = app.decimals;
  const dProductTaxMoney = commonUtils.convertToNum(tableDataRow[`d${type}TaxMoney`]);/* 税额 */
  const dProductMoney = commonUtils.convertToNum(tableDataRow[`d${type}Money`]);/* 金额 */
  const dProductNoTaxMoney = commonUtils.convertFixNum(dProductMoney - dProductTaxMoney, dNetMoney); /* 不含税金额 */
  /*   数据赋值   */
  tableDataRow[`d${type}NoTaxMoney`] = commonUtils.convertFixNum(dProductNoTaxMoney, dNetMoney);
  /*   返回值   */
  return tableDataRow;
}

/**   有报损情况下， 计算dSrcNoCheckMoney -  税额 */
export function getCalculateMoneyByLossMoney(app, type, masterData, tableDataRow, dSrcNoCheckMoney, dLossMoney) {
  /*   执行条件   */
  /*   待用数据赋值   */
  const { dNetMoney } = app.decimals;
  const dProductForeignMoney = commonUtils.convertFixNum(dSrcNoCheckMoney - dLossMoney, dNetMoney);
  const dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */
  const dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
  /*   数据赋值   */
  tableDataRow[`d${type}ForeignMoney`] = dProductForeignMoney;
  tableDataRow[`d${type}Money`] = dProductMoney; /* 金额 */
  /*   返回值   */
  return tableDataRow;
}

/* 自定义onChange事件  */
export function getKeyUpEvent(name, sFieldName, tableConfig, masterData, tableDataRow, isWait, dataCollection, dataSelected, app) {
  let tableDataRowNew = {};
  const newCopyTo = {};
  if (name === 'master') {
    tableDataRowNew = masterData;
  } else {
    tableDataRowNew = tableDataRow;
    newCopyTo.slave = tableDataRow;
  }
  if (commonUtils.isNotEmptyObject(tableConfig) && commonUtils.isNotEmptyArr(tableConfig.gdsconfigformslave)) {
    const iConfigIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === sFieldName);
    if (iConfigIndex > -1) {
      newCopyTo.master = masterData;
      // eslint-disable-next-line prefer-destructuring
      const sAssignField = tableConfig.gdsconfigformslave[iConfigIndex].sOnChangeAssignField;
      // eslint-disable-next-line prefer-destructuring
      const sButtonParam = tableConfig.gdsconfigformslave[iConfigIndex].sButtonParam; /* 设置多级联动 */
      console.log('sAssignField:', sAssignField);
      /* keyUp联动其他表 */
      if (commonUtils.isNotEmptyObject(sAssignField) && (sAssignField.includes('@@@:') || sAssignField.includes(';,'))) {
        const sAssignFieldObj = sAssignField.split(';,');
        console.log('=====sAssignFieldObj', sAssignFieldObj);
        let addState = {};

        if (name === 'master') {
          sAssignFieldObj.forEach((sAssignFieldItem) => {
            if (sAssignFieldItem?.indexOf('@@@:') !== -1) {
              const sFormula = sAssignFieldItem.split('@@@:')[1];
              const sAssignFieldV2 = commonFunc.getAssignFieldV2(sFormula, tableDataRowNew);
              const result = commonFunc.getAssignFieldValue(sAssignFieldV2, tableDataRowNew, newCopyTo);
              addState = { ...addState, ...result };
            } else if (sAssignFieldItem?.includes('_all')) {
              const leftFiled = sAssignFieldItem; /* 每一个赋值字段 */
              if (commonUtils.isNotEmptyObject(leftFiled)) {
                const tbName = leftFiled.substring(0, leftFiled.indexOf('_'));
                const tableData = dataCollection[tbName];
                if (commonUtils.isNotEmptyArr(tableData)) {
                  const sOnChangeAssignFieldNew = leftFiled.replace(`${tbName}_all.`, '').trim();
                  tableData.forEach((item, index) => {
                    newCopyTo[tbName] = item;
                    const tableRow = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, item, newCopyTo) }; // 取赋值字段
                    tableRow.handleType = commonUtils.isEmpty(tableRow.handleType) ? 'update' : tableRow.handleType;
                    tableData[index] = tableRow;
                  });
                  addState[tbName] = tableData;
                  masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? 'update' : masterData.handleType;
                  addState.master = masterData;
                  addState.bMultiTable = true;
                }
              }
            } else {
              addState = {
                ...addState,
                ...commonFunc.getAssignFieldValue(sAssignFieldItem, tableDataRowNew, newCopyTo),
              };
            }
          });
        } else {
          sAssignFieldObj.forEach((sAssignFieldItem) => {
            const tableConfigCopy = cloneDeep(tableConfig);
            tableConfigCopy.gdsconfigformslave[iConfigIndex].sOnChangeAssignField = sAssignFieldItem;
            const returnResult = getKeyUpEvent(name, sFieldName, tableConfigCopy, masterData, { ...tableDataRow, ...addState }, isWait, dataCollection, dataSelected, app);
            addState = { ...addState, ...returnResult };
          });
        }

        console.log('=====KeyUpResult', addState);
        return { ...tableDataRowNew, ...addState };
      } else if (commonUtils.isNotEmptyObject(sAssignField) && sAssignField.includes('_')) {
        const addState = {};
        /* 主表联动其他表格 */
        if (name === 'master' && (!sAssignField.includes('filter') && !sAssignField.includes('sum') )) {
          const sAssignFieldObj = sAssignField.split(',');
          if (commonUtils.isNotEmptyArr(sAssignFieldObj)) {
            if (false) { /* 单条件 */
              const leftFiled = sAssignFieldObj[0];
              if (commonUtils.isNotEmptyObject(leftFiled)) {
                const tbName = leftFiled.substring(0, leftFiled.indexOf('_'));
                const tableData = dataCollection[tbName];
                if (commonUtils.isNotEmptyArr(tableData)) {
                  const sOnChangeAssignFieldNew = sAssignField.replace(`${tbName}_all.`, '').trim();
                  tableData.forEach((item, index) => {
                    newCopyTo[tbName] = item;
                    newCopyTo.master = masterData;
                    const tableRow = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, item, newCopyTo, true) }; // 取赋值字段
                    tableRow.handleType = commonUtils.isEmpty(tableRow.handleType) ? 'update' : tableRow.handleType;
                    tableData[index] = tableRow;
                  });
                  addState[tbName] = tableData;
                  masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? 'update' : masterData.handleType;
                  addState.master = masterData;
                  addState.bMultiTable = true;
                }
                return addState;
              }
            } else { /* 多条件 数组方式 */
              sAssignFieldObj.forEach((eachFiled) => { /* 每个赋值字段 */
                if (eachFiled.includes('_')) {
                  const tbName = eachFiled.substring(0, eachFiled.indexOf('_'));
                  const tableData = dataCollection[tbName];
                  if (commonUtils.isNotEmptyArr(tableData)) {
                    const sOnChangeAssignFieldNew = eachFiled.replace(`${tbName}_all.`, '').trim();
                    console.log('333', sOnChangeAssignFieldNew);
                    tableData.forEach((item, index) => {
                      newCopyTo[tbName] = item;
                      newCopyTo.master = masterData;
                      let tableRow = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, item, newCopyTo, true, true) }; // 取赋值字段
                      if (commonUtils.isNotEmptyObject(sButtonParam)) {
                        let sLinkFieldName = '';
                        if (commonUtils.isJSON(sButtonParam)) { /* 按钮条件 */
                          const linkObj = JSON.parse(sButtonParam); /* 联动配置 */
                          let models = 'Product';
                          if (linkObj.linkMaterials) {
                            sLinkFieldName = linkObj.linkMaterials;
                            models = 'Materials';
                          } else if (linkObj.linkProduct) {
                            sLinkFieldName = linkObj.linkProduct;
                            models = 'Product';
                          }
                          console.log('sLinkFieldName', sLinkFieldName, models);
                          tableRow = this.getCalculateAllMoney(app, models, sLinkFieldName, masterData, tableRow);
                        }
                      }
                      tableRow.handleType = commonUtils.isEmpty(tableRow.handleType) ? 'update' : tableRow.handleType;
                      tableData[index] = tableRow;
                    });
                    addState[tbName] = tableData;
                    masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? 'update' : masterData.handleType;
                    addState.master = commonUtils.isNotEmptyObject(addState.master) ? { ...addState.master, ...masterData } : masterData;
                    addState.bMultiTable = true;
                  }
                } else {
                  if (commonUtils.isNotEmptyArr(dataCollection)) { /* 若包含主表 则var主表数据 */
                    if (eachFiled.includes('master.')) {
                      newCopyTo.master = dataCollection.master;
                    } else if (eachFiled.includes('control.')) {
                      // const tbName = 'control';
                    }
                  }
                  tableDataRowNew = { ...tableDataRowNew, ...commonFunc.getAssignFieldValue(eachFiled, tableDataRowNew, newCopyTo) }; // 取赋值字段
                  let { handleType } = masterData;
                  if (name !== 'master') {
                    // eslint-disable-next-line prefer-destructuring
                    handleType = tableDataRow.handleType;
                  }
                  addState.bMultiTable = true;
                  tableDataRowNew.handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
                  addState.master = tableDataRowNew;
                }
              });
              return addState;
            }
          }
        } else {
          const sAssignFieldObj = sAssignField.split(',');
          if (commonUtils.isNotEmptyArr(sAssignFieldObj)) {
            const leftFiled = sAssignFieldObj[0];
            if (commonUtils.isNotEmptyObject(leftFiled)) {
              const tbName = leftFiled.substring(0, leftFiled.indexOf('_'));
              const tableData = dataCollection[name];
              if (commonUtils.isNotEmptyArr(tableData)) {
                if (sAssignField.indexOf('filter') > -1 && sAssignField.indexOf('sum') > -1) { /* 根据过滤条件 筛选目标行数据 汇总数据 赋值到其他表某个字段上 */
                  console.log('赋值字段', sAssignField);
                  let sOnChangeAssignFieldNew = sAssignField;
                  const indexOf = sAssignField.indexOf('_');
                  const targetSumName = sAssignField.substring(0, indexOf); /* 目标要汇总的表名 */
                  let targetTbName = ''; /* 目标要过滤的表名 */
                  /* 拿目标要过滤的表名 */

                  const fStartIndexOf = sAssignField.indexOf(':');
                  const fEndIndexOf = sAssignField.lastIndexOf('_filter');
                  console.log('拿目标要过滤的表名', targetSumName, fStartIndexOf, fEndIndexOf);
                  if (fStartIndexOf > -1 && fEndIndexOf > -1) {
                    targetTbName = sAssignField.substring(fStartIndexOf + 1, fEndIndexOf); /* 找到JSON条件 */
                  }
                  const targetTableData = dataCollection[targetTbName]; /* 目标要过滤的数据集 */
                  const targetData = dataCollection[targetSumName]; /* 目标数据集 */
                  const targetRow = dataSelected[`${targetSumName}Row`]; /* 目标行 */
                  const targetFieldName = sAssignField.substring(sAssignField.indexOf('.') + 1, sAssignField.indexOf(':')); /* 拿到目标汇总字段 */
                  const baseFieldName = sAssignField.substring(sAssignField.lastIndexOf('.') + 1, sAssignField.length); /* 被叠加的字段 */
                  let filterTableData = []; /* 过滤后的数据集 */
                  const leftIndexOf = sAssignField.indexOf('{');
                  const rightIndexOf = sAssignField.lastIndexOf('}');
                  if (leftIndexOf > -1 && rightIndexOf > -1) {
                    const condition = sAssignField.substring(leftIndexOf, rightIndexOf + 1); /* 找到JSON条件 */
                    const conditionStr = condition.toString();
                    sOnChangeAssignFieldNew = sAssignField.replace(`${targetTbName}_filter_${condition}.`, '').replace('_sum', '').trim();
                    console.log('sOnChangeAssignFieldNew', sOnChangeAssignFieldNew);
                    let jsonObj = {};
                    if (commonUtils.isNotEmptyObject(conditionStr) && commonUtils.isJSON(conditionStr)) {
                      jsonObj = JSON.parse(conditionStr);
                      const { ifdo: ifdoStr, condition, decimal = 0 } = jsonObj;
                      let ifdoResult = true;
                      if (ifdoStr) {
                        try {
                          let ifdoStrNew = "";
                          const reg = new RegExp(`master\\.`, "g");
                          ifdoStrNew = ifdoStr.replace(reg, `masterData.`);
                          const reg1 = new RegExp(`slave\\.`, "g");
                          ifdoStrNew = ifdoStrNew.replace(reg1, `tableDataRow.`);
                          const evalStr = eval("`" + ifdoStrNew + "`");
                          ifdoResult = eval(evalStr);
                        } catch (error) {
                          console.log('=====keyup ifdo 报错:', {
                            ifdoStr, error
                          })
                        }
                      }
                      if (!ifdoResult) {
                        return {};
                      }
                      if (commonUtils.isNotEmptyArr(condition)) {
                        for (const item of condition) {
                          const {
                            bFilterName, bFilterCondition, bFilterValue,
                          } = item;
                          /* 若bFilterValue 是字段时 */

                          if (bFilterCondition === '>') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs);
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length);
                              if (sConditionFieldName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] > tableDataRow[sConditionTableName]);
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] > bFilterValue);
                            }
                          } else if (bFilterCondition === '=') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs); /* 条件表 */
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length); /* 条件字段 */
                              if (sConditionTableName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] === tableDataRow[sConditionFieldName]);
                                }
                              }else if (sConditionTableName === 'master') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] === masterData[sConditionFieldName]);
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] === bFilterValue);
                            }
                            if(baseFieldName !== sFieldName) {
                              sFieldName = baseFieldName;
                            }
                          } else if (bFilterCondition === '<') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs); /* 条件表 */
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length); /* 条件字段 */
                              if (sConditionTableName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] < tableDataRow[sConditionFieldName]);
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] < bFilterValue);
                            }
                          }
                        }
                      }
                      let sumData = 0;
                      if (commonUtils.isNotEmptyArr(filterTableData)) {
                        filterTableData.forEach((item) => {
                          const iIndex = targetTableData.findIndex(itemNew => itemNew.sId === item.sId);
                          if (iIndex > -1) {
                            newCopyTo.master = masterData;
                            newCopyTo[targetTbName] = item;
                            newCopyTo[name] = tableDataRow;
                            newCopyTo.slaveInfo = item;
                            newCopyTo.slaveChild = item;
                            if (item.sId !== tableDataRow.sId) {
                              sumData += commonUtils.isNull(item[sFieldName], 0);
                            } else {
                              sumData += commonUtils.isNull(tableDataRow[sFieldName], 0);
                            }
                            // const tableRowAfter = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, tableDataRow, newCopyTo) }; // 取赋值字段
                            // tableRowAfter.handleType = commonUtils.isEmpty(tableRowAfter.handleType) ? 'update' : tableRowAfter.handleType;
                            // targetTableData[iIndex] = { ...item, ...tableRowAfter };
                          }
                        });
                        if (decimal) {
                          sumData = Number(sumData.toFixed(decimal));
                        }
                        console.log('sumData', sumData);
                        if (commonUtils.isNotEmptyObject(targetRow)) {
                          targetRow[sFieldName] = sumData;
                        }
                        if (targetSumName === 'master') { /* 其他表汇总到主表中 */
                          const targetDataNew = name === 'master' ? masterData : targetData;
                          targetDataNew[targetFieldName] = sumData;
                          targetDataNew.handleType = commonUtils.isEmpty(targetDataNew.handleType) ? 'update' : targetDataNew.handleType;
                          addState[targetSumName] = targetDataNew;
                          if(name === 'master') {
                            addState[targetTbName] = targetTableData;
                            return  addState;
                          }
                        } else if (commonUtils.isNotEmptyArr(targetData)) {
                          targetRow[`${sFieldName}Sum`] = sumData;
                          const iSlaveIndex = targetData.findIndex(item => item.sId === targetRow.sId);
                          if (iSlaveIndex > -1) {
                            targetData[iSlaveIndex][`${sFieldName}Sum`] = sumData;
                            newCopyTo[targetSumName] = targetData[iSlaveIndex];
                            // const tableRowAfter = { ...targetRow, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, targetRow, newCopyTo) }; // 取赋值字段
                            // console.log('33', tableRowAfter);
                            targetData[iSlaveIndex].dTotal_waste_qty = sumData;
                            // targetData[iSlaveIndex] = { ...targetData[iSlaveIndex], ...tableRowAfter };
                            targetData[iSlaveIndex].handleType = commonUtils.isEmpty(targetData[iSlaveIndex].handleType) ? 'update' : targetData[iSlaveIndex].handleType;
                            addState[targetData] = targetData;
                          }
                        }
                        addState[targetTbName] = targetTableData;
                      }
                    }
                  }
                } else if (sAssignField.indexOf('sum') > -1) {
                  /* 根据过滤条件 筛选目标行数据 循环赋值 */
                  const sOnChangeAssignFieldNew = sAssignField.replace(`${tbName}_sum.`, '').trim();
                  newCopyTo.master = masterData;
                  let sumData = 0;
                  tableData.forEach((item, index) => {
                    if (item.sId === tableDataRowNew.sId) {
                      item = tableDataRowNew;
                      tableData[index] = tableDataRowNew;
                    }
                    newCopyTo[name] = item;
                    const tableRow = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, item, newCopyTo) }; // 取赋值字段
                    tableRow.handleType = commonUtils.isEmpty(tableRow.handleType) ? 'update' : tableRow.handleType;
                    const tempName = `${sFieldName}temp_sum`;
                    const tempData = tableRow[tempName];
                    if (!commonUtils.isEmpty(tempData)) {
                      sumData += tableRow[tempName];
                      sumData += tableRow[sFieldName];
                    }
                    tableData[index] = tableRow;
                  });
                  addState[name] = tableData;
                  masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? 'update' : masterData.handleType;
                  masterData[sumData] = sumData;
                  addState.masterData = masterData;
                } else if (sAssignField.indexOf('filter') > -1) { /* 根据过滤条件 筛选目标行数据 循环赋值 */
                  let sOnChangeAssignFieldNew = sAssignField;
                  const indexOf = sAssignField.indexOf('_');
                  const targetTbName = sAssignField.substring(0, indexOf); /* 目标要过滤的表名 */
                  const targetTableData = dataCollection[targetTbName]; /* 目标要过滤的数据集 */
                  let filterTableData = []; /* 过滤后的数据集 */
                  const leftIndexOf = sAssignField.indexOf('{');
                  const rightIndexOf = sAssignField.lastIndexOf('}');
                  if (leftIndexOf > -1 && rightIndexOf > -1) {
                    const condition = sAssignField.substring(leftIndexOf, rightIndexOf + 1); /* 找到JSON条件 */
                    const conditionStr = condition.toString();
                    sOnChangeAssignFieldNew = sAssignField.replace(`${targetTbName}_filter_${condition}.`, '').trim();
                    let jsonObj = {};
                    if (commonUtils.isNotEmptyObject(conditionStr)) {
                      jsonObj = JSON.parse(conditionStr);
                      const { condition } = jsonObj;
                      if (commonUtils.isNotEmptyArr(condition)) {
                        for (const item of condition) {
                          const {
                            bFilterName, bFilterCondition, bFilterValue,
                          } = item;
                          /* 若bFilterValue 是字段时 */

                          if (bFilterCondition === '>') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs);
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length);
                              if (sConditionFieldName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] > tableDataRow[sConditionTableName]);
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] > bFilterValue);
                            }
                          } else if (bFilterCondition === '=') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs); /* 条件表 */
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length); /* 条件字段 */
                              if (sConditionTableName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] === tableDataRow[sConditionFieldName]);
                                  /* 寻找递归的数据集 */
                                  const childData = this.getChildData(tableDataRow.sId, targetTableData);
                                  /* 递归循环所有子级 */
                                  if (commonUtils.isNotEmptyArr(childData)) {
                                    filterTableData = filterTableData.concat(childData);
                                  }
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] === bFilterValue);
                            }
                          } else if (bFilterCondition === '<') {
                            if (bFilterValue.includes('.')) { /* 动态字段 */
                              const indexs = bFilterValue.indexOf('.');
                              const sConditionTableName = bFilterValue.substring(0, indexs); /* 条件表 */
                              const sConditionFieldName = bFilterValue.substring(indexs + 1, bFilterValue.length); /* 条件字段 */
                              if (sConditionTableName === 'slave') {
                                if (commonUtils.isNotEmptyArr(targetTableData)) {
                                  filterTableData = targetTableData.filter(item => item[bFilterName] < tableDataRow[sConditionFieldName]);
                                }
                              }
                            } else {
                              filterTableData = targetTableData.filter(item => item[bFilterName] < bFilterValue);
                            }
                          }
                        }
                      }
                      if (commonUtils.isNotEmptyArr(filterTableData)) {
                        filterTableData.forEach((item) => {
                          const iIndex = targetTableData.findIndex(itemNew => itemNew.sId === item.sId);
                          if (iIndex > -1) {
                            newCopyTo.master = masterData;
                            newCopyTo[targetTbName] = item;
                            newCopyTo[name] = tableDataRow;
                            newCopyTo.slaveInfo = item;
                            const tableRowAfter = { ...item, ...commonFunc.getAssignFieldValue(sOnChangeAssignFieldNew, tableDataRow, newCopyTo) }; // 取赋值字段

                            let tableNewRow = {};
                            /* 如果sButtonParam不为空 则代表多级联动 */
                            if (commonUtils.isNotEmptyObject(sButtonParam)) {
                              newCopyTo[name] = tableRowAfter;
                              tableNewRow = { ...tableRowAfter, ...commonFunc.getAssignFieldValue(sButtonParam, tableRowAfter, newCopyTo) }; // 取赋值字段
                            }

                            tableRowAfter.handleType = commonUtils.isEmpty(tableRowAfter.handleType) ? 'update' : tableRowAfter.handleType;
                            if (commonUtils.isNotEmptyObject(tableNewRow)) {
                              targetTableData[iIndex] = { ...tableRowAfter, ...tableNewRow };
                            } else {
                              targetTableData[iIndex] = { ...item, ...tableRowAfter };
                            }
                          }
                        });
                        addState[targetTbName] = targetTableData;
                      }
                    }
                  }
                }
              }
              return tableDataRowNew;
            }
          }
        }
      } else if (commonUtils.isNotEmptyObject(sAssignField)) { /* 单表keyUp事件 */
        tableDataRowNew = { ...tableDataRowNew, ...commonFunc.getAssignFieldValue(sAssignField, tableDataRowNew, newCopyTo) }; // 取赋值字段
        let { handleType } = masterData ? masterData : { handleType: '' };
        if (name !== 'master') {
          // eslint-disable-next-line prefer-destructuring
          handleType = tableDataRow.handleType;
        }
        tableDataRowNew.handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
        if (isWait) {
          return tableDataRowNew;
        }
      } else {
        return {};
      }
    }
  }
}

/**   根据不同的模块，选出具体计算不同模块的计算方式等   */
export function getCalculateAllMoney(app, type, sFieldName, masterData, tableDataRow) {
  /*   待用数据声明   */
  /*   不同的数据进行不同的处理  */
  const sCkxDirectSolutionPack = commonUtils.isNotEmptyObject(app.systemData) && commonUtils.isNotEmptyObject(app.systemData.filter(item => item.sName === 'CkxDirectSolutionPack')) ?
    app.systemData.filter(item => item.sName === 'CkxDirectSolutionPack')[0].sValue : '0'; /* 默认反算 */

  if (sFieldName === 'sMaterialsStyle' || sFieldName === 'sMaterialsName' || sFieldName === 'dAuxiliaryQty' || sFieldName === `d${type}Price` || sFieldName === `dN${type}Price` || sFieldName === `d${type}ForeignPrice` || sFieldName === 'sTaxId' || sFieldName === 'sTaxName' || sFieldName === 'sSupplyId' || sFieldName === 'sSupplyName' || sFieldName === 'sProcessName') {
    if (type === 'Product') {
      tableDataRow = getCalculateByPriceNew(app, type, masterData, tableDataRow, sFieldName);
    } else {
      tableDataRow = getCalculateByPrice(app, type, masterData, tableDataRow, sFieldName);
    }
  } else if (sFieldName === `d${type}Qty`) {
    if (sCkxDirectSolutionPack === '0') { /* 箱包反算 */
      tableDataRow = getCalculatedReserveBags(tableDataRow, sFieldName);
    } else { /* 箱包正算 */
      tableDataRow = getCalculatedReserveBags1(tableDataRow, sFieldName);
    }

    if (type === 'Product') {
      tableDataRow = getCalculateByPriceNew(app, type, masterData, tableDataRow, sFieldName);
    } else {
      tableDataRow = getCalculateByPrice(app, type, masterData, tableDataRow, sFieldName);
    }
  } else if (sFieldName === `d${type}ForeignMoney`) { /* 外币金额 */
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === `d${type}Money`) {
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === 'dNProductMoney') {
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === 'dProofingMoney') {
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === 'dPlateMoney') {
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === 'dKnifeMouldMoney') {
    tableDataRow = getCalculateMoneyNew(app, masterData, tableDataRow, type, sFieldName);
  } else if (sFieldName === `d${type}NoTaxPrice`) {
    tableDataRow = getCalculateNoTaxPrice(app, masterData, tableDataRow, type);
  } else if (sFieldName === `d${type}NoTaxMoney`) {
    tableDataRow = getCalculateNoTaxMoney(app, masterData, tableDataRow, type);
  } else if (sFieldName === 'dAuxiliaryLossQty' || sFieldName === 'dLossQty') {
    tableDataRow = getCalculatedLossMoney(app, masterData, tableDataRow, type);
  } else if (sFieldName === 'dTrunkQty' || sFieldName === 'dFractionQty' || sFieldName === 'dPackQty' || sFieldName === 'dGiveQty') {
    if (sCkxDirectSolutionPack === '0') { /* 箱包反算 */
      tableDataRow = getCalculatedReserveBags(tableDataRow, sFieldName);
    } else { /* 箱包正算 */
      tableDataRow = getCalculatedReserveBags1(tableDataRow, sFieldName);
    }

    if (sFieldName === 'dFractionQty' || sFieldName === 'dTrunkQty' || sFieldName === 'dPackQty') { /* 包数、每包数量、零头数量改变时候 重算金额 */
      tableDataRow = getCalculateByPriceNew(app, type, masterData, tableDataRow, `d${type}Qty`);
    }
  } else if (sFieldName === `d${type}TaxMoney`) {
    tableDataRow = getCalculateTaxMoney(app, masterData, tableDataRow, type);
  }
  return tableDataRow;
}

/** 根据一系列判断，计算出其相应的单位类型 */
export function handleUnitType(app, resultValue) {
  const {
    dGramWeight, sMaterialsStyle, sMaterialsUnit, sAuxiliaryUnit,
  } = resultValue;
  const bReel = resultValue.bReel !== undefined ? resultValue.bReel : false;
  const sStyle = sMaterialsStyle !== undefined ? sMaterialsStyle.indexOf('*') : -1;
  let sMUnit = 'other';
  const unitTList = [commonFunc.showMessage(app.commonConst, 't'), 't', 'T', '吨'];
  const unitKgList = [commonFunc.showMessage(app.commonConst, 'kg'), 'kg', 'KG', '千克'];
  const unitM2List = [commonFunc.showMessage(app.commonConst, 'm2'), 'm2', 'M2', '平方米'];
  let unitM = false;
  if (sAuxiliaryUnit === 'm' || sAuxiliaryUnit === 'M' || sAuxiliaryUnit === '米') {
    unitM = true;
  }
  if (unitTList.includes(sMaterialsUnit) && sStyle > -1 && dGramWeight > 0) {
    sMUnit = 't';
  } else if (unitKgList.includes(sMaterialsUnit) && sStyle > -1 && dGramWeight > 0) {
    sMUnit = 'kg';
  } else if (unitM2List.includes(sMaterialsUnit) && !bReel && sStyle > -1) {
    sMUnit = 'm2';
  } else if (unitM2List.includes(sMaterialsUnit) && bReel && sStyle > -1) {
    sMUnit = 'm2Reel';
  } else if (unitTList.includes(sMaterialsUnit) && unitM && sStyle === -1 && dGramWeight > 0) {
    sMUnit = 'tNo';
  } else if (unitKgList.includes(sMaterialsUnit) && unitM && sStyle === -1 && dGramWeight > 0) {
    sMUnit = 'kgNo';
  } else if (unitM2List.includes(sMaterialsUnit) && bReel && sStyle === -1) {
    sMUnit = 'm2ReelNo';
  }
  return sMUnit;
}


/**   根据数量算出换算数量   */
export function getMaterialsQty(app, tableDataRow, sAuxiliaryFieldName, sFieldName) {
  /* 根据库存数量计算其换算数量 - 正算 */
  const { bReel } = tableDataRow;
  let {
    dGramWeight, sMaterialsStyle, [sAuxiliaryFieldName]: dAuxiliaryQty, dCoefficient, sReelStyle,
  } = tableDataRow;
  dCoefficient = commonUtils.convertIsNotNumToNumber1(dCoefficient); /* 系数 */
  const sType = handleUnitType(app, tableDataRow);

  sMaterialsStyle = sMaterialsStyle === undefined ? '' : sMaterialsStyle;
  dAuxiliaryQty = commonUtils.convertToNum(dAuxiliaryQty);
  let dMaterialsQty = 0;
  dGramWeight = commonUtils.convertToNum(dGramWeight);

  const sMStyleO = sMaterialsStyle !== undefined ? sMaterialsStyle.split('*')[0] : '';
  let sMStyleT = sMaterialsStyle !== undefined ? sMaterialsStyle.split('*')[1] !== '' ? sMaterialsStyle.split('*')[1] : 1 : '';

  // 如果bReel为true，则sMStyleT为1
  if (bReel) {
    sMStyleT = 1;
  }

  if (tableDataRow.sAuxiliaryUnit === sType) {
    dMaterialsQty = dAuxiliaryQty;
  } else if (sType === 't' || sType === 'kg') {
    /* 按重量 */
    const multiple = sType === 't' ? 1000000000000 : 1000000000;
    dMaterialsQty = ((dAuxiliaryQty * (sMStyleO * sMStyleT) * dGramWeight) / multiple).toFixed(6);
  } else if (sType === 'm2') {
    dMaterialsQty = ((dAuxiliaryQty * (sMStyleO * sMStyleT)) / 1000000).toFixed(6);
  } else if (sType === 'm2Reel') {
    dMaterialsQty = ((dAuxiliaryQty * (sMStyleO * sMStyleT)) / 1000).toFixed(6);
  } else if (sType === 'tNo' || sType === 'kgNo') {
    const multiple = sType === 'tNo' ? 1000000000 : 1000000;
    dMaterialsQty = ((dAuxiliaryQty * sMStyleO * dGramWeight) / multiple).toFixed(6);
  } else if (sType === 'm2ReelNo') {
    dMaterialsQty = ((dAuxiliaryQty * sMStyleO) / 1000).toFixed(6);
  } else {
    /**
     * 修改日期：2021-04-02
     * 修改人：吕杰
     * 区域：以下 1 行
     * BUG：-
     * 说明：修复计算精度
     * 原代码：dMaterialsQty = dAuxiliaryQty * dCoefficient;
     */
    dMaterialsQty = (dAuxiliaryQty * dCoefficient).toFixed(6);
  }

  if (sFieldName === 'dReelQty') {
    if (bReel && sReelStyle !== undefined && sReelStyle.toString().split('*').length > 1) {
      const sMReelStyleO = sReelStyle.toString().split('*')[0];
      const sMReelStyleT = sReelStyle.toString().split('*')[1];
      sMStyleT = sMaterialsStyle !== undefined ? sMaterialsStyle.split('*')[1] !== '' ? sMaterialsStyle.split('*')[1] : 1 : '';
      dMaterialsQty = (dAuxiliaryQty * Math.floor(sMStyleO / sMReelStyleO) * (sMStyleT / sMReelStyleT)).toFixed(3);
    } else {
      dMaterialsQty = 0;
    }
  }
  tableDataRow[sFieldName] = dMaterialsQty;
  return tableDataRow;
}

/** 计算库存数量--反算 */
export function getAuxiliaryQty(app, tableDataRow, sFieldName, sAuxiliaryFieldName) {
  const { bReel } = tableDataRow;
  let {
    sMaterialsStyle, [sFieldName]: dMaterialsQty, dGramWeight, dCoefficient,
  } = tableDataRow;
  sMaterialsStyle = sMaterialsStyle === undefined ? '' : sMaterialsStyle;
  dMaterialsQty = commonUtils.convertToNum(dMaterialsQty);
  dGramWeight = commonUtils.convertToNum(dGramWeight);
  dCoefficient = commonUtils.convertIsNotNumToNumber1(dCoefficient); /* 系数 */
  let dAuxiliaryQty = 0;
  const sType = handleUnitType(app, tableDataRow);

  const sMStyleO = sMaterialsStyle !== undefined ? sMaterialsStyle.split('*')[0] : '';
  let sMStyleT = sMaterialsStyle !== undefined ? sMaterialsStyle.split('*')[1] !== '' ? sMaterialsStyle.split('*')[1] : 1 : '';

  // 如果bReel为true，则sMStyleT为1
  if (bReel) {
    sMStyleT = 1;
  }

  if (tableDataRow.sAuxiliaryUnit === sType) {
    dAuxiliaryQty = dMaterialsQty;
  } else if (sType === 't' || sType === 'kg') {
    /* 按重量 */
    const multiple = sType === 't' ? 1000000000000 : 1000000000;
    dAuxiliaryQty = ((dMaterialsQty * multiple) / dGramWeight / (sMStyleO * sMStyleT)).toFixed(0);
  } else if (sType === 'm2') {
    dAuxiliaryQty = ((dMaterialsQty * 1000000) / (sMStyleO * sMStyleT)).toFixed(2);
  } else if (sType === 'm2Reel') {
    dAuxiliaryQty = ((dMaterialsQty * 1000) / (sMStyleO * sMStyleT)).toFixed(2);
  } else if (sType === 'tNo' || sType === 'kgNo') {
    const multiple = sType === 'tNo' ? 1000000000 : 1000000;
    dAuxiliaryQty = ((dMaterialsQty * multiple) / dGramWeight / sMStyleO).toFixed(0);
  } else if (sType === 'm2ReelNo') {
    dAuxiliaryQty = (dMaterialsQty * 1000) / sMStyleO;
  } else {
    dAuxiliaryQty = dMaterialsQty / dCoefficient;
  }
  tableDataRow[sAuxiliaryFieldName] = dAuxiliaryQty;
  return tableDataRow;
}


/**   根据数量用公式处理   */
export async function getFormulaValue(param) {
  /* 根据库存数量计算其换算数量 - 正算 */
  const {
    token, sModelsId, masterData, tableDataRow, sComputeId, sFormulaIdType,
  } = param;
  let result = '';
  const value = {
    sHandleType: 'getResult',
    replaceData: { /* 数据列集合Map形式 */
      billMaster: masterData, /* 单据主表 */
      billSlave: tableDataRow, /* 单据从表 */
    },
    sFormulaId: sComputeId, /* 计算公式ID */
    sFormulaIdType, /* 计算类型（正算、反算） */
    sClientType: '1',
  };
  const url = `${commonConfig.server_host}replaceField/checkReplaceField?sModelsId=${sModelsId}`;
  const dataReturn = (await commonServices.postValueService(token, value, url)).data;
  /*   成功的话返回数据   */
  if (dataReturn.code === 1) { /*   成功   */
    result = dataReturn.dataset.rows[0].sResult;
  } else { /*   失败   */
    // message.error(dataReturn.msg);
    return 0;
  }
  return result;
}
/**   获取发外公式ID   */
export async function getOutSideProcessFormula(param) {
  /* 根据库存数量计算其换算数量 - 正算 */
  const {
    token, sModelsId, sSupplyId, sProcessId,
  } = param;
  let result = '';
  /* 根据客户id,工序id获取公式ID */
  const url = `${commonConfig.server_host}calculationFormula/getFormulaBySupplyIdProcessId?sModelsId=${sModelsId}`;
  const value = {
    sSupplyId,
    sProcessId,
  };
  const dataReturn = (await commonServices.postValueService(token, value, url)).data;
  if (dataReturn.code === 1) {
    if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows)) {
      result = dataReturn.dataset.rows[0].sFormulaId;/* 获取公式ID */
    }
  } else {
    result = '';
  }
  return result;
}

export function getShowTableSelectTypes(name, props, sReturnField) {
  const returnTypes = {
    name,
    app: props.app,
    formId: props.sModelsId,
    data: props[`${name}Data`],
    disabled: !props.enabled,
    sReturnFieldName: sReturnField === undefined ? 'value' : sReturnField,
    onDoubleClick: props.onButtonChange,
  };
  return returnTypes;
}

/** Tree 传入数据格式 */
export function getTreeTypes(name, props) {
  const returnTypes = {
    name,
    app: props.app,
    formId: props.sModelsId,
    checkable: props.checkable === undefined ? true : props.checkable,
    disabled: !props.enabled,
    defaultExpandAll: props.defaultExpandAll ? props.defaultExpandAll : false,
    sKeyName: props[`${name}KeyName`] === undefined ? 'key' : props[`${name}KeyName`],
    sFieldName: props[`${name}sShowName`] === undefined ? 'showName' : props[`${name}sFieldName`],
    treeData: props[`${name}Data`] === undefined ? [] : props[`${name}Data`],
    checkedKeys: props[`${name}CheckedKeys`] === undefined ? [] : props[`${name}CheckedKeys`],
    selectedKeys: props[`${name}SelectedKeys`] === undefined ? [] : props[`${name}SelectedKeys`],
    allCheckKeys: props[`${name}AllCheckKeys`] === undefined ? [] : props[`${name}AllCheckKeys`],
    disabledCheckedKeys: props.disabledCheckedKeys === undefined ? [] : props.disabledCheckedKeys,
    onCheck: props.onTreeCheck === undefined ? undefined : props.onTreeCheck.bind(this, name),
    onSetTreeOptionKeys: props.onSetTreeOptionKeys === undefined ? undefined : props.onSetTreeOptionKeys.bind(this, name),
    showLine: props.showLine,
    isSearch: props.isSearch,
    onSearch: props.onSearch,
    onSelect: props.onTreeSelect,
    checkedAll: true,
    unChecked: true,
    multiple: props.multiple === undefined ? false : props.multiple,
  };
  return returnTypes;
}

/** 输入框 传入数据格式 */
export function getWriteTypes(name, props) {
  const returnTypes = {
    componentName: name,
    gdsconfigformmasterId: props.gdsconfigformmasterId,
    uploading: props.uploading,
    ...props,
  };
  return returnTypes;
}

/** 保存数据 */
export async function clearSocketData(param) {
  message.destroy();
  const {
    token, value, sModelsId,
  } = param;
  const { optName } = value;
  const dataReturn = (await commonServices.postValueService(
    token, value,
    `${commonConfig.server_host}sysWebsocket/clearUserOperationRecord?sModelsId=${sModelsId}`,
  )).data;
  /*   成功的话返回数据   */
  if (dataReturn.code === 1) { /*   成功   */
    if (!commonUtils.isEmpty(optName)) {
      message.success(optName + dataReturn.msg);
    }
    return dataReturn;
  } else { /*   失败   */
    message.error(dataReturn.msg);
    return false;
  }
}
/*
* title:主题
* bVisibleMemo:是否可是操作
* memoField:修改的字段
* currRecord:当前修改的数据
* data:数据
* props
* */
export function createMemoProps(name, props) {
  const { sCurrMemoProps } = props;
  if (commonUtils.isNotEmptyObject(sCurrMemoProps) && commonUtils.isEmptyStr(sCurrMemoProps.title)) {
    sCurrMemoProps.title = '详细';
    sCurrMemoProps.name = name;
  }
  const sMemoProps = {
    ...sCurrMemoProps,
    dataSource: props[`${name}Data`],
    onSaveState: props.onSaveState,
    onGetMemo: props.onGetMemo,
    onGetMemoCancel: props.onGetMemoCancel,
  };
  return sMemoProps;
}

/** 处理图表传入数据格式 */
export function getCharTypes(name, configList, configAndData, props, otherSetting) {
  const returnTypes = {
    ...otherSetting,
    name,
    app: props.app,
    formId: props.sModelsId,
    charConfigAndData: configAndData, /* 总图表配置及数据 */
    charConfigList: configList, /* 配置集 */
    gdsformconst: [], /* 常量 */
    charMenu: [], /* 图表右查询菜单 */
  };
  return returnTypes;
}

/** 处理图表传入数据格式 */
export function getCharConfig(name, charType, dataID, order, width, height) {
  return {
    showName: name,
    iWidth: width,
    sCharType: charType,
    sDataID: dataID,
    iHeight: height,
    iOrder: order,
    sId: dataID + order,
  };
}

// 验证各种参数等是否有必填的
export function validatePramsNotEmpty(props) {
  let result = true;

  const allTableConfig = commonFunc.getAllTableConfig(props);
  const bParamsMustConfigList = [];
  Object.keys(allTableConfig).forEach(tableName => {
    const tableConfig = allTableConfig[tableName] || {};
    const { gdsconfigformslave = [], sChinese } = tableConfig;
    const bMustConfig = gdsconfigformslave.find(item => item.sControlName === 'paramsNotEmpty');
    if (bMustConfig) {
      const { sDefault } = bMustConfig;
      if (sDefault) {
        bParamsMustConfigList.push([tableName, sChinese, sDefault.split(',')]);
      }
    }
  })

  if (!bParamsMustConfigList.length) return result;

  const paramsObj = {
    sProcess: '工序参数',
    sReport: '上报参数',
    sWorkOrder: '工单参数',
    sNorm: '标准书参数',
    sTest: '测试参数'
  };

  try {
    for (let i = 0; i < bParamsMustConfigList.length; i++) {
      const [tableName, sChinese, sParamsNamesList] = bParamsMustConfigList[i];
      const tableData = props[`${tableName}Data`] || [];
      let sProductName = '';
      let sMainPre = '';
      let iLocationIndex = -1;
      let sTipAll = '';
      for (let j = 0; j < tableData.length; j++) {
        const rowData = tableData[j];
        const { sParams: sParamsStr, iOrder = j + 1 } = rowData;
        const sParams = commonUtils.convertStrToObj(sParamsStr, []);
        for (let k = 0; k < sParamsNamesList.length; k++) {
          const sParamsName = sParamsNamesList[k];
          const sParamsData = sParams.find(item => item.sParamType === sParamsName) || {};

          const { data = {} } = sParamsData;
          const { [`${sParamsName}Param`]: paramConfigStr } = rowData;
          const paramConfig = commonUtils.convertStrToObj(paramConfigStr);
          const bMustFieldName = ['12710101117313076578090', '12710101117054908553170'].includes(props.sModelsId) || ['/indexPage/commonCostomTabBill'].includes(props.formRoute) ? 'sParamNotFirstEmpty' : 'sParamNotEmpty';
          const bMustList = Object.keys(paramConfig).filter(
            key => key.startsWith(bMustFieldName) && paramConfig[key]
          ).map(key => `sParam${key.replace(bMustFieldName, '')}`);
          const bMustValueList = bMustList.map(key => {
            //yhl 保存校验不能使用默认值，默认值应放在选择工艺工序进来的时候。
            const sDefaultValue = paramConfig[`${key.replace('sParam', 'sParamDefault')}`];
            return data[key] === undefined ? sDefaultValue : data[key];
          });


          const bNotZeroList = Object.keys(paramConfig).filter(
            key => key.startsWith('sParamNotZero') && paramConfig[key]
          ).map(key => `sParam${key.replace('sParamNotZero', '')}`);
          const bNotZeroValueList = bNotZeroList.map(key => {
            const sDefaultValue = paramConfig[`${key.replace('sParam', 'sParamDefault')}`];
            return data[key] === undefined ? sDefaultValue : data[key];
          });

          const iEmptyIndex = bMustValueList.findIndex(item => item === undefined || item === '');
          const iZeroIndex = bNotZeroValueList.findIndex(item => item === undefined || item === '0' || item === 0);

          if (iEmptyIndex !== -1 || iZeroIndex !== -1) {
            let sTip = '';
            let iIndex = 0;
            for(const mustValue of bMustValueList) {
              if (mustValue === undefined || mustValue === '') {
                if (paramConfig[bMustList[iIndex]] === "色序") {
                  if (commonUtils.isEmpty(rowData.sColorSerialMemo)) {
                    sTip = `${sTip}【${paramConfig[bMustList[iIndex]]}】字段不能为空!xpm`;
                  }
                }
                else if (paramConfig[bMustList[iIndex]] === "电化铝版本") {
                  if (commonUtils.isEmpty(rowData.sAlumiteBomBillNo)) {
                    sTip = `${sTip}【${paramConfig[bMustList[iIndex]]}】字段不能为空!xpm`;
                  }
                } else {
                  sTip = `${sTip}【${paramConfig[bMustList[iIndex]]}】字段不能为空!xpm`;
                }
              }

              iIndex = iIndex + 1;
            }

            iIndex = 0;
            for(const zeroValue of bNotZeroValueList) {
              if (zeroValue === undefined || zeroValue === '0' || zeroValue === 0) {
                sTip = `${sTip}【${paramConfig[bNotZeroList[iIndex]]}】字段不能0!xpm`;
              }
              iIndex = iIndex + 1;
            }

            const sChineseTableName = sChinese.charAt(sChinese.length - 1) === '表' ? sChinese : `${sChinese}表`;
            if (commonUtils.isNotEmptyStr(rowData.sControlId) ) {
              const { slaveData, slave0Child1Data, controlData: controlDataOld } = props;
              const controlData = slave0Child1Data ? slave0Child1Data : controlDataOld;
              const iControlIndex = controlData.findIndex(item => item.sId === rowData.sControlId);
              if (iControlIndex > -1) {
                const iSlaveIndex = slaveData.findIndex(item => controlData[iControlIndex].sCombinedMemo.includes(item.sProductNo));

                if (iSlaveIndex > -1) {
                  sMainPre = slaveData[iSlaveIndex].sMainProductTechnologyId === controlData[iControlIndex].sProductCardId ? '首选：' :
                    slaveData[iSlaveIndex].sSpareProductTechnologyId === controlData[iControlIndex].sProductCardId ?  '备选：' : '';
                  sProductName = slaveData[iSlaveIndex].sProductName;
                  iLocationIndex = tableData.filter(item => item.sControlId === rowData.sControlId).findIndex(item => item.sId === rowData.sId);
                }
              }
            }
            if (!commonUtils.isEmpty(sTip)) {
              if (commonUtils.isNotEmptyStr(sProductName) && iLocationIndex > -1) {
                sTipAll = `${sTipAll}${sMainPre}【${sProductName}的 ${sChineseTableName}】的【第${iLocationIndex + 1}行】的 ${sTip}xpm`;
              } else {
                sTipAll = `${sTipAll}【${sChineseTableName}】的【第${iOrder}行】的 ${sTip}xpm`
              }
            }
          }
        }
      }

      if (commonUtils.isNotEmptyStr(sTipAll)) {
        Modal.error({
          title: "错误提示:",
          content: <div>{handleGetMsg(sTipAll)}</div>,
          okText: "确认",
          onOk() {}
        });
        throw new Error();
      }
    }
  } catch (error) {
    result = false;
  }

  if (!result) {
    props.onSaveState({
      loading: false,
    });
  }
  return result;
}

/* 解析消息 */
export function handleGetMsg(str) {
  const msgArr = commonUtils.isNotEmptyObject(str) ? str.split('xpm'): '';
  const divStr = [];
  if(commonUtils.isNotEmptyArr(msgArr)) {
    for (let i = 0; i < msgArr.length; i ++) {
      divStr.push(<p>{msgArr[i]}</p>);
    }
  }
  return divStr;
}


export function handleGetChanged(props) {
  let bChanged = false;
  let tableNameList = [];
  if(commonUtils.isNotEmptyArr(props)) {
    for (const key of Object.keys(props)) {
      if(key.includes('Config') && !key.includes('onGet') && !key.includes('report')) {
        const tablename =  key.replace('Config', '').trim();
        tableNameList.push(tablename);
      }
    }
  }
  if(commonUtils.isNotEmptyArr(tableNameList)) {

    for (const name of tableNameList) {
      const tableConfig = props[name +'Config']; /* 动态配置 */
      if(commonUtils.isNotEmptyObject(tableConfig)) {
        const tableData = props[name +'Data']; /* 动态配置 */
        const tableDelData = props[name +'DelData']; /* 动态配置 */
        console.log('tableData', tableData);
        if(commonUtils.isNotEmptyArr(tableDelData)) {
          bChanged = true;
          break;
        } else if (name === 'master' && commonUtils.isNotEmptyObject(tableData)) {
          const handleType = tableData.handleType;
          if(commonUtils.isNotEmptyObject(handleType)) {
            bChanged = true;
            break;
          }
        } else if(commonUtils.isNotEmptyArr(tableData)) {
          const filterData =  tableData.filter(item => item.handleType === 'add' || item.handleType === 'update');
          if(commonUtils.isNotEmptyArr(filterData)) {
            bChanged = true;
            break;
          }
        }
      }

    }
    console.log('界面数据是否发生了更改：', bChanged);
    return bChanged;

  }
}
