
//转换公式的参数
function transformArguments(children,curEle,eleMap){
  let fcReg = /(FC\.\S+\()(.+)\)/;
  let fcText = '';
  for (let i = (children.length-1); i >= 0; i--) {
    let ele = children[i];
    //console.log(ele.name)
    let tmpArr = fcReg.exec(ele.template.ft);
    fcText = tmpArr[1] + fcText;//fc.XX( 左括号部分
    let argList = tmpArr[2].split(",");//括号里面参数部分#1,#2..
    //console.log(argList)
    //console.log(text)
    argList.forEach((argText,index)=>{
      if(argText.indexOf('#')>-1){
        //#动态参数
        let argIndex = index;
        for (let j = 0; j < ele.template.args.length; j++) {
          if(ele.template.args[j].key == argText){
            //找到相同的#编码
            argIndex = j;
            break;
          }
        }
        let arg = ele.arguments[argIndex];
        
        if(arg && arg.type == 'Element'){
          if(i != (children.length-1) && curEle.id == arg.id){
            //不是第一个嵌套的公式，且和当前挂载的是同一个元素
            //认为这个参数是之前公式计算的结果，不再写入元素
          }else{
            eleMap[arg.tableElementKey] = {
              id: arg.id,
              name: arg.name,
              tableElementKey: arg.tableElementKey,
              type: "Element",
            };
            fcText += `E[${arg.tableElementKey}]`;
          }
        }else{
          fcText += arg?arg:'""';
        }

      }else{
        //已有参数
        fcText += argText?argText:'';
      }
      if(index != argList.length-1){
        fcText += ',';
      }
    })
    fcText += ')';
  }

  return fcText;
}

export const formulaArrayToString = (processFormula,resultFormula) => {
  let text = '';
  let eleMap = {};//元素字典，为了回显的时候查询信息

  processFormula.forEach(item => {
    if(item.type == 'Element'){
      //console.log(item)
      if(item.children.length <1){
        eleMap[item.tableElementKey] = {
          id: item.id,
          name: item.name,
          tableElementKey: item.tableElementKey,
          type: "Element",
        };
        text += `E[${item.tableElementKey}]`;
      }else{
        text += transformArguments(item.children,item,eleMap);
      }
    }else if(item.type == 'Element'){
      text += item.template.ft;
    }else{
      text += item.name;
    }
  });

  if(resultFormula[0].children.length){
    //等号左侧部分
    let resText = transformArguments(resultFormula[0].children,resultFormula[0],eleMap);
  
    //等号左侧元素不需要，左侧的公式嵌套右侧所有结果
    text = resText.replace(`E[${resultFormula[0].tableElementKey}]`,text);
  }

  console.log(text);
  //console.log(eleMap)
  return {text,eleMap};
}
