<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 class="retain-box">
          <el-button size="mini" style="margin:10px;margin-top:16px;" @click="deviationRange.show = !deviationRange.show">允许偏差值范围</el-button>
        </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" v-loading="treeLoad" class="h-100p ov-auto">
              <div style="overflow: auto;flex:1;max-height:500px">
                  <div class="flex">
                      <el-input
                        size="small"
                        placeholder="输入关键字搜索"
                        clearable
                        @clear="clearfiltertext"
                        v-model="filterText">
                      </el-input>
                      <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
                    </div>
                <el-tree
                 style="display: inline-block;min-width: 100%;"
                  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"
                 lazy
                  :load="treeLoadNode"
                   v-show="!allTreeShow"

                >
                </el-tree>
                 <el-tree
                  style="width: 100%"
                  ref="treeall"
                  v-loading="treeloading"
                  :data="allTreeData"
                  :props="defaultProps"
                  @node-click="getNodeDetail"
                  node-key="id"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  v-show="allTreeShow"
                >
                </el-tree>
              </div>
            </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="选择节点参数2" value="选择节点参数"></el-option>
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
            </el-select> -->
            <el-select v-model="input3" filterable placeholder="请选择元素字段"  @change="getTableEle"  style="width:100%"  :popper-append-to-body="false">
              <el-option

                v-for="item in eleTableList"
                :key="item.id"
                :label="item.eName"
                :value="item.eName">
              </el-option>
            </el-select>

            <div class="mg-t-10 no-mb-col flex1 ov-hidden" style="height: 360px; overflow-y: auto; max-height: 360px;">
              <el-scrollbar style="height: 100%">
                <el-row v-loading="eleListable">
                  <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>
                       <!-- <span >{{item.title}}</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="canceloperationVisible ">取消</el-button>
          <el-button size="small" @click="operationHandle" type="primary">保存</el-button>

        </div>
      </div>
    </div>
    <div v-show="!operationVisible && !showFunDetail && !deviationRange.show">
      <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" >
              <div class=" flex-d-c"  style="width:40%">
                <component ref="dynamiccomponent" v-bind:is="componentMap[item.name]" :formulainfo="item" :curele="equationSelectEle" :formulamap="formulaMap" @uncheck="unCheckEleComp" class="flex1"></component>
                <div class="flex1" v-show="item.showSelectEle" style="margin-top:10px;margin-bottom:30px">
                  <div class="flex">
                      <el-input
                        size="small"
                        placeholder="输入关键字搜索"
                        clearable
                        @clear="clearfiltertext"
                        v-model="filterText">
                      </el-input>
                      <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
                    </div>
                  <el-scrollbar style="height: 520px">
                    <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"
                      lazy
                      :load="treeLoadNode"
                       v-show="!allTreeShow"
                    >
                    </el-tree>
                    <el-tree
                        style="width: 100%"
                        ref="treeall"
                        v-loading="treeloading"
                        :data="allTreeData"
                        :props="defaultProps"
                        @node-click="getNodeDetailComp"
                        node-key="id"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        v-show="allTreeShow"
                      >
                      </el-tree>
                  </el-scrollbar>
                </div>
              </div>
                <div v-show="item.showSelectEle"  style="width:60%">
                  <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素字段" style="width:100%" filterable>
                    <el-option v-if="paramDataList.length" label="选择节点参数1" value="选择节点参数"></el-option>
                    <el-option  v-for="item in eleTableListComp" :key="item.id" :label="item.eName" :value="item.id"></el-option>
                  </el-select>
                  <div class="mg-t-10 mg-b-10 no-mb-col" style="width:100%">
                    <el-scrollbar style="height:520px;">
                      <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>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 允许偏差值范围 -->
    <div v-if="!operationVisible && !showFunDetail && deviationRange.show" class="flex1">
      <div class="flex">
        <div class=" flex-d-c"  style="width:40%">
          <deviation-range ref="deviationrange" :formulainfo="deviationRange" :formulamap="formulaMap" @uncheck="unCheckEleComp" class="flex1"></deviation-range>
          <div class="flex1" v-show="deviationRange.showSelectEle" style="margin-top:10px;margin-bottom:30px">
             <div class="flex">
                      <el-input
                        size="small"
                        placeholder="输入关键字搜索"
                        clearable
                        @clear="clearfiltertext"
                        v-model="filterText">
                      </el-input>
                      <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
                </div>
            <el-scrollbar style="height: 520px">
              <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"
                lazy
                :load="treeLoadNode"
                v-show="!allTreeShow"
              >
              </el-tree>
                 <el-tree
                  style="width: 100%"
                  ref="treeall"
                  v-loading="treeloading"
                  :data="allTreeData"
                  :props="defaultProps"
                  @node-click="getNodeDetailComp"
                  node-key="id"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  v-show="allTreeShow"
                >
                </el-tree>
            </el-scrollbar>
          </div>
        </div>
        <div v-show="deviationRange.showSelectEle"  style="width:60%">
          <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素表" style="width:100%" filterable>
            <el-option v-if="paramDataList.length" label="选择节点参数" value="选择节点参数"></el-option>
            <el-option  v-for="item in eleTableListComp" :key="item.id" :label="item.eName" :value="item.id"></el-option>
          </el-select>
          <div class="mg-t-10 mg-b-10 no-mb-col" style="width:100%">
            <el-scrollbar style="height:520px;">
              <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 => setDeviationRangeEle(value,item)"></el-checkbox>
                  </div>
                </el-col>
              </el-row>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </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">
                  <div class="flex">
                      <el-input
                        size="small"
                        placeholder="输入关键字搜索表单"
                        clearable
                        @clear="clearfiltertext"
                        v-model="filterText">
                      </el-input>
                      <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
                    </div>
              <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"
                     lazy
                  :load="treeLoadNode"
                 v-show="!allTreeShow"
                >
                </el-tree>
                 <el-tree
                  style="width: 100%"
                  ref="treeall"
                  v-loading="treeloading"
                  :data="allTreeData"
                  :props="defaultProps"
                  @node-click="getNodeDetail"
                  node-key="id"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  v-show="allTreeShow"
                >
                </el-tree>
              </el-scrollbar>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-select v-model="eleTableId" @change="getTableEle1" placeholder="请选择元素字段" filterable style="width:100%">
              <el-option v-if="paramDataList.length" label="选择节点参数3" value="选择节点参数"></el-option>
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.eName" :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 {tabTypeLazyTreeAll} from "@/api/manager/wbsprivate";
import {tabTypeLazyTree} from "@/api/manager/wbsprivate";
import {getTableElments} from "@/api/manager/wbstree";
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 deviationRange from "./component/deviationRange/deviationRange"
import {rangeToString} from "./component/deviationRange/rangeToString"

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


import draggable from 'vuedraggable'
import { log } from '@antv/g2plot/lib/utils';

export default {
  components: {
    draggable,

    formulaItem,
    formulaTemplate,

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

    dateDeviation,
    dateFormat,
    datasRepeat,
    datasReme,
    datasGetlist,
    datasJoin,
    ifelse,
    deviationRange
  },
  props: {
    wbsid:{
      type:String,
      default:''
    },
    eleid:{
      type:String,
      default:''
    },
    globaltype:{
      type:Number,
      default:10
    },
    elementType:{
      type:Boolean,//公有还是私有

    },
    nodeid:{
      type:String,
      default:''
    },
    pid:{
      type:String,
      default:''
    },
    projectid:{
      type:String,
      default:''
    },
    fromcurNode:{
      type:Object,
      default:''
    },
  },
  data() {
    return {
      // wbsid: "", //从哪个wbs树过来的
      // eleid: "", //元素id
      // nodeid:'',//所在树节点id
      // pid:'',//项目id 私有树才有
      filterText:'',//树形控件搜索文字
      allTreeShow:'',//搜索树显示
      formulaid:'',
      treeloading:false,//搜索树加载效果
      allTreeData:[],//过滤树


      treeData:[],//树节点
      treeLoad:false,
      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;
        },
      },
      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:[],//节点参数数组

      deviationRange:{
        show:false,//显示
        showSelectEle:false,//显示选择元素
        datas:{
          symbol:'【min,max】',
          model:'1',
          arguments1:'',
          arguments2:'',
        },
      },//允许偏差值范围

      version:1,//版本号，以后可能会有不兼容旧公式的改动，留作以后可能用来判断
      curData:{},
      curNode:{},
      treeId:'',
      page: {
        size: 10,
        current: 1,
        total: 2
      },
      eleListable:false,
      input3:'',
      rootNodeData: [],
      nodeZero: null,
      resolveZero: null,
      loading: false,
      itemList:[]


    };
  },
  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();
    },



           //#region 接口
    async tabTypeLazyTree (parentId, projectId,current,size,titleName) {//清表树
      const { data: res } = await tabTypeLazyTree({ parentId, projectId,current,size,titleName })
      if (res.code === 200) {
        return res.data;
      }
    },


    //懒加载树
    loadNode(node, resolve) {
     console.log(this.elementType);
       console.log(this.globaltype,'globaltype');
      let parentId = 12345678910;
      if (node.level != 0) {
        parentId = node.data.id;
      }
      if(this.globaltype===1&&!this.elementType){

           tabTypeLazyTreeAll({parentId,current:1,size:1000}).then((res) => {
            let arr = [];
            if (Array.isArray(res.data.data.records)) {
              arr = res.data.data.records;
            }
            return resolve(arr);
          });
      }else if(this.globaltype===1&&this.elementType){

         tabTypeLazyTree({parentId,projectId:this.projectid,pcurrent:1,size:1000}).then((res) => {
            let arr = [];
            if (Array.isArray(res.data.data.records)) {
              arr = res.data.data.records;
            }
            return resolve(arr);
          });

      }

    },
     treeLoadNode(node, resolve){
       let parentId = 12345678910;
      if (node.level != 0) {
        parentId = node.data.id;
      }
        // 开启 “加载中” 动画
        if(node.level == 0) this.loading=true
         if(this.globaltype===1&&!this.elementType){
             tabTypeLazyTreeAll({parentId,current:1,size:1000}).then(res => {
                // 请求接口，返回数据
                let data = res.data.data.records;
                  this.loading=false
                 resolve(data);
                this.$nextTick(() => {
                  let expandid=Number(this.fromcurNode.parentId)-1
                   node.childNodes[expandid].expand();

                    let paramsId = this.fromcurNode.id
                  console.log(paramsId, "paramsId")
                  let isArray = Array.isArray(this.$refs.tree)
                  if (isArray) {
                    // 根据 id 获取节点信息
                    this.$refs.tree[0].setCurrentKey(paramsId);
                  } else {
                    this.$refs.tree.setCurrentKey(paramsId);
                  }

                  this.getNodeDetail(this.fromcurNode)
                  this.getNodeDetailComp(this.fromcurNode)

                })
            })
         }else if(this.globaltype===1&&this.elementType){
          tabTypeLazyTree({parentId,projectId:this.projectid,pcurrent:1,size:1000}).then(res => {
                // 请求接口，返回数据
                let data = res.data.data.records;
                  this.loading=false
                 resolve(data);
                this.$nextTick(() => {
                  console.log(this.fromcurNode,'this.fromcurNode')
                  let expandid=Number(this.fromcurNode.parentId)-1
                   node.childNodes[expandid].expand();
                    let paramsId = this.fromcurNode.id
                    console.log(this.nodeid,'this.initTableId');
                    // 根据 id 获取节点信息
                    // let getNodeById = this.$refs.tree.getNode(paramsId);
                    // if(getNodeById){
                    //     // 设置节点选中
                    //     this.$refs.tree.setCurrentKey(paramsId);
                    //      this.getNodeDetail(this.fromcurNode)
                    //         this.getNodeDetailComp(this.fromcurNode)
                    // }
                     let isArray = Array.isArray(this.$refs.tree)
                  if (isArray) {
                    // 根据 id 获取节点信息
                    this.$refs.tree[0].setCurrentKey(paramsId);
                  } else {
                    this.$refs.tree.setCurrentKey(paramsId);
                  }

                  this.getNodeDetail(this.fromcurNode)
                  this.getNodeDetailComp(this.fromcurNode)
                })
            })
         }


    },

    //搜索树
    treeFilter() {
      console.log('搜索');
      this.eleTableList=[];
      this.eleList=[];
      this.eleListComp=[];
      this.eleTableListComp =[];
      this.eleTableId='';
      this.eleTableIdComp=''
      if (this.filterText&&this.treeId) {
        this.allTreeShow = true;
        this.allTreeData=[]
        if (!this.allTreeData.length) {
          this.treeloading = true;
          if(this.globaltype===1&&!this.elementType){
             let parentId=''
             if(this.curData.hasChildren){
               parentId=this.curData.id
             }else{
                parentId=this.curData.parentId
             }

               tabTypeLazyTreeAll({parentId:parentId,current:1,size:1000,titleName:this.filterText}).then((res) => {
                  this.treeloading = false;
                  this.allTreeData = res.data.data.records;
                    this.$nextTick(() => {
                      console.log("过滤");
                      this.$refs.treeall.filter(this.filterText);
                    });
              })


          }else if(this.globaltype===1&&this.elementType){
             let parentId=''
             if(this.curData.hasChildren){
               parentId=this.curData.id
             }else{
                parentId=this.curData.parentId
             }
             console.log(parentId,'parentId');
                tabTypeLazyTree({parentId:parentId,projectId:this.projectid,pcurrent:1,size:1000,titleName:this.filterText}).then((res) => {
                  this.treeloading = false;
                  this.allTreeData = res.data.data.records;
                });
                this.$nextTick(() => {
                    console.log("过滤");
                    this.$refs.treeall.filter(this.filterText);
                });
          }
        } else {
          this.$refs.treeall.filter(this.filterText);
        }
      } else {
        this.$message.warning('请先选择父节点')
        this.allTreeShow = false;
      }
    },
    clearfiltertext(){
      this.allTreeShow=false;
       this.eleTableList=[];
      this.eleList=[];
      this.eleListComp=[];
      this.eleTableListComp =[];
      this.eleTableId='';
      this.eleTableIdComp=''

    },
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    //获取项目列表
    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){
      if(value){
        //简单语法判断
        if(this.itemList.length != 0 && this.deleEleIndex < 0){
                let lastEle = this.itemList[this.itemList.length-1];
                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.itemList.push(item);
      }else{
           let index = -1;
            for (let i = 0; i < this.itemList.length; i++) {
            if(this.itemList[i].id == item.id){
              index = i;
              break;
            }
          }
          if(index>-1){
            this.itemList.splice(index,1);
          }
      }
    },
    //快捷添加运算符号
    addOperator(operator){

      let lastEle = this.selectEleFormula[this.selectEleFormula.length-1];
      this.itemList.forEach(e => {
        if(this.selectEleFormula.length != 0 && lastEle.type != 'Operator' && lastEle.type != 'Brackets' && lastEle.name != '('){
          this.eleAddFormulaHandle(this.formulaMap[operator]);
        }

        this.eleAddFormulaHandle(e);
      })


      this.itemList=[]
    },
    //插入运算符
   addOperration(text,type){
      //type 是true 表示在元素右边插入
      if(this.curSeleEleIndex == Number(this.curSeleEleIndex)){
        this.eleAddFormulaHandle({
          type:type,
          name:text,
          selectIndex:type?Number(this.curSeleEleIndex)+1:this.curSeleEleIndex
        })
        //如果在左边插入index要增1
        if(!type){
          this.curSeleEleIndex = Number(this.curSeleEleIndex)+1;
        }
      }
    },

    //把元素加到公式里
    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;
      this.allTreeShow=false;
      this.filterText=''
    },

    canceloperationVisible(){
      this.operationVisible=false;
      this.allTreeShow=false;
      this.filterText=''
      this.treeId=''
      this.itemList=[];
      this.eleList.forEach((ele)=>{
          this.$set(ele,'checked',false);
          //ele.checked = false;
      })
      console.log('取消');
    },

    //点选等式中的元素
    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;
      // this.eleList=[];
      // this.eleTableList=[];
      this.eleTableId='';
      this.allTreeShow=false;
      this.filterText=''
       this.eleList.forEach((ele)=>{
          this.$set(ele,'checked',false);
          //ele.checked = false;
        })
      //  this.treeId=''

    },

    //移除挂载的函数
    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);

      let deviationRangeText = rangeToString(this.deviationRange.datas,obj.eleMap);
      obj.eleMap.deviationRangeJson = JSON.stringify(this.deviationRange.datas);
      //console.log(obj.eleMap)
      //return;

      //特殊公式会有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:'',
          nodeId:this.nodeid,
          elementId:this.eleid,
          scale:this.isRetain?this.retainNum:'',
          number:number,
          map:JSON.stringify(obj.eleMap),
          scope:this.globaltype,
          dev:deviationRangeText
        }).then(()=>{
          this.$message({
            type: "success",
            message: "修改成功"
          });
        })
      }else{
        saveFormula({
          formula:obj.text,
          remark:'',
          nodeId:this.nodeid,
          elementId:this.eleid,
          scale:this.isRetain?this.retainNum:'',
          number:number,
          map:JSON.stringify(obj.eleMap),
          scope:this.globaltype,
          projectId:this.curProjiect.id,
          dev:deviationRangeText,
          ver:this.version
        }).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,scope:this.globaltype,nodeId:this.nodeid})).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;

        //允许偏差值范围
        let mapObj = JSON.parse(detail.map);
        if(mapObj.deviationRangeJson){
          this.deviationRange.datas = JSON.parse(mapObj.deviationRangeJson);
        }
      }

      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);
      }
    },

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

    async tabTypeLazyTreeAll ( parentId,current,size,titleName) {//清表树
      console.log(parentId);
      const { data: res } = await tabTypeLazyTreeAll({parentId,current,size,titleName}	)
      if (res.code === 200) {
        return res.data

      }
    },

    getNodeDetail(data,node){
      console.log(data,node,'getNodeDetail');
      this.curNode=node;
      this.curData=data;
      this.treeId=data.initTableId;
       this.page.current=1;
      this.page.currentPage=1;
      this.input3=''
        if(data.hasChildren===false){
           this.eleListable=true;
           getTableElments(data.initTableId ).then((res)=>{
             if(res.data.code==200){
                this.eleList=res.data.data;
                 this.eleTableList =res.data.data;
                this.eleListable=false;
             }
           })
        }
        else{
          this.eleListable=true;
           this.eleList=[]
           this.page.total=0
           setTimeout(() => {
              this.eleListable=false
            }, 1000);
        }


    },



    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){
       let arr=[]
      arr=this.eleTableList.filter((item)=>{
        if(item.eName===tableId){
          return item
        }
      })
      this.eleList=arr;
    },
    getTableEle1(tableId){
       let arr=[]
      arr=this.eleTableList.filter((item)=>{
        if(item.id===tableId){
          return item
        }
      })
      this.eleList=arr;
    },


    getNodeDetailComp(data,node) {
      console.log(1111111111);
       this.treeId=data.initTableId;
       this.curNode=node;
      this.curData=data;
       this.input3=''
        if(data.hasChildren===false){
           getTableElments(data.initTableId ).then((res)=>{
             if(res.data.code==200){
               if(res.data.data.length){
                this.eleListComp=res.data.data;
                this.eleTableListComp =res.data.data;
                console.log( this.eleTableListComp,' this.eleTableListComp');
                this.eleTableIdComp = this.eleTableListComp[0].id;
              ;
               }

             }
           })
        }
        else{

           this.eleListComp=[]
           this.page.total=0

        }
    },

    getTableEleComp(tableId){
       let arr=[]
      arr=this.eleTableListComp.filter((item)=>{
        if(item.id===tableId){
          return item
        }
      })
      this.eleListComp=arr;
    },

    //取消方法下面 元素勾选
    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;
  overflow-y: auto;
  // 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%;
  }
}
 .el-select-dropdown{
        max-width:600px ;
    }
    //.el-select-dropdown__item{
    //    display: inline-block;
    //}
    .el-select-dropdown__item span {
        min-width: 300px;
        display: inline-block;
   }
</style>
