<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">
              <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">
            <div class="flex" style="justify-content: space-between;width:100%">
               <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表" style="width:45%">
                <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.pkeyId!==-1?item.pkeyId:item.id"></el-option>
              </el-select>
              <!-- 搜索元素下拉框 -->
              <el-select v-model="input3" filterable clearable placeholder="搜索元素字段1"  @change="getInput" style="width:45%">
              <el-option
                v-for="item in eleList1"
                :key="item.id"
                :label="item.eName"
                :value="item.eName">
              </el-option>
              </el-select>
            </div>
           
            <div class="mg-t-10 no-mb-col flex1 ov-hidden">
              <el-scrollbar style="height: 100%">
                <el-row v-loading="eleListable"  v-if="eleList.length>0">
                  <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-row v-else style="text-align: center;line-height: 328px;border:1px solid #bbb">暂无数据</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" style="height:50px">
              <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-if="!operationVisible">
      <div class="box-dashed" style="padding:10px" >
       函数公式运算执行溯源 <el-button type="info" @click="searchElement" v-if="!elementTbinfo">查询</el-button>
          <el-button type="info" @click="searchElement1" v-if="elementTbinfo">收起</el-button>
         
       
        
          <!-- <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> -->
          
       
         <div>
            <div class="box-dashed-1"  v-if="elementTbinfo">
            <span>
              <span
                style="cursor: pointer;font-size:20px"
                v-bind:class="{'span-select':index===nowtitleIndex}"
                v-for="(item,index) in processFormula" :key="index" 
                :item="item" @click="equationClicksouce(item,index)"
                :isShow="true"
              >
              {{item.name}}
              </span>
            </span>
        
             
          
            </div>
            <div class="box-dashed-1-tabinfo" v-if="istabinfo&&elementTbinfo">
                <div class="left_box">
                    <el-descriptions class="margin-top"  :column="1" size="large" border > 
                      <el-descriptions-item>
                        <template slot="label">
                          元素表名称
                        </template>
                          <span style="color: rgba(64,149,229,1);font-weight:bold;cursor: pointer;" @click="eleTbaleName">  {{checkFormula[0]['initTableName']}}</span>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                      
                          元素名称
                        </template>
                       <span >{{checkFormula[0]['name']}}</span>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                    
                          数据类型
                        </template>
                           {{checkFormula[0]['eType']}}
                      </el-descriptions-item>
            
                      <el-descriptions-item>
                        <template slot="label">
                        
                          长度
                        </template>
                       {{checkFormula[0]['eLength']}}
                      </el-descriptions-item>
                    </el-descriptions>
                  
                           <div class="formula-title"> 嵌套公式：</div>
                        <div class="formula-box">
                            <div class="formula-list-box" v-for="(item,index) in innerFormulaList" :key="index"  @click="checkInnerList(item,index)">
                                <span class="formula-list"    v-if="item&&item['children']&&item['children'].length>0" v-bind:class="{'span-select':index===nowIndex}"> {{'（'+Number(index+1)+')'}}{{item['children'][0]['name']}}</span> 
                                <div class="formula-detail"   v-if="index===nowIndex">
                                          <component 
                                          style="font-size:12px"
                                          ref="dynamiccomponent" 
                                          v-if="item&&item['children']&&item['children'].length>0"
                                          v-bind:is="componentMap[item['children'][0]['name']]" 
                                          :formulainfo="item['children'][0]" 
                                          :curele="equationSelectEle" 
                                          :formulamap="formulaMap" 
                                          @uncheck="unCheckEleComp" 
                                          :isShow="false"
                                          :inputSize="'small'"
                                          class="flex1">
                                          </component>
                                          <div class="formula-detail-element">
                                              <el-descriptions class="margin-top"  :column="1" size="mini" border > 
                                                  <el-descriptions-item>
                                                    <template slot="label">
                                                  
                                                      元素表名称
                                                    </template>
                                                      <span style="color: rgba(64,149,229,1);font-weight:bold;cursor: pointer;"  @click="eleTbaleName">  {{checkFormula[0]['initTableName']}}</span>
                                                  </el-descriptions-item>
                                                  <el-descriptions-item>
                                                    <template slot="label">
                                                  
                                                      元素名称
                                                    </template>
                                                  <span >{{checkFormula[0]['name']}}</span>
                                                  </el-descriptions-item>
                                                  <el-descriptions-item>
                                                    <template slot="label">
                                                
                                                      数据类型
                                                    </template>
                                                      {{checkFormula[0]['eType']}}
                                                  </el-descriptions-item>
                                        
                                                  <el-descriptions-item>
                                                    <template slot="label">
                                                    
                                                      长度
                                                    </template>
                                                  {{checkFormula[0]['eLength']}}
                                                  </el-descriptions-item>
                                                </el-descriptions>
                                          </div>
                                </div>
                              
                            </div>
                   
                    </div>
               
                    
                      
                </div>
               
                  <div class="right_box"  >
                    <div class="parent"  id='parent'   ></div>
                      <div v-if="!ishowExcel" style="margin-top:40px">
                        <el-result title="请选择左侧对应的元素表名称，回显表单坐标定位信息" >
                              <template slot="icon">
                                <img src="/img/welIndex/empty.png" alt="loading">
                                    
                              </template>
                            
                          </el-result>
                      </div>
                  </div>
                  
                
            </div>
         </div>
      </div>
    </div>
    <div v-if="!operationVisible && showFunDetail&&!elementTbinfo" 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">
                  <el-scrollbar style="height: 400px">
                    <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>
                <div v-show="item.showSelectEle"  style="width:60%">
                  <div  class="flex" style="justify-content: space-between;width:100%">
                        <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素表" style="width:45%">
                        <el-option v-if="paramDataList.length" label="选择节点参数1" value="选择节点参数"></el-option>
                        <el-option  v-for="item in eleTableListComp" :key="item.id" :label="item.tableName" :value="item.pkeyId!==-1?item.pkeyId:item.id"></el-option>
                      </el-select>
                      <!-- 搜索元素下拉框 -->
                      <el-select v-model="input3" filterable placeholder="搜索元素字段2"  @change="getInput1" style="width:45%">
                      <el-option
                        v-for="item in eleListComp1"
                        :key="item.id"
                        :label="item.eName"
                        :value="item.eName">
                      </el-option>
                      </el-select>
                  </div>
                  
                  <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">
            <el-scrollbar style="height: 400px">
              <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>
        <div v-show="deviationRange.showSelectEle"  style="width:60%">
           <div  class="flex" style="justify-content: space-between;width:100%">
                <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素表" style="width:45%">
                <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.pkeyId!==-1?item.pkeyId:item.id"></el-option>
              </el-select>
           <!-- 搜索元素下拉框 -->
              <el-select v-model="input3" filterable clearable placeholder="搜索元素字段3"  @change="getInput1" style="width:45%">
                  <el-option
                    v-for="item in eleListComp1"
                    :key="item.id"
                    :label="item.eName"
                    :value="item.eName">
                  </el-option>
              </el-select>
           </div>
       
          <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">
              <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">
             <div  class="flex" style="justify-content: space-between;width:100%">
               <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表">
                <el-option v-if="paramDataList.length" label="选择节点参数3" value="选择节点参数"></el-option>
                <template v-if="pid">
                    <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.pkeyId!==-1?item.pkeyId:item.id"></el-option>
                </template>
                <template v-else>
                    <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
                </template>
              
              </el-select>
              <!-- 搜索元素下拉框 -->
                <el-select v-model="input3" filterable clearable placeholder="搜索元素字段4"  @change="getInput" style="width:45%">
                <el-option
                  v-for="item in eleList1"
                  :key="item.id"
                  :label="item.eName"
                  :value="item.eName">
                </el-option>
                </el-select>
             </div>
            

            <div class="mg-t-10 mg-b-10 no-mb-col">
              <el-scrollbar style="height: 460px">
                <el-row v-loading="eleListable"  v-if="eleList.length>0">
                  <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-row v-else style="text-align: center;line-height: 328px;border:1px solid #bbb">暂无数据</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 formulaItemCopy from "./component/formulaItem copy"
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 { getDictionary } from "@/api/system/dict";
import {formulaArrayToString} from "./formulaArrayToString"
import {formulaStringToArray} from "./formulaStringToArray"
import {getExcelHtml} from "@/api/exctab/excelmodel"

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

export default {
  components: {
    draggable,
    formulaItem,
    formulaItemCopy,
    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
    },
    nodeid:{
      type:String,
      default:''
    },
    pid:{
      type:String,
      default:''
    },
    fromcurNode:{
      type:Object,
      default:() => ({})
    }
  },
  data() {
    return {
      // wbsid: "", //从哪个wbs树过来的
      // eleid: "", //元素id
      // nodeid:'',//所在树节点id
      // pid:'',//项目id 私有树才有
      formulaid:'',

      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 || (data.isExistForm==1);
        },
      },
      eleTableId:'',//选中的元素表id
      eleTableList:[],
      eleList:[],
      eleChecks:[],//勾选的元素列表
      selectEleFormula:[],
      curSeleEleIndex:-1,//公式文字里面选中的元素索引
      inputVisible:false,//输入弹窗
      inputText:"",//输入值
      deleEleIndex:-1,//删除元素的位置，如果下次添加元素，先加到这个位置

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

      symbolReg:/(\+|-|\*|\/)（.+）/,
      operatorReg : /^\+|-|\*|%/,//加减乘除
      startFCRegExp : /^FC\.([a-zA-Z0-9]+)\(/,// 匹配开始的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,//版本号，以后可能会有不兼容旧公式的改动，留作以后可能用来判断
      input3:'',//搜索元素字段
      eleListable:false,
      activeNames: ['1'],
      elementTbinfo:false,
      istabinfo:false,
     stringTypeList:[],
     checkFormula:[{initTableName:''}],
     checkid:'',
     nowIndex:'',
     innerFormulaList:[
       {title:'公式配置',selected:false},
       {title:'公式配置',selected:false},
       {title:'公式配置',selected:false},
     ],
     isShowDetail:false,
     nowtitleIndex:'',
     nowEleitem:{},
     ishowExcel:false
    };
  },
  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.pid;//项目id 私有树才有
    
    this.init();
  },
  methods: {
    async init() {
      this.getStringTypelist()
      this.getEleDeatil();
      this.getProjectList();
      this.geTreeData();
      await this.getTypeMap();
      this.formulaStringToArray();
      
    },

    geTreeData(){
      this.treeLoad = true;
      if(this.pid){
        findProjectTree(this.pid, this.wbsid).then((res) => {
          this.treeLoad = false;
          this.treeData = res.data.data;
          this.defaultExpanded = [this.nodeid];
          
          this.$nextTick(()=>{
            let isArray = Array.isArray(this.$refs.tree)
            if (isArray) {
              // 根据 id 获取节点信息
              this.$refs.tree[0].setCurrentKey(this.nodeid);
            } else {
                this.$refs.tree.setCurrentKey(this.nodeid);
            }
              this.getNodeDetail(this.fromcurNode)
              this. getNodeDetailComp(this.fromcurNode)
          })
          
        })
      }else{
        getAlltree(this.userInfo.tenant_id, 1, this.wbsid).then((res) => {
          this.treeLoad = false;
          this.treeData = res.data.data;
          this.defaultExpanded = [this.nodeid];
           console.log(this.$refs.tree,'tree');
          this.$nextTick(()=>{
            let isArray = Array.isArray(this.$refs.tree)
            if (isArray) {
              // 根据 id 获取节点信息
              this.$refs.tree[0].setCurrentKey(this.nodeid);
            } else {
                this.$refs.tree.setCurrentKey(this.nodeid);
            }
             this.getNodeDetail(this.fromcurNode)
              this. getNodeDetailComp(this.fromcurNode)
          })
          
        })
      }
    },

    //懒加载树
    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){
        console.log(ele,'ele');
        //元素
        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;
    //   }
    // },
    //勾选元素多选
    eleCheckHandle(checked,item){
      if(checked){
        this.eleChecks.push(item);
      }else{
        for (let i = 0; i < this.eleChecks.length; i++) {
          if(this.eleChecks[i].id == item.id){
            this.eleChecks.splice(i,1);
            break;
          }
        }
      }
    },

    //点选公式中的元素
    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(arrName==='resultFormula'){
            // this.elementTbinfo=true
        }else{
          //  this.elementTbinfo=false
        }

        if(this.showFunDetail){
          //切到第一个
          this.actiFunIndex = '0';
        }
     
      }else{
        this.processType = '';
      }
        this.innerFormulaList=this.processFormula//内部元素嵌套公式
    },
    //显示函数公式溯源
    searchElement(){
      if(this.processType==='resultFormula'){
        this.elementTbinfo=true
      }else{
          this.elementTbinfo=false
      }
       
    },
    searchElement1(){
      if(this.processType==='resultFormula'){
        this.elementTbinfo=false
      }else{
          this.elementTbinfo=false
      }
       
    },

  //点选公式溯源公式
   equationClicksouce(item,index){
    console.log(item,'item');
    this.nowEleitem=item
    this.nowtitleIndex=index;
    this.istabinfo=true;
    this.checkid=item.id
    console.log(this.processFormula,'this.processFormula');
    this.getEleDeatilList()

  },
    //点击元素表名称回显表单
  eleTbaleName(){
    this.ishowExcel=true
    this.getExcelHtml(this.eleTableList[0].pkeyId).then(()=>{
       let dom = document.getElementById('key_21__3_1')//定位元素位置
       if(dom){
          dom.classList.add("oldlace-bg");
       }
       
    })
  },
    //在等式模式下点选计算式
    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;
    //     }
    //   }
    // },
    //选择元素多选
    chooseEleHandle(){
      this.eleChecks.forEach((element,index) => {
        this.setEleToArgumen(element,index+this.argumenObj.index);
      });

      this.chooseEleVisible = false;

      this.clearEleListCheck();
    },
    //设置元素到指定位置参数
    setEleToArgumen(ele,index){
      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:[],
        }
      }
      if(index < this.argumenObj.arguments.length){
        this.$set(this.argumenObj.arguments,index,obj);
      }
    },
    //清理元素列表的勾选
    clearEleListCheck(){
      this.eleChecks = [];
      this.eleList.forEach((item)=>{
        item.checked = false;
      })
    },

    //显示选择元素弹窗
    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(){
      console.log('保存',this.pid);
      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(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,
          // projectId:this.curProjiect.id||this.projectId,
           projectId:this.curProjiect.id||this.pid,
          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,
          dev:deviationRangeText,
          // projectId:this.curProjiect.id||this.projectId,
           projectId:this.curProjiect.id||this.pid,
          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,projectId:this.curProjiect.id||this.pid})).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);
        console.log(mapObj,'mapObj');
          console.log(formula,'formula');
        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);
      }
    },

    getNodeDetail(data) {
      if(this.pid){
          this.eleListable=true;
          console.log(data.id,'data.id');
        wbsPrivateGetNodeTabAndParam(data.id, this.pid, this.wbsid).then((res) => {
          if(res.data.data.tabData.length){
            this.eleTableList = res.data.data.tabData;
              this.eleListable=false;
            // 获取点击节点的第一张表
            console.log(this.eleTableList[0],'this.eleTableList[0]');
            // let tabId= this.eleTableList[0].initTableId; pkeyId
            let tabId= this.eleTableList[0].pkeyId!==-1?this.eleTableList[0].pkeyId:this.eleTableList[0].id;
            console.log("wbsPrivateGetNodeTabAndParam")
            this.getTableEle(tabId);
            setTimeout(() => {
              // 启动这个指令的DOM结构点击事件
              this.eleTableId = tabId;
            },1000); // 默认1秒
          }else{
            this.eleTableList = [];
            this.eleTableId = '';
            this.eleList = [];
          }

          if(res.data.data.paramData.length){
            this.paramDataList = res.data.data.paramData;
          }else{
            this.paramDataList = [];
          }
        })
      }else{
         this.eleListable=true;
        getNodeTabAndParam(data.id).then((res)=>{
          if(res.data.data.tabData.length){
            this.eleTableList = res.data.data.tabData;
             this.eleListable=false;
            // let tabId= this.eleTableList[0].initTableId;
               let tabId= this.eleTableList[0].pkeyId!==-1?this.eleTableList[0].pkeyId:this.eleTableList[0].id;
               console.log(this.eleTableList[0],'this.eleTableList[0]');
            console.log("getNodeTabAndParam",tabId);
            this.getTableEle(tabId);
            setTimeout(() => {
              // 启动这个指令的DOM结构点击事件
              this.eleTableId = tabId;
            },1000); // 默认1秒
          }else{
            this.eleTableList = [];
            this.eleTableId = '';
            this.eleList = [];
              this.eleListable=false;
          }

          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:[],
          eLength:ele.eLength,
          eType:ele.eType,
          initTableName:ele.initTableName
        }]
      })
    },
   getEleDeatilList(){
      getEleDeatil(this.checkid).then((res)=>{
        let ele = res.data.data;
       
        this.checkFormula = [{
          type:'Element',
          name:ele.eName,
          id:ele.id,
          selected:false,
          tableElementKey:ele.tableElementKey,
          children:[],
          eLength:ele.eLength,
          eType:ele.eType,
          initTableName:ele.initTableName
        }]
         this.checkFormula.forEach((ele=>{
            this.stringTypeList.forEach((item1)=>{
                if(ele.eType==item1.dictKey){
                  ele.eType=item1.dictValue
                }
              })
        }))
      })
    },
    getTableEle(tableId){
      console.log("getTableEle");
      this.input3=''
      if(tableId === '选择节点参数'){
        this.eleList = this.paramDataList;
        this.eleList1 = this.paramDataList;
      }else{
        selectFormElements(tableId,{nodeId:this.nodeid,type:1}).then((res)=>{
          this.eleList = res.data.data;
          this.eleList1 = res.data.data;
        })
      }
    },
    getInput(tableId){
      if(tableId.length>0){
        let arr=[]
        arr=this.eleList1.filter((item)=>{
          if(item.eName===tableId){
            return item
          }
        })
        this.eleList=arr;
      }else{
        this.eleList=this.eleList1
      }
       
    },
    getInput1(tableId){
      if(tableId.length>0){
        let arr=[]
        arr=this.eleListComp1.filter((item)=>{
          if(item.eName===tableId){
            return item
          }
        })
        this.eleListComp=arr;
      }else{
         this.eleListComp=this.eleListComp1;
      }
       
    },

    //方法下面的点击树节点
    getNodeDetailComp(data) {
       console.log(data.id,'data.id111111111');
      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].initTableId;
            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].initTableId;
            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){
        this.input3=''
      if(tableId === '选择节点参数'){
        this.eleListComp = this.paramDataList;
        this.eleListComp1 = this.paramDataList;
      }else{
        selectFormElements(tableId,{type:1}).then((res)=>{
          this.eleListComp = res.data.data;
           this.eleListComp1 = 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;
                }
              })
            }
          }
          console.log( this.formulaList,' this.formulaList');
        }).finally(() => {
          resolve();
        })
      })
    },
    //展开公式
     handleChange(val) {
        console.log(val);
      },
     //获取元素表类型
      getStringTypelist() {
              getDictionary({
                  code: "data_type",
              }).then((res) => {
                  this.stringTypeList = res.data.data;
                  
              });
         
      },
      checkInnerList(item,index){
        console.log(item,'item');
        this.nowIndex=index
        // this.innerFormulaList.forEach((item)=>{
        //   item.selected=false
        // })
       
      },


      //获取表单html
    async getExcelHtml (pkeyId) {
      const { data: res } = await getExcelHtml({ pkeyId })
      if (res.code === 200) {
        localStorage.setItem('excelHtml', res.data)
        this.copss()
       
       
      }
    },
    getInformation (name, tr, td) {//鼠标点击事件
      //console.log(event)
      let tdEle = null;
      //获取TD元素
      if(event.target.nodeName == "TD"){
        tdEle = event.target
      }else{
        tdEle = this.getParentTD(event.target);
      }
      let moreObj = {};
      if(tdEle){
        moreObj = this.getWidget(tdEle);
      }

      this.htmlData = Object.assign({
        name,
        tr,
        td
      },moreObj)
    },

  


    getParentTD(ele){
      let targetParent = ele.parentNode;
      while (targetParent.nodeName !== "TD") {
          if(targetParent.id == 'parent'){
            return null;
          }
          targetParent = targetParent.parentNode;
      }
      return targetParent;
    },


    //获取控件信息
    getWidget(tdEle){
      let checkLabels = tdEle.querySelectorAll('.el-checkbox-group span.el-checkbox__label');
      //console.log(checkLabels)
      if(checkLabels.length > 0){
        let checkLabelDatas = [];
        for (let i = 0; i < checkLabels.length; i++) {
          //console.dir(checkLabels[i])
          checkLabelDatas.push({
            dictValue:checkLabels[i].innerText
          });
        }
        return {
          type:'checkbox',
          checkLabelDatas
        }
      }

      let radioLabels = tdEle.querySelectorAll('.el-radio .el-radio__label');
      if(radioLabels.length > 0){
        let radioDatas = [];
        for (let i = 0; i < radioLabels.length; i++) {
          radioDatas.push({
            dictValue:radioLabels[i].innerText
          });
        }
        return {
          type:'radio',
          radioDatas
        }
      }

      let elSelect = tdEle.querySelectorAll('.el-select');
      //console.dir(elSelect[0])
      if(elSelect.length){
        let options = elSelect[0].__vue__.options;
        let selectDatas = [];
        for (let i = 0; i < options.length; i++) {
          selectDatas.push({
            dictValue:options[i].label
          });
        }
        return {
          type:'select',
          selectDatas
        }
      }

      return {};
    },
    async copss () {
      let _that = this
      var MyComponent = await Vue.extend({
        template: localStorage.getItem('excelHtml'),
        data () {
          return {
            formData: {},
            getTokenHeader: {},
            dap_site_data:{}
          }
        },
        methods: {
          contextmenuClick(tr, td, x1, x2, y1, y2, event) {},
          getInformation (name, tr, td) {//鼠标右键事件
            _that.getInformation(name, tr, td)
          },
          formUploadSuccess(){},
          formUploadExceed(){},
          formUploadLoading(){},
          delTableFormFile(){},
          formUploadError(){},
          uploadprogress(){},
          getRegularExpression(){},
          formRemoteMethod(){},
          checkboxGroupChange(){},
          formRemoteChange(){},
          dateKeydown(){},
          keyupShiftUp() {},
          keyupShiftDown() {},
          keyupShiftLeft() {},
          keyupShiftRight() {},
          inputLeftClick() {},
        }
      })
      var component = new MyComponent().$mount()
      let na = document.getElementById('parent')
      na.innerHTML = `<div
        class='parent'
        id='parent'
      ></div>`
      document.getElementById('parent').appendChild(component.$el);
    },
  }
};
</script>

<style scoped lang="scss">
#parent /deep/ .oldlace-bg {
  background-color: oldlace;
}
.span-select{
  color: rgba(64,149,229,1);
}
.box-dashed {
  border: 1px dashed #bbbbbb;
  border-radius: 6px;
  // padding: 10px;
  margin-bottom: 10px;
}
.box-dashed-1{
  margin-top: 20px;
  width:98%;
  border: 1px dashed #bbbbbb;
  // height: 400px;
  padding: 20px;
}
.box-dashed-1-tabinfo{
 
  height: 500px;
  // border: 1px solid gray;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  .left_box{
   padding: 10px;
    width: 30%;
    height: 100%;
    background-color: rgb(167, 167, 167);
    border-radius: 1%;
  
  }
  .right_box{
    width:68%;
    height:100%;
    padding: 10px;
    margin-left: 20px;
    overflow: auto;
    border-radius: 1%;
    background-color: rgb(218, 218, 218);
  }
}
.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%;
  }
}
.formula-title{
  font-weight: bolder;
  font-size: large;
  margin-top:10px
}
.formula-box{
  height: 280px;
  overflow-y: auto;
}
.formula-list-box{
  margin-top: 10px;

}
.formula-list{
  color: white;
  font-weight: bold;
  cursor: pointer;
}
.formula-list-checked{
  color: blue !important;
  
 }
 .formula-detail{
   margin-top: 10px;
 }
 .formula-detail-element{
   margin-top: 10px;
 }

</style>
