<template>
  <basic-container>
  <div class="flex flex-d-c h-100p">
    <div class="box-dashed flex jc-sb">
      <div class="flex">
        <div class="retain-box">
          <el-checkbox v-model="isRetain"></el-checkbox>
          <span>保留</span>
          <el-input-number
            v-model="retainNum"
            :step="1"
            :min="0" :max="5"
            :disabled="!isRetain"
            size="small"
          ></el-input-number>
          <span class="retain">位</span>
        </div>
        <div>
          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
          >
            <el-submenu v-for="(value,key,index) in formulaList" :key="key" :index="key">
              <template slot="title">
                <span>{{key}}</span>
              </template>
              <el-menu-item v-for="(item2,index2) in value" :key="index2" :index="(index+1) +'-' + (index2+1)">{{item2.name}}</el-menu-item>
            </el-submenu>
          </el-menu>
        </div>
      </div>
      <div>
        <!-- <el-button size="small" @click="handwrit">手写模式</el-button> -->
      </div>
    </div>
    <div class="box-dashed">
      <div class="mg-b-20">函数公式</div>
      <div class="edit-text">
        <span>
          <formula-item
            v-for="(item,index) in resultFormula" :key="index"
            :item="item" @click="obj => equationClick(obj,index,'resultFormula')"
          >
          </formula-item>
        </span>
        <span>=</span>
        <span>
          <formula-item
            v-for="(item,index) in processFormula" :key="index"
            :item="item" @click="obj => equationClick(obj,index,'processFormula')"
          >
          </formula-item>
        </span>
      </div>
      <div class="flex jc-sb">
        <div></div>
        <div><el-button type="info" size="small" @click="operationEdit">重置函数</el-button></div>
      </div>
    </div>
    <div v-show="operationVisible" class="operation-box flex1 flex flex-d-c ov-hidden">
      <div>选择参数设置</div>
      <div class="flex flex-d-c flex1 ov-hidden">
        <el-row :gutter="20" class="flex1 ov-hidden">
          <el-col :span="8" class="h-100p">
            <el-card shadow="never" class="h-100p ov-auto">
              <el-scrollbar style="height: 100%">
                <!-- <el-tree
                  class="filter-tree"
                  lazy
                  :load="loadNode"
                  @node-click="getNodeDetail"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  highlight-current
                  node-key="id"
                  ref="tree"
                >
                </el-tree> -->
                <el-tree
                  class="filter-tree"
                  :data="treeData"
                  :default-expanded-keys="defaultExpanded"
                  @node-click="getNodeDetail"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  highlight-current
                  node-key="id"
                  ref="tree"
                >
                </el-tree>
              </el-scrollbar>
            </el-card>
          </el-col>
          <el-col :span="16" class="h-100p flex flex-d-c ov-hidden">
            <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表" style="width:300px">
              <el-option v-if="paramDataList.length" label="选择节点参数" value="选择节点参数"></el-option>
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
            </el-select>
            <div class="mg-t-10 no-mb-col flex1 ov-hidden">
              <el-scrollbar style="height: 100%">
                <el-row>
                  <el-col :span="6" v-for="item in eleList" :key="item.id">
                    <div class="ele-box">
                      <span v-if="item.k">{{item.name}}</span>
                      <span v-else>{{item.eName}}</span>
                      <el-checkbox v-model="item.checked" @change="value => eleChang(value,item)"></el-checkbox>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
            <div class="flex jc-sb">
              <!-- <div>定位数据位置:</div> -->
              <div class="icon-box">
                <el-link :underline="false" icon="el-icon-delete" type="danger" @click="removeSelect"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('+')" icon="el-icon-circle-plus-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('-')" icon="el-icon-remove-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('*')" icon="el-icon-circle-close"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('%')">÷</el-link>
              </div>
              <div>
                <!-- <el-link :underline="false" type="primary" class="mg-r-20" @click="eleAddFormula">元素添加到公式</el-link> -->
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('(',false)">(</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(')',true)">)</el-link>
                <!-- <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('[',false)">【</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(']',true)">】</el-link> -->
                <el-link :underline="false" type="primary" @click="addText">输入值</el-link>
              </div>
            </div>
            <div class="border-grey sele-ele-box">
              <draggable v-model="selectEleFormula">
                <formula-item
                  v-for="(item,index) in selectEleFormula" :key="index"
                  :item="item" @click="obj => eleFormulaClick(obj,index)"
                >
                </formula-item>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <div class="text-align-c">
          <el-button size="small" @click="operationHandle" type="primary">保存</el-button>
          <el-button size="small" @click="operationVisible = false">取消</el-button>
        </div>
      </div>
    </div>
    <div v-show="!operationVisible && !showFunDetail">
      <div class="box-dashed">
        <div class="mg-b-20">函数公式运算执行溯源</div>
        <div>
          <el-select
            v-model="projectId"
            @change="projectChange"
            placeholder="请选择项目"
            style="width: 380px"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-model="contractId" placeholder="请选择合同段">
            <el-option
              v-for="item in contractList"
              :key="item.id"
              :label="item.contractName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="info">查询</el-button>
        </div>
      </div>
    </div>
    <div v-if="!operationVisible && showFunDetail" class="flex1">
      <el-tabs v-model="actiFunIndex" closable @tab-remove="removeFun" :before-leave="funLeave">
        <el-tab-pane v-for="(item,index) in equationSelectEle.children" :key="index" :label="item.name" :name="index.toString()">
          <template v-if="!componentMap[item.name]">
            <formula-template ref="dynamiccomponent" :formulainfo="item" :curele="equationSelectEle" @sele-ele-handle="showChooseEle">
            </formula-template>
          </template>
          <template v-else>
            <div class="flex" style="height:calc(100vh - 460px)">
              <div class="flex flex-d-c">
                <component ref="dynamiccomponent" v-bind:is="componentMap[item.name]" :formulainfo="item" :curele="equationSelectEle" :formulamap="formulaMap" @uncheck="unCheckEleComp" class="flex1"></component>
                <div v-show="item.showSelectEle">
                  <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素表" style="width:100%">
                    <el-option v-if="paramDataList.length" label="选择节点参数" value="选择节点参数"></el-option>
                    <el-option  v-for="item in eleTableListComp" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
                  </el-select>
                  <div class="mg-t-10 mg-b-10 no-mb-col" style="width:900px">
                    <el-scrollbar style="height: 210px;">
                      <el-row>
                        <el-col :span="6" v-for="item in eleListComp" :key="item.id">
                          <div class="ele-box">
                            <span v-if="item.k">{{item.name}}</span>
                            <span v-else>{{item.eName}}</span>
                            <el-checkbox v-model="item.checked" @change="value => setComponentEle(value,item,index)"></el-checkbox>
                          </div>
                        </el-col>
                      </el-row>
                    </el-scrollbar>
                  </div>
                </div>
              </div>
              <div class="flex1" v-show="item.showSelectEle">
                <el-scrollbar style="height: 100%">
                  <el-tree
                    class="filter-tree"
                    :data="treeData"
                    :default-expanded-keys="defaultExpanded"
                    @node-click="getNodeDetailComp"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    highlight-current
                    node-key="id"
                    ref="tree"
                  >
                  </el-tree>
                </el-scrollbar>
              </div>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="text-align-c" v-show="!operationVisible">
      <el-button type="warning" @click="$emit('hideDialog')">取消</el-button>
      <el-button type="primary" @click="saveFormula">保存</el-button>
    </div>
  </div>

    <el-dialog title="输入值" :visible.sync="inputVisible" width="300px" append-to-body :close-on-click-modal="false">
      <el-input v-model="inputText" placeholder="请输入内容"></el-input>
      <div class="text-align-c mg-t-10">
        <el-button size="small" @click="addTextHandle" type="primary">保存</el-button>
        <el-button size="small" @click="inputVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择元素" :visible.sync="chooseEleVisible" width="70%" append-to-body :close-on-click-modal="false">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="never">
              <el-scrollbar style="height: 460px">
                <el-tree
                  class="filter-tree"
                  :data="treeData"
                  :default-expanded-keys="defaultExpanded"
                  @node-click="getNodeDetail"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  highlight-current
                  node-key="id"
                  ref="tree"
                >
                </el-tree>
              </el-scrollbar>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表">
              <el-option v-if="paramDataList.length" label="选择节点参数" value="选择节点参数"></el-option>
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
            </el-select>
            <div class="mg-t-10 mg-b-10 no-mb-col">
              <el-scrollbar style="height: 460px">
                <el-row>
                  <el-col :span="6" v-for="item in eleList" :key="item.id">
                    <div class="ele-box">
                      <span v-if="item.k">{{item.name}}</span>
                      <span v-else>{{item.eName}}</span>
                      <el-checkbox v-model="item.checked" @change="value => eleCheckHandle(value,item)"></el-checkbox>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
        <div class="text-align-c">
          <el-button size="small" @click="chooseEleHandle" type="primary">保存</el-button>
          <el-button size="small" @click="chooseEleVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="手写模式" :visible.sync="handwritVisible" width="900px" append-to-body :close-on-click-modal="false">
      <div class="font-c-warning">tips:手写模式不保证能转换成配置模式！！即使能转换也不保证正确！！！</div>
      <div class="mg-b-20 font-c-warning">无法在手写模式手写加入新的元素！新的节点参数！</div>
      <editor v-model="handwritText" @init="editorInit" lang="javascript" theme="github" width="100%" height="200"></editor>
      <!-- <el-input
        type="textarea"
        :autosize="{ minRows: 5,}"
        placeholder="请输入内容"
        v-model="handwritText">
      </el-input> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handwritVisible = false">取 消</el-button>
        <el-button type="primary" @click="handwritTransform">转 换</el-button>
      </span>
    </el-dialog>

  </basic-container>
</template>

<script>
import { getLazytree,selectFormElements,getAlltree,getNodeTabAndParam} from "@/api/manager/wbstree";
import { getProjectList,findProjectTree } from "@/api/manager/projectinfo";
import { findContractByProjectId } from "@/api/manager/contractinfo";
import { getDetail as getEleDeatil } from "@/api/manager/wbsformelement";
import { getTypeMap,saveFormula,formulaDetail,updateFormula } from "@/api/formula/formula";
import { getNodeTabAndParam as wbsPrivateGetNodeTabAndParam } from "@/api/manager/wbsprivate";
import {mapGetters} from "vuex";

import formulaItem from "./component/formulaItem"
import formulaTemplate from "./component/formulaTemplate"

import dateDeviation from "./component/funComponent/dateDeviation"
import dateFormat from "./component/funComponent/dateFormat"
import datasRepeat from "./component/funComponent/datasRepeat"
import datasReme from "./component/funComponent/datasReme"
import datasGetlist from "./component/funComponent/datasGetlist"
import datasJoin from "./component/funComponent/datasJoin"
import ifelse from "./component/funComponent/ifelse"

import {formulaArrayToString} from "./formulaArrayToString"
import {formulaStringToArray} from "./formulaStringToArray"

import draggable from 'vuedraggable'

export default {
  components: {
    draggable,

    formulaItem,
    formulaTemplate,

    editor: require('vue2-ace-editor'),

    dateDeviation,
    dateFormat,
    datasRepeat,
    datasReme,
    datasGetlist,
    datasJoin,
    ifelse
  },
  props: {
    wbsid:{
      type:String,
      default:''
    },
    eleid:{
      type:String,
      default:''
    },
    nodeid:{
      type:String,
      default:''
    },
    pid:{
      type:String,
      default:''
    },
  },
  data() {
    return {
      // wbsid: "", //从哪个wbs树过来的
      // eleid: "", //元素id
      // nodeid:'',//所在树节点id
      // pid:'',//项目id 私有树才有
      formulaid:'',

      treeData:[],//树节点
      defaultExpanded:[],//默认展开节点

      isRetain: false, //是否保留小数
      retainNum: 2, //保留几位小数
      formulaList:{},
      formulaMap:{},
      activeIndex: "1-1", //当前选择的公式

      projectList: [], //项目备选列表
      projectId: "", //溯源的项目ID
      curProjiect: {}, //当前项目对象
      contractList: [], //合同段备选列表
      contractId: "", //合同段id

      operationVisible: false, //基础运算弹窗
      defaultProps: {
        children: "children",
        label: "title",
        isLeaf: function (data) {
          return !data.hasChildren || (data.isExistForm==1);
        },
      },
      eleTableId:'',//选中的元素表id
      eleTableList:[],
      eleList:[],
      selectEleFormula:[],
      curSeleEleIndex:-1,//公式文字里面选中的元素索引
      inputVisible:false,//输入弹窗
      inputText:"",//输入值
      deleEleIndex:-1,//删除元素的位置，如果下次添加元素，先加到这个位置

      resultFormula:[],//=等号左边的数组
      processFormula:[],//=等号右边的数组
      processType:'',//选中的元素在等号哪边
      processSelectIndex:0,//选中的索引
      actiFunIndex:0,//元素下挂载的计算式的索引
      chooseEleVisible:false,//选择元素弹窗
      argumenObj:{},

      symbolReg:/(\+|-|\*|\/)（.+）/,
      operatorReg : /^\+|-|\*|%/,//加减乘除
      startFCRegExp : /^FC\.([a-zA-Z]+)\(/,// 匹配开始的FC.xxx(

      componentMap:{
        '日期偏移':'date-deviation',
        '日期格式化':'date-format',
        // '去重':'datas-repeat',
        // '去空':'datas-reme',
        '下标取数':'datas-getlist',
        // '数组转字符串':"datas-join",
        '判断':'ifelse'
      },

      eleListComp:[],//方法下面元素列表
      eleTableListComp:[],//方法下面元素表列表
      eleTableIdComp:'',//方法下面元素表id

      handwritVisible:false,//手写弹框
      handwritText:'',//文本
      handwritEleMap:'',//元素map

      paramDataList:[],//节点参数数组
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),

    // selectEleFormulaText:function(){
    //   let text = '';
    //   this.selectEleFormula.forEach((Element)=>{
    //     text+=Element.name;
    //   })
    //   return text
    // }

    //等式中选中的元素
    equationSelectEle:function(){
      if(this.processType){
        return this[this.processType][this.processSelectIndex];
      }else{
        return null;
      }
    },

    //是否显示元素下挂载的计算式信息
    showFunDetail:function(){
      if(this.equationSelectEle && this.equationSelectEle.children && this.equationSelectEle.children.length>0){
        return true;
      }else{
        return false;
      }
    }
  },
  created() {
    // this.wbsid = this.$route.query.wbsid;
    // this.eleid = this.$route.query.eleid;
    // this.nodeid = this.$route.query.nodeid;
    // this.pid = this.$route.query.projectid;//项目id 私有树才有
    this.init();
  },
  methods: {
    async init() {
      this.getEleDeatil();
      this.getProjectList();
      this.geTreeData();
      await this.getTypeMap();

      this.formulaStringToArray();
    },

    geTreeData(){
      if(this.pid){
        findProjectTree(this.pid, this.wbsid).then((res) => {
          this.treeData = res.data.data;
          this.defaultExpanded = [this.nodeid];
        })
      }else{
        getAlltree(this.userInfo.tenant_id, 1, this.wbsid).then((res) => {
          this.treeData = res.data.data;
          this.defaultExpanded = [this.nodeid];
        })
      }
    },

    //懒加载树
    loadNode(node, resolve) {
      let pid = 0;
      if (node.level != 0) {
        pid = node.data.id;
      }
      getLazytree(this.wbsid, pid, this.userInfo.tenant_id).then((res) => {
        let arr = [];
        if (Array.isArray(res.data.data)) {
          arr = res.data.data;
        }
        return resolve(arr);
      });
    },

    //获取项目列表
    getProjectList() {
      getProjectList(1, 999).then((res) => {
        this.projectList = res.data.data.records;
      });
    },

    //选择公式处理
    handleSelect(index,indexPath) {
      //console.log(index,'index')
      //console.log(indexPath,'indexPath')
      if(this.operationVisible){
        this.openerationSelect(index,indexPath)
      }else{
        this.equationSelect(index,indexPath)
      }
    },

    //在选择元素模式下点选计算式
    openerationSelect(index,indexPath){
      if(indexPath[0]!='基础运算'){
        this.$message({
          type: "warning",
          message: "当前只能使用基础运算"
        });
        return;
      }
      let formulaindex = Number(indexPath[1].split('-')[1])-1;
      this.eleAddFormulaHandle(this.formulaList[indexPath[0]][formulaindex]);
    },

    //溯源项目id切换
    projectChange(id) {
      for (let i = 0; i < this.projectList.length; i++) {
        if (id == this.projectList[i].id) {
          this.curProjiect = this.projectList[i];
          //根据项目id获取合同段列表
          findContractByProjectId(this.curProjiect.id).then((res) => {
            this.contractList = res.data.data;
            this.contractId = "";
          });
          return;
        }
      }
    },

    operationEdit(){
      this.selectEleFormula= JSON.parse(JSON.stringify(this.processFormula));
      this.operationVisible = true;
    },

    eleAddFormula(){
      for (let i = 0; i < this.eleList.length; i++) {
        if (this.eleList[i].checked) {
          this.eleAddFormulaHandle(this.eleList[i]);
          break;
        }
      }
    },

    eleChang(value,item){
      //console.log(value)
      //console.log(item)
      if(value){
        //简单语法判断
        if(this.selectEleFormula.length != 0 && this.deleEleIndex < 0){
          let lastEle = this.selectEleFormula[this.selectEleFormula.length-1];
          if(lastEle.type == 'Element'){
            this.$message({
              type: "warning",
              message: "元素无法连续出现在元素后面"
            });
            item.checked = false;
            return;
          }
          if(lastEle.type == 'Text'){
            this.$message({
              type: "warning",
              message: "元素无法连续出现在输入值后面"
            });
            item.checked = false;
            return;
          }
          if(lastEle.type == 'Brackets' && lastEle.name == ')'){
            this.$message({
              type: "warning",
              message: "元素无法连续出现在右括号后面"
            });
            item.checked = false;
            return;
          }
        }

        this.eleAddFormulaHandle(item);
      }else{
        let index = -1;
        for (let i = 0; i < this.selectEleFormula.length; i++) {
          if(this.selectEleFormula[i].id == item.id){
            index = i;
            break;
          }
        }
        if(index>-1){
          this.selectEleFormula.splice(index,1);
        }
      }
    },

    //快捷添加运算符号
    addOperator(operator){
      this.eleAddFormulaHandle(this.formulaMap[operator]);
    },

    //把元素加到公式里
    eleAddFormulaHandle(ele){
      if(ele.tableElementKey){
        //元素
        if(this.deleEleIndex > -1 && this.selectEleFormula.length-1 >= this.deleEleIndex){
          //删除元素的位置，如果下次添加元素，先加到这个位置
          this.selectEleFormula.splice(this.deleEleIndex,0,{
            type:'Element',
            name:ele.eName,
            id:ele.id,
            selected:false,
            tableElementKey:ele.tableElementKey,
            children:[],
          })
          this.deleEleIndex = -1;
        }else{
          this.selectEleFormula.push({
            type:'Element',
            name:ele.eName,
            id:ele.id,
            selected:false,
            tableElementKey:ele.tableElementKey,
            children:[],
          })
          this.deleEleIndex = -1;
        }

      }else if(ele.template && ele.example){

        //简单语法判断
        if(this.selectEleFormula.length == 0){
          this.$message({
            type: "warning",
            message: "公式开头不能是运算符号"
          });
          return;
        }else{
          let lastEle = this.selectEleFormula[this.selectEleFormula.length-1];
          if(lastEle.type == 'Operator'){
            this.$message({
              type: "warning",
              message: "运算符号无法连续出现在运算符号后面"
            });
            return;
          }
          if(lastEle.type == 'Brackets' && lastEle.name == '('){
            this.$message({
              type: "warning",
              message: "运算符号无法连续出现在左括号后面"
            });
            return;
          }
        }

        //运算符号
        this.selectEleFormula.push({
          type:'Operator',
          name:this.symbolReg.exec(ele.name)[1],
          selected:false,
          template:ele.template
        })
      }else if(ele.type == 'Brackets'){
        //括号
        this.selectEleFormula.splice(ele.selectIndex,0,{
          type:'Brackets',
          name:ele.name,
          selected:false,
        })
      }else if(ele.type == 'Text'){
        //输入值
        this.selectEleFormula.push({
          type:'Text',
          name:ele.name,
          selected:false,
        })
      }else if(ele.k){
        //节点参数
        this.selectEleFormula.push({
          type:'ParamData',
          name:ele.name,
          selected:false,
          id:ele.id,
          v:ele.v,
          k:ele.k,
          children:[],
        })
      }
    },

    //添加括号
    addBrackets(text,type){
      //type 是true 表示在元素右边插入
      if(this.curSeleEleIndex == Number(this.curSeleEleIndex)){
        this.eleAddFormulaHandle({
          type:'Brackets',
          name:text,
          selectIndex:type?Number(this.curSeleEleIndex)+1:this.curSeleEleIndex
        })
        //如果在左边插入index要增1
        if(!type){
          this.curSeleEleIndex = Number(this.curSeleEleIndex)+1;
        }
      }
    },


    addText(){
      this.inputVisible = true;
    },
    //添加输入值
    addTextHandle(){
      //简单语法判断
      if(this.selectEleFormula.length != 0){
        let lastEle = this.selectEleFormula[this.selectEleFormula.length-1];
        if(lastEle.type == 'Element'){
          this.$message({
            type: "warning",
            message: "输入值无法连续出现在元素后面"
          });
          return;
        }
        if(lastEle.type == 'Text'){
          this.$message({
            type: "warning",
            message: "输入值无法连续出现在输入值后面"
          });
          return;
        }
        if(lastEle.type == 'Brackets' && lastEle.name == ')'){
          this.$message({
            type: "warning",
            message: "输入值无法连续出现在右括号后面"
          });
          return;
        }
      }

      this.eleAddFormulaHandle({
        type:'Text',
        name:this.inputText
      })
      this.inputVisible = false;
    },

    //勾选元素
    eleCheckHandle(checked,item){
      if(checked){
        this.eleList.forEach((ele)=>{
          this.$set(ele,'checked',false);
          //ele.checked = false;
        })
        item.checked = true;
      }
    },

    //点选公式中的元素
    eleFormulaClick({selected,item},index){
      if(selected){
        this.selectEleFormula.forEach((ele)=>{
          ele.selected = false;
        })
        item.selected = true;
        this.curSeleEleIndex = index;
      }else{
        this.curSeleEleIndex = -1;
      }
    },

    //取消勾选
    unCheckEleFormulac(eleId){
      for (let i = 0; i < this.eleList.length; i++) {
        if(this.eleList[i].id == eleId){
          this.eleList[i].checked = false;
        }
      }
    },

    //删除点选公式中的元素
    removeSelect(){
      if(this.curSeleEleIndex > -1 && this.curSeleEleIndex <= this.selectEleFormula.length-1){
        if(this.selectEleFormula[this.curSeleEleIndex].type == 'Element'){
          //删除元素的位置，如果下次添加元素，先加到这个位置
          this.deleEleIndex = this.curSeleEleIndex;
          this.unCheckEleFormulac(this.selectEleFormula[this.curSeleEleIndex].id)
        }
        this.selectEleFormula.splice(this.curSeleEleIndex,1);
        //this.curSeleEleIndex = -1;
      }
    },

    //赋值给等号右边的数组
    operationHandle(){
      //检测左右括号数量是否相等
      let lBracketNum = 0;
      let rBracketNum = 0;
      this.selectEleFormula.forEach((ele)=>{
        if(ele.type == 'Brackets'){
          if(ele.name == '('){
            lBracketNum++;
          }else if(ele.name == ')'){
            rBracketNum++;
          }
        }
      })
      if(lBracketNum != rBracketNum){
        this.$message({
          type: "warning",
          message: "左右括号数量不相等,请先检查是否正确"
        });
        return;
      }


      this.processFormula = JSON.parse(JSON.stringify(this.selectEleFormula));
      this.operationVisible = false;
    },

    //点选等式中的元素
    equationClick({selected,item},index,arrName){
      if(selected){
        this.resultFormula.forEach((ele)=>{
          ele.selected = false;
        })
        this.processFormula.forEach((ele)=>{
          ele.selected = false;
        })
        this.processSelectIndex = index;
        this.processType = arrName;
        item.selected = true;

        if(this.showFunDetail){
          //切到第一个
          this.actiFunIndex = '0';
        }
      }else{
        this.processType = '';
      }
    },

    //在等式模式下点选计算式
    equationSelect(index,indexPath){
      if(!this.equationSelectEle ||(this.equationSelectEle && !(this.equationSelectEle.type == 'Element' || this.equationSelectEle.type == 'ParamData')) ){
        this.$message({
          type: "warning",
          message: "请先选中元素"
        });
        return;
      }

      let formulaindex = Number(indexPath[1].split('-')[1])-1;
      let expression = this.formulaList[indexPath[0]][formulaindex];
      if(expression.type ==1){
        return;
      }
      //console.log(JSON.parse(expression.template));
      let obj = Object.assign({}, expression);
      //obj.template = JSON.parse(obj.template);
      obj.arguments = new Array(obj.template.args.length);

      let ele = {};
      if(this.equationSelectEle.type == 'ParamData'){
        ele = {
          type:'ParamData',
          name:this.equationSelectEle.name,
          id:this.equationSelectEle.id,
          selected:false,
          v:this.equationSelectEle.v,
          k:this.equationSelectEle.k,
        }
      }else{
        ele = {
            id:this.equationSelectEle.id,
            name:this.equationSelectEle.name,
            selected:false,
            tableElementKey:this.equationSelectEle.tableElementKey,
            type:"Element",
        };
      }

      obj.arguments[0] = ele;
      this.equationSelectEle.children.push(obj);
      //跳转到最新的标签
      this.actiFunIndex = (this.equationSelectEle.children.length-1).toString();
    },

    //选择元素
    chooseEleHandle(){
      for (let i = 0; i < this.eleList.length; i++) {
        if (this.eleList[i].checked) {
          let ele = this.eleList[i];
          let obj = {};
          if(ele.k){
            obj = {
              type:'ParamData',
              name:ele.name,
              id:ele.id,
              selected:false,
              v:ele.v,
              k:ele.k,
              children:[],
            }
          }else{
            obj = {
              type:'Element',
              name:ele.eName,
              id:ele.id,
              selected:false,
              tableElementKey:ele.tableElementKey,
              children:[],
            }
          }

          
          this.$set(this.argumenObj.arguments,this.argumenObj.index,obj);
          this.chooseEleVisible = false;
          break;
        }
      }
    },

    //显示选择元素弹窗
    showChooseEle(argumenObj){
      this.argumenObj = argumenObj;
      this.chooseEleVisible = true;
    },

    //移除挂载的函数
    removeFun(name){
      //console.log(name)
      this.equationSelectEle.children.splice(Number(name), 1);
    },

    //切换公式tab标签
    funLeave(activeName, oldActiveName){
      if(oldActiveName){
        let formula = this.equationSelectEle.children[Number(oldActiveName)];
        if(formula){
          return this.checkFormulaLegal(formula);
        }
      }

    },

    //检测公式合法
    checkFormulaLegal(formula){
      if(!formula.arguments){
        return false;
      }

      //当前选中的元素
      let curEle = this.equationSelectEle;
      let isIn = false;
      for (let i = 0; i < formula.arguments.length; i++) {
        if(Array.isArray(formula.arguments[i])){
          for(let j=0;j<formula.arguments[i].length;j++){
            if(formula.arguments[i][j] && formula.arguments[i][j].id ==curEle.id){
              isIn = true;
              break;
            }
          }
          if(isIn){
            break;
          }
        }else if(formula.arguments[i] && formula.arguments[i].id ==curEle.id){
          isIn = true;
          break;
        }
      }
      if(!isIn){
        this.$message({
          type: "warning",
          message: "参数必须有一个值是当前元素"
        });
        return false;
      }

      return true;
    },

    //保存公式
    saveFormula(){
      let obj = formulaArrayToString(this.processFormula,this.resultFormula);

      //特殊公式会有number
      let number = '';
      for (let i = 0; i < this.processFormula.length; i++) {
        if(this.processFormula[i].children){
          for (let j = 0; j < this.processFormula[i].children.length; j++) {
            if(this.processFormula[i].children[j].number){
              number = this.processFormula[i].children[j].number;
              break;
            }
          }
        }
        if(number){
          break;
        }
      }
      if(number === ''){
        for (let i = 0; i < this.resultFormula.length; i++) {
          if(this.resultFormula[i].children){
            for (let j = 0; j < this.resultFormula[i].children.length; j++) {
              if(this.resultFormula[i].children[j].number){
                number = this.resultFormula[i].children[j].number;
                break;
              }
            }
          }
          if(number){
            break;
          }
        }
      }
      
      //console.log(obj)
      //console.log(text);
      if(this.formulaid){
        updateFormula({
          id:this.formulaid,
          formula:obj.text,
          remark:'',
          wbsId:this.wbsid,
          elementId:this.eleid,
          scale:this.isRetain?this.retainNum:'',
          number:number,
          map:JSON.stringify(obj.eleMap)
        }).then(()=>{
          this.$message({
            type: "success",
            message: "修改成功"
          });
        })
      }else{
        saveFormula({
          formula:obj.text,
          remark:'',
          wbsId:this.wbsid,
          elementId:this.eleid,
          scale:this.isRetain?this.retainNum:'',
          number:number,
          map:JSON.stringify(obj.eleMap)
        }).then((res)=>{
          if(res.data.data){
            this.formulaid = res.data.data;
          }
          this.$message({
            type: "success",
            message: "保存成功"
          });
        })
      }

    },

    //把公式文本还原数组
    async formulaStringToArray(){
      let detail = (await formulaDetail({elementId:this.eleid})).data.data;
      console.log(detail);
      if(detail.id){
        this.formulaid = detail.id;
        //let formula = formulaStringToArray('FC.sum(FC.repeat(E[测试测试_222]))+FC.ifelse(3<E[测试测试_333]&&E[测试测试_333]<10,E[测试测试_222]+E[测试测试_333],E[测试测试_333])',detail.map,this.formulaMap);
        let formula = formulaStringToArray(detail.formula,detail.map,this.formulaMap);
        this.processFormula = formula.processFormula;
        formula.resultFormula[0].id = this.resultFormula[0].id;
        formula.resultFormula[0].name = this.resultFormula[0].name;
        formula.resultFormula[0].tableElementKey = this.resultFormula[0].tableElementKey;
        this.resultFormula[0].children = formula.resultFormula[0].children;
      }

      if(detail.scale > -1){
        this.isRetain = true;
        this.retainNum = detail.scale;
      }
    },


    //设置动态组件里面的元素
    setComponentEle(value,item,index){
      if(value){
        //console.log(this.$refs.dynamiccomponent[index])
        this.$refs.dynamiccomponent[index].setELe(item);
      }
    },

    getNodeDetail(data) {
      if(this.pid){
        wbsPrivateGetNodeTabAndParam(data.id, this.pid, this.wbsid).then((res) => {
          if(res.data.data.tabData.length){
            this.eleTableList = res.data.data.tabData;

            this.eleTableId = this.eleTableList[0].id;
            this.getTableEle(this.eleTableId);
          }else{
            this.eleTableList = [];
            this.eleTableId = '';
            this.eleList = [];
          }

          if(res.data.data.paramData.length){
            this.paramDataList = res.data.data.paramData;
          }else{
            this.paramDataList = [];
          }
        })
      }else{
        getNodeTabAndParam(data.id).then((res)=>{
          if(res.data.data.tabData.length){
            this.eleTableList = res.data.data.tabData;

            this.eleTableId = this.eleTableList[0].id;
            this.getTableEle(this.eleTableId);
          }else{
            this.eleTableList = [];
            this.eleTableId = '';
            this.eleList = [];
          }

          if(res.data.data.paramData.length){
            this.paramDataList = res.data.data.paramData;
          }else{
            this.paramDataList = [];
          }
        })
      }
    },

    getEleDeatil(){
      getEleDeatil(this.eleid).then((res)=>{
        let ele = res.data.data;
        this.resultFormula = [{
          type:'Element',
          name:ele.eName,
          id:ele.id,
          selected:false,
          tableElementKey:ele.tableElementKey,
          children:[],
        }]
      })
    },

    getTableEle(tableId){
      if(tableId === '选择节点参数'){
        this.eleList = this.paramDataList;
      }else{
        selectFormElements(tableId).then((res)=>{
          this.eleList = res.data.data;
        })
      }
    },

    //方法下面的点击树节点
    getNodeDetailComp(data) {
      if(this.pid){
        wbsPrivateGetNodeTabAndParam(data.id, this.pid, this.wbsid).then((res) => {
          if(res.data.data.tabData.length){
            this.eleTableListComp = res.data.data.tabData;

            this.eleTableIdComp = this.eleTableListComp[0].id;
            this.getTableEleComp(this.eleTableIdComp);
          }else{
            this.eleTableListComp = [];
            this.eleTableIdComp = '';
            this.eleListComp = [];
          }
          
          if(res.data.data.paramData.length){
            this.paramDataList = res.data.data.paramData;
          }else{
            this.paramDataList = [];
          }
        })
      }else{
        getNodeTabAndParam(data.id).then((res)=>{
          if(res.data.data.tabData.length){
            this.eleTableListComp = res.data.data.tabData;

            this.eleTableIdComp = this.eleTableListComp[0].id;
            this.getTableEleComp(this.eleTableIdComp);
          }else{
            this.eleTableListComp = [];
            this.eleTableIdComp = '';
            this.eleListComp = [];
          }

          if(res.data.data.paramData.length){
            this.paramDataList = res.data.data.paramData;
          }else{
            this.paramDataList = [];
          }
        })
      }
    },

    //方法下面的查询元素
    getTableEleComp(tableId){
      if(tableId === '选择节点参数'){
        this.eleListComp = this.paramDataList;
      }else{
        selectFormElements(tableId).then((res)=>{
          this.eleListComp = res.data.data;
        })
      }
    },

    //取消方法下面 元素勾选
    unCheckEleComp(eleId){
      //console.log(eleId)
      for (let i = 0; i < this.eleListComp.length; i++) {
        if(this.eleListComp[i].id == eleId){
          this.eleListComp[i].checked = false;
        }
      }
    },

    //手写模式
    handwrit(){
      try {
        let obj = formulaArrayToString(this.processFormula,this.resultFormula);
        this.handwritText = obj.text;
        this.handwritEleMap = JSON.stringify(obj.eleMap);
        this.handwritVisible = true;
      } catch (error) {
        console.error(error)
        this.$message({
          type: "error",
          message: "生成公式文本失败,"+error
        });
      }
    },

    //转成配置用的数组
    handwritTransform(){
      try {
        let formula = formulaStringToArray(this.handwritText,this.handwritEleMap,this.formulaMap);
        this.processFormula = formula.processFormula;
        formula.resultFormula[0].id = this.resultFormula[0].id;
        formula.resultFormula[0].name = this.resultFormula[0].name;
        formula.resultFormula[0].tableElementKey = this.resultFormula[0].tableElementKey;
        this.resultFormula[0].children = formula.resultFormula[0].children;
        this.handwritVisible = false;
      } catch (error) {
        console.error(error)
        this.$message({
          type: "error",
          message: "转成配置用的数组失败,"+error
        });
      }

    },

    editorInit: function (editor) {
        console.log('editorInit')
        require('brace/ext/searchbox') //添加搜索功能
        require('brace/ext/language_tools') //language extension prerequsite...
        require('brace/mode/javascript')    //language
        require('brace/theme/github')
        require('brace/snippets/javascript') //snippet

        editor.session.setUseWrapMode(true);//切换自动换行
        editor.setHighlightActiveLine(false);//设置行高亮显示
        editor.setShowPrintMargin(false);
        editor.setOptions({
          enableLiveAutocompletion:true,//语法提示和补全
          showInvisibles:true,//显示隐藏，空格，回车等
          fontSize:'16px'
        })
    },

    getTypeMap(){
      return new Promise((resolve)=>{
        getTypeMap().then((res)=>{
          //console.log(res)
          this.formulaList = res.data.data;

          //生成map，方便查找
          for (let key in this.formulaList) {
            if(typeof(this.formulaList[key]) == 'object'){
              this.formulaList[key].forEach((formula)=>{
                formula.template =  JSON.parse(formula.template);
                if(this.operatorReg.test(formula.template.ft)){
                  this.formulaMap[formula.template.ft] = formula;
                }else if(this.startFCRegExp.test(formula.template.ft)){
                  let regRes = formula.template.ft.match(this.startFCRegExp);
                  this.formulaMap[regRes[0]] = formula;
                }
              })
            }
          }
        }).finally(() => {
          resolve();
        })
      })
    }
  },
};
</script>

<style scoped lang="scss">
.box-dashed {
  border: 1px dashed #bbbbbb;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 10px;
}
.retain-box {
  border-right: 1px dashed #bbbbbb;
}
.retain {
  line-height: 50px;
  margin-right: 10px;
}
.edit-text {
  font-size: 26px;
  margin-left: 20px;
}

.el-menu--popup .el-menu-item.is-active {
  background-color: #fff;
}
.ele-box{
  //border: 1px solid #bbb;
  //height: 26px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
}
.no-mb-col .el-col{
  margin-bottom: 0px;
  border: 1px solid #bbb;
  height: 100px;
}
.sele-ele-box{
  height: 160px;
  padding: 20px;
  // margin-top: 10px;
}

.icon-box .el-link{
  font-size: 24px;
  margin-right: 10px;
}
</style>

<style lang="scss">
.basic-container.h-basic-full {
  height: calc(100% - 30px);
  overflow: auto;
  .el-card, .el-card .el-card__body {
    height: 100%;
  }
}
</style>
