// 计算公式相关工具方法
import {evalFn, getFieldWidgetById, traverseFieldWidgetsOfContainer} from "@base/components/xform/utils/util";
import * as formulajs from '@formulajs/formulajs'
import {EditorView} from "codemirror"
import {MatchDecorator, Decoration, ViewPlugin, WidgetType} from "@codemirror/view"
import {translate} from "@base/components/xform/utils/i18n";

class PlaceholderWidget extends WidgetType {
  field;
  text;
  type;

  constructor(text) {
    super();
    if (text) {
      //type 仅用于区分颜色
      const [field, mText, type] = text.split(".");
      this.text = mText;
      this.type = type;
      this.field = field;
    }
  }

  eq(other) {
    return this.text === other.text;
  }

  // 此处是我们的渲染方法
  toDOM() {
    let elt = document.createElement('span');
    if (!this.text) return elt;
    elt.className = this.type === "func" ? "cm-function" : "cm-field";
    elt.textContent = this.text;
    return elt;
  }

  ignoreEvent() {
    return true;
  }
}

export const FORMULA_REG_EXP = /\{\{(\w+\.[^.]+\.\w+)}}/g

const placeholderMatcher = new MatchDecorator({
  regexp: /\{\{(.+?)}}/g,
  decoration: (match) =>
    Decoration.replace({
      widget: new PlaceholderWidget(match[1])
    })
});


export const placeholders = ViewPlugin.fromClass(class {
  placeholders

  constructor(view) {
    this.placeholders = placeholderMatcher.createDeco(view)
  }

  update(update) {
    this.placeholders = placeholderMatcher.updateDeco(update, this.placeholders)
  }
}, {
  decorations: instance => instance.placeholders,
  provide: plugin => EditorView.atomicRanges.of(view => {
    return view.plugin(plugin)?.placeholders || Decoration.none
  })
})

// 背景样式
export const baseTheme = EditorView.baseTheme({
  ".cm-function": {
    paddingLeft: "6px",
    paddingRight: "6px",
    paddingTop: "3px",
    paddingBottom: "3px",
    marginLeft: "3px",
    marginRight: "3px",
    backgroundColor: "#ffcdcc",
    borderRadius: "4px",
  },
  ".cm-field": {
    paddingLeft: "6px",
    paddingRight: "6px",
    paddingTop: "3px",
    paddingBottom: "3px",
    marginLeft: "3px",
    marginRight: "3px",
    backgroundColor: "#f8e7a0",
    borderRadius: "4px",
  }

});

export function calculateFormula(VFR, DSV, formulaJs, formulaFieldRef, changedFieldRef) {
  if (formulaFieldRef.tableParam) {
  } else if (!!formulaFieldRef.subFormItemFlag && !!changedFieldRef.subFormItemFlag) {
    /* 子表单字段变化，只能触发子表单同一行字段的计算公式重新计算！！ */
    if (changedFieldRef.subFormRowId !== formulaFieldRef.subFormRowId) {
      return
    }
  }

  let formula = formulaFieldRef.field.options.formula
  formula = replaceFieldsAndFunctionsOfFormula(VFR, formulaFieldRef, changedFieldRef)  //替换字段值
  if (!formula) {
    return
  }

  //替换formula-js函数
  const matchResult = formula.match(/[A-Za-z]*/g)
  let matchedList = []
  if (!!matchResult) {
    matchResult.forEach(mi => {
      if (!!mi && (findCalFunStartIndex(mi) !== -1) && !matchedList.includes(mi)) {
        const funcName = mi.toUpperCase()
        formula = formula.replaceAll(mi, 'formulaJs.' + funcName)
        matchedList.push(mi)
      }
    })
  }

  const formulaValue = evalFn(formula, DSV, VFR, formulaJs)
  if(formulaFieldRef)formulaFieldRef.setValue(formulaValue)
  return formulaValue
}

// ... existing code ...
export function baseCalculateFormula(that,formulaStr, row /* VFR, DSV, formulaJs, formulaFieldRef, changedFieldRef */) {
  if(!formulaStr)return
  let formula = formulaStr;
  let VFR = that.getFormRef();
  let DSV = that.getGlobalDsv()
  let formulaJs = formulajs
  let formulaFieldRef = that;
  let changedFieldRef = arguments[5];

  // 增强子表单字段变化时的计算范围控制
  if (formulaFieldRef.tableParam) {
  } else if (!!formulaFieldRef.subFormItemFlag && !!changedFieldRef?.subFormItemFlag) {
    /* 子表单字段变化，只能触发子表单同一行字段的计算公式重新计算 */
    if (changedFieldRef.subFormRowId !== formulaFieldRef.subFormRowId) {
      return
    }
  }

  // 预处理：识别并标记聚合函数，记录它们的参数字段所属子表单
  const aggregationFunctions = ['SUM', 'AVERAGE', 'MAX', 'MIN', 'SUMIF', 'SUMIFS'];
  let functionCalls = [];

  // 解析公式中的函数调用
  // 方案1：先替换占位符，再解析函数调用
  // 临时处理公式中的占位符，以便正确识别函数调用
  let tempFormula = formulaStr;
  const placeholders = tempFormula.match(/\{\{([^}]*)\}\}/g) || [];
  placeholders.forEach(placeholder => {
    // 处理函数占位符
    if (placeholder.includes('.func')) {
      const parts = placeholder.split('.');
      if (parts.length >= 2) {
        const fieldId = parts[0].substring(2); // 去掉开头的 {{
        const funcName = parts[1];
        // 临时替换函数占位符为函数名，便于后续解析
        tempFormula = tempFormula.replace(placeholder, funcName);
      }
    }
  });

  // 解析公式中的函数调用 - 修改正则表达式，支持大小写字母
  let functionCallMatch;
  const functionCallRegex = /([A-Za-z]+)\s*\(([^)]*)\)/g;
  while ((functionCallMatch = functionCallRegex.exec(tempFormula)) !== null) {
    const funcName = functionCallMatch[1].toUpperCase();
    const params = functionCallMatch[2];

    if (aggregationFunctions.includes(funcName)) {
      // 找出原始公式中对应的位置
      const originalStart = formulaStr.indexOf(functionCallMatch[0].substring(0, 10));

      functionCalls.push({
        name: funcName,
        params: params,
        fullMatch: functionCallMatch[0],
        start: originalStart > -1 ? originalStart : functionCallMatch.index
      });
    }
  }

  // 替换字段值，增加对子表单引用子表单场景的特殊处理
  formula = baseReplaceFieldsAndFunctionsOfFormula(VFR, formulaFieldRef, formula, row, functionCalls)

  if (!formula) {
    return
  }

  //替换formula-js函数
  const matchResult = formula.match(/[A-Za-z]*/g)
  let matchedList = []
  if (!!matchResult) {
    matchResult.forEach(mi => {
      if (!!mi && (findCalFunStartIndex(mi) !== -1) && !matchedList.includes(mi)) {
        const funcName = mi.toUpperCase()
        formula = formula.replaceAll(mi, 'formulaJs.' + funcName)
        matchedList.push(mi)
      }
    })
  }

  try {
    const formulaValue = evalFn(formula, DSV, VFR, formulaJs)
    return formulaValue
  } catch (error) {
    console.error('公式计算错误:', error, '公式:', formula);
    return null;
  }
}

// 优化 baseReplaceFieldsAndFunctionsOfFormula 方法，增加对聚合函数的特殊处理
export function baseReplaceFieldsAndFunctionsOfFormula(VFR, formulaFieldRef, formula, row, functionCalls = []) {
  // let formula = formulaFieldRef.field.options.formula
  const matchResult = formula.match(FORMULA_REG_EXP)
  if (!matchResult) {
    return formula
  }

  let resultFormula = formula
  let quitFlag = false

  // 记录所有字段引用及其所属子表单
  let fieldReferences = [];

  matchResult.forEach(mi => {
    const thirdPart = mi.split('.')[2]
    const nodeType = thirdPart.substring(0, thirdPart.length - 2)
    if (nodeType === 'func') {
      const funcName = mi.split('.')[1]
      resultFormula = resultFormula.replace(mi, funcName)
      return
    }

    const firstPart = mi.split('.')[0]
    const fieldId = firstPart.substring(2, firstPart.length)
    const fieldSchema = getFieldWidgetById(VFR.formJsonObj.widgetList, fieldId, false)
    if (!!fieldSchema) {
      let fieldRef = VFR.getWidgetRef(fieldSchema.options.name)
      if (!!fieldRef) {
        let fieldKeyName = getFieldKeyName(fieldSchema)
        let value = fieldRef.formModel[fieldKeyName]??null;
        resultFormula = resultFormula.replace(mi, value)
      } else {  //getWidgetRef找不到，则可能是子表单字段
        const subFormNameOfField = VFR.getSubFormNameOfWidget(fieldSchema.options.name)

        // 记录字段引用信息
        fieldReferences.push({
          placeholder: mi,
          fieldName: fieldSchema.options.name,
          subFormName: subFormNameOfField
        });

        if (!!formulaFieldRef.subFormItemFlag || formulaFieldRef.tableParam || row) {
          /* 如果当前计算字段是子表单字段，要判断公式中的子表单字段是否和当前计算字段是否属于同一子表单！！ */
          // 判断是否是同一子表单
          const isSameSubForm = subFormNameOfField === formulaFieldRef?.parentWidget?.options?.name ||
                              subFormNameOfField === formulaFieldRef.subFormName;

          // 检查该字段是否在某个聚合函数的参数中
          let isInAggregationParam = false;
          functionCalls.forEach(call => {
            if (call.params.includes(mi)) {
              isInAggregationParam = true;
            }
          });

          /* if(functionCalls.length){
          } */

          if (isSameSubForm && !isInAggregationParam) {
            // 同一子表单且不在聚合函数参数中，使用当前行数据
            if(row){
              let fieldKeyName = getFieldKeyName(fieldSchema)
              let value = row[fieldKeyName]??null;
              resultFormula = resultFormula.replaceAll(mi, value)
            }else if (subFormNameOfField === formulaFieldRef?.parentWidget?.options?.name) {
              let subFormRowId = formulaFieldRef.tableParam.row._X_ROW_KEY
              fieldRef = VFR.getWidgetRef(fieldSchema.options.name + '_' + subFormRowId)
              if (!!fieldRef) {
                let value = fieldRef.currentValue??null;
                resultFormula = resultFormula.replaceAll(mi, value)
              } else {
                quitFlag = true
                console.error('Field not found: ' + fieldSchema.options.label)
              }
            } else if (subFormNameOfField === formulaFieldRef.subFormName) {
              fieldRef = VFR.getWidgetRef(fieldSchema.options.name + '@row' + formulaFieldRef.subFormRowId)
              if (!!fieldRef) {
                resultFormula = resultFormula.replaceAll(mi, fieldRef.currentValue)
              } else {
                quitFlag = true
                console.error('Field not found: ' + fieldSchema.options.label)
              }
            }
          } else {
            // 不同子表单或在聚合函数参数中，使用全部明细行数据创建数组表达式
            let dataTableRef = VFR.getWidgetRef(subFormNameOfField)
            if (!dataTableRef) {
              console.error('Subform not found: ' + subFormNameOfField);
              quitFlag = true;
              return;
            }

            const subFormValue = VFR.formDataModel[fieldKeyName(dataTableRef.widget)] || [];
            const subFieldName = fieldKeyName(fieldSchema);

            // 构建有效的数组表达式
            let arrayExpr = '[';
            subFormValue.forEach((vi, idx) => {
              const val = vi[subFieldName] ?? null;
              // 确保数值类型正确处理
              if (val === null || val === undefined || val === '') {
                arrayExpr += (idx === 0) ? '0' : ', 0';
              } else if (typeof val === 'string' && !isNaN(Number(val))) {
                arrayExpr += (idx === 0) ? Number(val) : ', ' + Number(val);
              } else if (typeof val === 'number') {
                arrayExpr += (idx === 0) ? val : ', ' + val;
              } else {
                arrayExpr += (idx === 0) ? '0' : ', 0';
              }
            });
            arrayExpr += ']';

            resultFormula = resultFormula.replaceAll(mi, arrayExpr);
          }
        } else {
          /* 在主表单字段的计算公式中使用子表单字段，应将子表单所有记录同字段的值代入！！ */
          let dataTableRef = VFR.getWidgetRef(subFormNameOfField)
          const subFormValue = VFR.formDataModel[fieldKeyName(dataTableRef.widget)]
          let allSubFieldValues = ''
          const subFieldName = fieldKeyName(fieldSchema)

          // 对于聚合函数，创建数组表达式
          let isInAggregationParam = false;
          functionCalls.forEach(call => {
            if (call.params.includes(mi)) {
              isInAggregationParam = true;
            }
          });

          if (isInAggregationParam) {
            let arrayExpr = '[';
            subFormValue.forEach((vi, idx) => {
              const val = vi[subFieldName] ?? 0;
              arrayExpr += (idx === 0) ? val : ', ' + val;
            });
            arrayExpr += ']';
            resultFormula = resultFormula.replaceAll(mi, arrayExpr);
          } else {
            // 非聚合函数，使用逗号分隔的字符串
            subFormValue.forEach((vi, idx) => {
              let val = vi[subFieldName]??null
              allSubFieldValues = (idx === 0) ? val : allSubFieldValues + ', ' + val
            })
            resultFormula = resultFormula.replaceAll(mi, allSubFieldValues)
          }
        }
      }
    }
  })

  return quitFlag ? null : resultFormula
}
// ... existing code ...


function getFieldKeyName(widget) {
    let o = widget.options.name;
    return (widget.options.keyNameEnabled && widget.options.keyName) || o;
}

function funOtherHanlde(){

}

export function calculateFormula2(formulaStr, data, that) {
  if(!formulaStr)return
  let formula = formulaStr;
  let VFR = that.getFormRef();
  let DSV = that.getGlobalDsv()
  let formulaJs = formulajs

  if(data){
    for(let key in data){
      formula = formula.replaceAll(`[${key}]`,(data[key] || 0))
    }
  }

  //替换formula-js函数
  const matchResult = formula.match(/[A-Za-z]*/g)
  let matchedList = []
  if (!!matchResult) {
    matchResult.forEach(mi => {
      if (!!mi && (findCalFunStartIndex(mi) !== -1) && !matchedList.includes(mi)) {
        const funcName = mi.toUpperCase()
        formula = formula.replaceAll(mi, 'formulaJs.' + funcName)
        matchedList.push(mi)
      }
    })
  }

  const formulaValue = evalFn(formula, DSV, VFR, formulaJs)
  return formulaValue
}

/**
 * 判断字段是否用在计算公式中
 * @param fieldName
 * @param formula
 * @param VFR
 */
export function fieldIsUsedInFormula(fieldName, formula, VFR, fieldTarget) {
  const matchResult = formula.match(FORMULA_REG_EXP)
  if (!matchResult) {
    return false
  }

  let foundResult = false
  matchResult.forEach(mi => {
    const thirdPart = mi.split('.')[2]
    const nodeType = thirdPart.substring(0, thirdPart.length - 2)
    if (nodeType === 'func') {
      return
    }

    const firstPart = mi.split('.')[0]
    const fieldId = firstPart.substring(2, firstPart.length)
    let fieldSchema = getFieldWidgetById(VFR.formJsonObj.widgetList, fieldId, false)
    if (!fieldSchema) {
      console.error('The field used by formula not found: ', fieldId)
      console.error('The formula is: ', formula)
    }
    if (fieldSchema && (fieldSchema.options.name === fieldName)) {
      foundResult = true
    }
  })

  return foundResult
}


/**
 * 替换计算公式中的字段值
 * @param VFR
 * @param formulaFieldRef
 * @returns {*}
 */
export function replaceFieldsAndFunctionsOfFormula(VFR, formulaFieldRef) {
  let formula = formulaFieldRef.field.options.formula
  const matchResult = formula.match(FORMULA_REG_EXP)
  if (!matchResult) {
    return formula
  }

  let resultFormula = formula
  let quitFlag = false
  matchResult.forEach(mi => {
    const thirdPart = mi.split('.')[2]
    const nodeType = thirdPart.substring(0, thirdPart.length - 2)
    if (nodeType === 'func') {
      const funcName = mi.split('.')[1]
      resultFormula = resultFormula.replace(mi, funcName)
      return
    }

    const firstPart = mi.split('.')[0]
    const fieldId = firstPart.substring(2, firstPart.length)
    const fieldSchema = getFieldWidgetById(VFR.formJsonObj.widgetList, fieldId, false)
    if (!!fieldSchema) {
      let fieldRef = VFR.getWidgetRef(fieldSchema.options.name)
      if (!!fieldRef) {
        //是否要考虑字符串值的替换？？
        resultFormula = resultFormula.replace(mi, fieldRef.currentValue)
      } else {  //getWidgetRef找不到，则可能是子表单字段
        const subFormNameOfField = VFR.getSubFormNameOfWidget(fieldSchema.options.name)
        if (!!formulaFieldRef.subFormItemFlag || formulaFieldRef.tableParam) {
          /* 如果当前计算字段是子表单字段，要判断公式中的子表单字段是否和当前计算字段是否属于同一子表单！！ */


          if (subFormNameOfField === formulaFieldRef?.parentWidget?.options?.name) {
            let subFormRowId = formulaFieldRef.tableParam.row._X_ROW_KEY
            fieldRef = VFR.getWidgetRef(fieldSchema.options.name + '_' + subFormRowId)
            if (!!fieldRef) {
              resultFormula = resultFormula.replaceAll(mi, fieldRef.currentValue)
            } else {
              quitFlag = true
              console.error('Field not found: ' + fieldSchema.options.label)
            }
          } else if (subFormNameOfField === formulaFieldRef.subFormName) {
            fieldRef = VFR.getWidgetRef(fieldSchema.options.name + '@row' + formulaFieldRef.subFormRowId)
            if (!!fieldRef) {
              resultFormula = resultFormula.replaceAll(mi, fieldRef.currentValue)
            } else {
              quitFlag = true
              console.error('Field not found: ' + fieldSchema.options.label)
            }
          } else {
            console.error('Invalid formula!')
          }
        } else {
          /* 在主表单字段的计算公式中使用子表单字段，应将子表单所有记录同字段的值代入！！ */
          // const subFormValue = VFR.formDataModel[subFormNameOfField]
          let dataTableRef = VFR.getWidgetRef(subFormNameOfField)
          const subFormValue = VFR.formDataModel[fieldKeyName(dataTableRef.widget)]

          let allSubFieldValues = ''
          // const subFieldName = fieldSchema.options.name
          const subFieldName = fieldKeyName(fieldSchema)
          subFormValue.forEach((vi, idx) => {
            allSubFieldValues = (idx === 0) ? vi[subFieldName] : allSubFieldValues + ', ' + vi[subFieldName]
          })
          resultFormula = resultFormula.replaceAll(mi, allSubFieldValues)
        }
      }
    }
  })

  return quitFlag ? null : resultFormula
}

function fieldKeyName(widget) {
  let o = widget.options.name;
  return (
    (widget.options.keyNameEnabled && widget.options.keyName) || o
  );
}

/**
 * 获取字段值
 */
function getWidgetValue(VFR, formula, widgetName) {
  const sIndex = formula.indexOf("(");
  const func = formula.substring(0, sIndex);

  const funcType = formulas.find(item => {
    if (item.flist.some(fItem => {
      return fItem.fName === func
    })) {
      return item;
    }
  });
  if (translate(funcType.fClass) === "数学类型") {
    return Number(VFR.getWidgetRef(widgetName).getValue());
  } else {
    return VFR.getWidgetRef(widgetName).getValue() + '';
  }
}

// 查找公式中的函数是否在枚举中
export function hasFun(funName) {
  for (let i = 0; i < FORMULA_JS_FUNCTIONS.length; i++) {
    if (funName === FORMULA_JS_FUNCTIONS[i]) {
      return true
    }
  }
  return false
}

export function findCalFunStartIndex(formula) {
  let startIndex = -1
  for (let i = 0; i < FORMULA_JS_FUNCTIONS.length; i++) {
    let index = formula.indexOf(FORMULA_JS_FUNCTIONS[i])
    if (index !== -1) {
      return index
    }
  }
  return startIndex
}

/**
 * 当删除子表单行时，重新计算相关联的计算字段
 */
export function recalculateFormulaOnSubFormRowDelete(VFR, DSV, formulaJs, formulaFieldRef) {
  if (!!formulaFieldRef.subFormItemFlag) {
    return
  }

  let formula = formulaFieldRef.field.options.formula
  formula = replaceFieldsAndFunctionsOfFormula(VFR, formulaFieldRef)  //替换字段值
  if (!formula) {
    return
  }

  //替换formula-js函数
  const matchResult = formula.match(/[A-Za-z]*/g)
  let matchedList = []
  if (!!matchResult) {
    matchResult.forEach(mi => {
      if (!!mi && (findCalFunStartIndex(mi) !== -1) && !matchedList.includes(mi)) {
        const funcName = mi.toUpperCase()
        formula = formula.replaceAll(mi, 'formulaJs.' + funcName)
        matchedList.push(mi)
      }
    })
  }

  console.log('formula: ', formula)
  const formulaValue = evalFn(formula, DSV, VFR, formulaJs)
  formulaFieldRef.setValue(formulaValue)
}

export function broadcastFormulaRecalculateEvent(subFormRef) {
  let fieldNames = []
  let getFieldNamesFn = (fw) => {
    fieldNames.push(fw.options.name)
  }
  traverseFieldWidgetsOfContainer(subFormRef.widget, getFieldNamesFn)
  fieldNames.map(fieldName => {
    subFormRef.getFormRef().broadcast('FieldWidget', 'calculate-formula-sfRowDeleted', [null, fieldName])
  })
}

//--------------------- 以下为公式计算的API方法 start ------------------//
// 日期格式化
export function dateFormat(date, fmt) {
  date = new Date(date)
  let a = ['日', '一', '二', '三', '四', '五', '六']
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
    'w': date.getDay(), // 周
    'W': a[date.getDay()], // 大写周
    'T': 'T'
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

//月份加减
export function addMonths(yearMonthDay, monthNum) {
  let arr = yearMonthDay.split('-'); //2020-08-19或2020-08
  let year = parseInt(arr[0]);
  let month = parseInt(arr[1]);
  month = month + monthNum;
  if (month > 12) { //月份加
    let yearNum = parseInt((month - 1) / 12);
    month = month % 12 === 0 ? 12 : month % 12;
    year += yearNum;
  } else if (month <= 0) { //月份减
    month = Math.abs(month);
    let yearNum = parseInt((month + 12) / 12);
    year -= yearNum;
  }
  month = month < 10 ? "0" + month : month;
  return year + "-" + month;
}

// 获取当前日期 yyyy-MM-dd
export function TODAY() {
  // return this.FUNAPI.DODAY().toLocaleDateString().replaceAll("/","-")
  return dateFormat(new Date(), "yyyy-MM-dd")
}

// 获取当前时间 yyyy-MM-dd hh:mm:ss
export function NOW() {
  // return this.FUNAPI.NOW().toLocaleDateString().replaceAll("/","-")
  return dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
}

/** 加减日期年
 * @param {Object} date 日期
 * @param {Object} month 加减的年
 */
export function EYEAR(date, year) {
  try {
    let myDate = new Date(date)
    let newDate = myDate.setYear(myDate.getFullYear() + year)
    return dateFormat(new Date(newDate), "yyyy-MM-dd")
  } catch (e) {
    //TODO handle the exception
    //console.log(this.i18nt('designer.hint.formulaDateError'), date)
    //console.error(this.i18nt('designer.hint.formulaDateErrorMsg'), e);
  }
}

/** 加减日期月份
 * @param {Object} date 日期
 * @param {Object} month 加减的月份
 */
export function EMONTH(date, month) {
  try {
    let myDate = new Date(date)
    let newDate = myDate.setMonth(myDate.getMonth() + month)
    return dateFormat(new Date(newDate), "yyyy-MM-dd")
  } catch (e) {
    //TODO handle the exception
    // console.log(this.i18nt('designer.hint.formulaDateError'), date)
    // console.error(this.i18nt('designer.hint.formulaDateErrorMsg'), e);
  }
}

/** 加减日期天数
 * @param {Object} date
 * @param {Object} day 加减天数
 */
export function EDAY(date, day) {
  try {
    let myDate = new Date(date)
    let newDate = myDate.setDate(myDate.getDate() + day)
    return dateFormat(new Date(newDate), "yyyy-MM-dd")
  } catch (e) {
    //TODO handle the exception
  }
}

const FORMULA_JS_FUNCTIONS = [
  "INT",
  "SUM",
  "AVERAGE",
  "MAX",
  "MIN",
  "ABS",
  "ROUND",
  "CEILING",
  "LOG",
  "MOD",
  "POWER",
  "AND",
  "IF",
  "IFS",
  "IFERROR",
  "IFNA",
  "NOT",
  "OR",
  "SWITCH",
  "XOR",
  "YEAR",
  "MONTH",
  "DAY",
  "TODAY",
  "NOW",
  "EMONTH",
  "EDAY",
  "FIND",
  "LEFT",
  "RIGHT",
  "LEN",
  "LOWER",
  "UPPER",
  "MID",
  "TRIM",
];

export const formulas = [
  {
    fClass: "designer.hint.formulaFunctionMaths",
    flist: [
      {
        fName: "INT",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaINT",
      },
      {
        fName: "SUM",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaSUM",
      },
      {
        fName: "SUMIF",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaSUMIF",
      },
      {
        fName: "SUMIFS",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaSUMIFS",
      },
      {
        fName: "AVERAGE",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaAVERAGE",
      },
      {
        fName: "MAX",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaMAX",
      },
      {
        fName: "MIN",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaMIN",
      },
      {
        fName: "ABS",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaABS",
      },
      {
        fName: "ROUND",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaROUND",
      },
      {
        fName: "CEILING",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaCEILING",
      },
      {
        fName: "LOG",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaLOG",
      },
      {
        fName: "MOD",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaMOD",
      },
      {
        fName: "POWER",
        fType: "designer.hint.formulaNumber",
        fIntro: "designer.hint.formulaPOWER",
      },
    ],
  },
  {
    fClass: "designer.hint.formulaFunctionLogic",
    flist: [
      {
        fName: "AND",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaAND",
      },
      {
        fName: "IF",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaIF",
      },
      {
        fName: "IFS",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaIFS",
      },
      {
        fName: "IFERROR",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaIFERROR",
      },
      {
        fName: "IFNA",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaIFNA",
      },
      {
        fName: "NOT",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaNOT",
      },
      {
        fName: "OR",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaOR",
      },
      {
        fName: "SWITCH",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaSWITCH",
      },
      {
        fName: "XOR",
        fType: "designer.hint.formulaObject",
        fIntro: "designer.hint.formulaXOR",
      },
    ],
  },
  {
    fClass: "designer.hint.formulaFunctionTime",
    flist: [
      {
        fName: "YEAR",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaYEAR",
      },
      {
        fName: "MONTH",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaMONTH",
      },
      {
        fName: "DAY",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaDAY",
      },
      {
        fName: "TODAY",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaTODAY",
      },
      {
        fName: "NOW",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaNOW",
      },
      {
        fName: "EMONTH",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaEMONTH",
      },
      {
        fName: "EDAY",
        fType: "designer.hint.formulaDate",
        fIntro: "designer.hint.formulaEDAY",
      },
    ],
  },
  {
    fClass: "designer.hint.formulaFunctionString",
    flist: [
      {
        fName: "FIND",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaFIND",
      },
      {
        fName: "LEFT",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaLEFT",
      },
      {
        fName: "RIGHT",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaRIGHT",
      },
      {
        fName: "LEN",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaLEN",
      },
      {
        fName: "LOWER",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaLOWER",
      },
      {
        fName: "UPPER",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaUPPER",
      },
      {
        fName: "MID",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaMID",
      },
      {
        fName: "TRIM",
        fType: "designer.hint.formulaChar",
        fIntro: "designer.hint.formulaTRIM",
      },
    ],
  },
];
