<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>
            <el-input-number v-model="retainNum" :step="1" :min="0" :max="5" :disabled="!isRetain"
              size="mini"></el-input-number>
            <span class="unit">位</span>
          </div>
          <div class="retain-box">
            <el-button size="mini" @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">
          <div>
            <formula-item-big v-for="(item, index) in resultFormula" :key="index" :item="item"
              @click="obj => equationClick(obj, index, 'resultFormula')">
            </formula-item-big>
          </div>
          <span>=</span>
          <span v-for="(item, index) in processFormula" :key="index">
            <el-tooltip class="item" effect="light" placement="top-start" :disabled="item.type !== 'Element'">
              <div slot="content">{{ item.tableName }}</div>
              <formula-item-big :getname="getItemTableName(item)" :item="item"
                @click="obj => equationClick(obj, index, 'processFormula')" :isShowCursor="false">
              </formula-item-big>
            </el-tooltip>
          </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:601px">
                  <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">
              <!-- 放出来的代码——start -->
              <div style="display:flex">
                <el-input placeholder="请输入你想搜索的元素字段" v-model="inputEle" clearable @clear="clearInput"> </el-input>
                <el-button type="primary" icon="el-icon-search" size="small" @click="searchChange">搜索</el-button>
              </div>
              <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>


                        <el-checkbox v-model="item.checked" @change="value => eleChang(value, item)"></el-checkbox>
                      </div>
                    </el-col>
                  </el-row>
                </el-scrollbar>
              </div>
              <!-- 运算符选择区域 -->
              <div class="operation-box">

                <div class="flex jc-sb operation-symbol-box">

                  <div class="icon-box ">
                    <span>插入运算符:</span>
                    <el-link type="primary" @click="addOperator('+')" icon="el-icon-circle-plus-outline"></el-link>
                    <el-link type="primary" @click="addOperator('-')" icon="el-icon-remove-outline"></el-link>
                    <el-link type="primary" @click="addOperator('*')" icon="el-icon-circle-close"></el-link>
                    <el-link type="primary" @click="addOperator('%')">÷</el-link>
                    <el-link type="primary" class="mg-r-10" @click="addBrackets('(', false)">(</el-link>
                    <el-link type="primary" class="mg-r-10" @click="addBrackets(')', true)">)</el-link>
                    <el-link type="primary" @click="addText">固定值</el-link>
                  </div>
                  <div class="flex">
                    <span>操作</span>
                    <el-link icon="el-icon-delete" type="danger" @click="handleDelete"></el-link>
                  </div>
                </div>

                <div class="border-grey sele-ele-box1" tabindex="0" inputmode="none" @keydown.prevent="onKeyDown"
                  @keydown.prevent.left="handleLeftArrow" @keydown.prevent.right="handleRightArrow"
                  @keydown.prevent.delete="handleDelete" @focus="containerFocused = true"
                  @blur="containerFocused = false">
                  <draggable v-model="selectEleFormula" class="pane-box">
                    <formula-item v-for="(item, index) in selectEleFormula" :key="index" :item="item"
                      @click="obj => eleFormulaClick(obj, index)">
                    </formula-item>
                  </draggable>
                </div>

                <div class="flex mg-t-10" style="justify-content: space-between;width:100%;">
                  <!-- <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表1" style="width:45%"
                    size="small">
                    <el-option v-if="paramDataList.length" label="选择节点参数2" value="选择节点参数"></el-option>
                    <el-option v-for="item in eleTableList" :key="item.id" :label="item.title"
                      :value="(item.pkeyId !== null && item.pkeyId !== -1) ? item.pkeyId : item.id"></el-option>
                  </el-select> -->

                  <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 class="mg-t-10 no-mb-col flex1">
                  <el-scrollbar style="height: 450px">

                    <tableFormWrite :pkeyId="eleTableId" @element-selected="handleElementSelected"
                      :initTableName="initTableName" :selectedTableKey="selectedTableKey" :key="1"
                      :container-id="'excel-container-1'"></tableFormWrite>
                  </el-scrollbar>
                </div> -->

              </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" :map="formulaDetailMap"
                    @uncheck="unCheckEleComp" class="flex1" :moreConditions="moreConditions" :isMore="isMore"
                    :isGetData="isGetData" :dataListGet="dataListGet" :isDataChange="isDataChange" :dataForm="dataForm"
                    :remark="remark" :method="method">
                  </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%">
                  <div style="display:flex">
                    <el-input placeholder="请输入你想搜索的元素字段" v-model="inputEleJudge" clearable @clear="clearInputJudge">
                    </el-input>
                    <el-button type="primary" icon="el-icon-search" size="small"
                      @click="searchChangeJudge">搜索</el-button>
                  </div>
                  <div class="mg-t-10 mg-b-10 no-mb-col" style="width:100%">
                    <el-scrollbar style="height:600px;">
                      <el-row v-loading="eleListJudge">
                        <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%">
            <div style="display:flex">
              <el-input placeholder="请输入你想搜索的元素字段" v-model="inputElePian" clearable @clear="clearInputPian"> </el-input>
              <el-button type="primary" icon="el-icon-search" size="small" @click="searchChangePian">搜索</el-button>
            </div>
            <div class="mg-t-10 mg-b-10 no-mb-col" style="width:100%">
              <el-scrollbar style="height:520px;">
                <el-row v-loading="eleListCompLoading">
                  <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">
            <div style="display:flex">
              <el-input placeholder="请输入你想搜索的元素字段" v-model="inputEle" clearable @clear="clearInput"> </el-input>
              <el-button type="primary" icon="el-icon-search" size="small" @click="searchChange">搜索</el-button>
            </div>
            <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 { getProjectList } from "@/api/manager/projectinfo";
import { findContractByProjectId } from "@/api/manager/contractinfo";
import { getDetail as getEleDetail } from "@/api/manager/wbsformelement";
import { getTypeMap, saveFormula, formulaDetail, updateFormula } from "@/api/formula/formula";
import { tabTypeLazyTreeAll, tabTypeLazyTree } from "@/api/manager/wbsprivate";
import { getTableElments } from "@/api/manager/wbstree";
import { mapGetters } from "vuex";

import formulaItem from "../component/formulaItem"
import formulaItemBig from "../component/formulaItemBig"
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 tableFormWrite from "../component/table-form-write.vue";
import { formatArrayMore, restoreArrayMore, generateResult } from '../component/funComponent/multiIfElseTools'
export default {
  components: {
    draggable,

    formulaItem,
    formulaItemBig,
    formulaTemplate,

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

    dateDeviation,
    dateFormat,
    datasRepeat,
    datasReme,
    datasGetlist,
    datasJoin,
    ifelse,

    deviationRange,
    tableFormWrite
  },
  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: ''
    },
    tableType: {
      type: Boolean,
      default: false
    }
  },
  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: [],//=等号右边的数组
      checkGsId: '',//选中的公式id
      rightDict: [],//等号右边元素的字典
      processType: '',//选中的元素在等号哪边
      processSelectIndex: 0,//选中的索引
      actiFunIndex: 0,//元素下挂载的计算式的索引
      chooseEleVisible: false,//选择元素弹窗
      argumenObj: {},

      symbolReg: /(\+|-|\*|\/)（.+）/,
      operatorReg: /^\+|-|\*|%/,//加减乘除
      startFCRegExp: /^FC\.([a-zA-Z\d]+)\(/,// 匹配开始的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,
      eleListCompLoading: false,
      eleListJudge: false,
      input3: '',
      rootNodeData: [],
      nodeZero: null,
      resolveZero: null,
      loading: false,
      itemList: [],
      inputEle: '',
      inputElePian: '',
      inputEleJudge: '',
      moreConditions: [],//多条件判断数组
      isMore: false,//是否多条件
      isGetData: false,//是否获取数据
      dataListGet: [],//获取的数据列表
      isDataChange: false,//数据是否变化
      dataForm: '',
      remark: '',
      method: '',
      formulaDetailMap: {},//公式详情map
      containerFocused: 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;
      }
    },
  },
  watch: {
    selectEleFormula: {
      handler() {
        this.checkDefaultSelection();
        this.$nextTick(() => {
          this.$el.querySelector('.sele-ele-box1').focus();
        });
      },
      deep: true
    },
  },
  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 私有树才有
    console.log(this.pid, 'this.pid');
    console.log(this.globaltype, 'this.globaltype');


    this.init();
  },
  methods: {
    onKeyDown(e) {
      if (!e.shiftKey) return;
      const key = e.key;          // 物理键名
      console.log(key, 'key');
      const map = {
        '_': () => this.addOperator('-'),
        '——': () => this.addOperator('-'),
        '—': () => this.addOperator('-'),
        '-': () => this.addOperator('-'),
        '+': () => this.addOperator('+'),
        '*': () => this.addOperator('*'),
        '?': () => this.addOperator('%'),
        '？': () => this.addOperator('%'),
        '(': () => this.addBrackets('(', false),
        '（': () => this.addBrackets('(', false),
        ')': () => this.addBrackets(')', true),
        '）': () => this.addBrackets(')', true)
      };
      (map[key] || (() => { }))();
    },
    async init() {
      this.getEleDetail();
      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;
      }
    },
    treeLoadNode(node, resolve) {
      let parentId = 12345678910;
      console.log(node.level, "node.level")
      if (node.level != 0) {
        parentId = node.data.id;
      }
      // 开启 “加载中” 动画
      if (node.level == 0) this.loading = true
      if (!this.elementType) {
        tabTypeLazyTreeAll({ parentId, current: 1, size: 1000, hasPartFormula: this.fromcurNode.hasPartFormula }).then(res => {
          // 请求接口，返回数据
          let data = res.data.data.records;
          this.loading = false
          resolve(data);
          this.$nextTick(() => {
            let expandid = this.tableType ? Number(this.fromcurNode.tableType) - 1 : Number(this.fromcurNode.parentId) - 1;
            node.childNodes[expandid].expand();
            let paramsId = this.fromcurNode.initTableId
            let isArray = Array.isArray(this.$refs.tree)
            console.log(isArray, "isArray")
            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.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(() => {
            let expandid = Number(this.fromcurNode.parentId) - 1
            node.childNodes[expandid].expand();
            let paramsId = this.fromcurNode.id
            console.log(this.nodeid, 'this.initTableId');
            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.allTreeShow = true;
        this.allTreeData = []
        if (!this.allTreeData.length) {
          this.treeLoading = true;
          if (!this.elementType) {
            let parentId = ''
            if (this.curData.hasChildren) {
              parentId = this.curData.id
            } else {
              // parentId=this.curData.parentId
              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.elementType) {
            let parentId = ''
            if (this.curData.hasChildren) {
              parentId = this.curData.id
            } else {
              // parentId=this.curData.parentId
              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;

      // 确保容器获得焦点
      this.$nextTick(() => {
        this.$el.querySelector('.sele-ele-box1').focus();
      });
    },

    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;
          }
        }
        let lastEle = this.selectEleFormula[this.selectEleFormula.length - 1];
        if (this.selectEleFormula.length == 0 || lastEle.type == 'Operator' || lastEle.type == 'Brackets') { /* 存在运算符 */
          this.eleAddFormulaHandle(item);
        } else {
          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) {
      if (this.itemList.length > 0) {
        this.itemList.forEach(e => {
          let lastEle = this.selectEleFormula[this.selectEleFormula.length - 1];
          if (this.selectEleFormula.length != 0 && lastEle.type != 'Operator' && lastEle.type != 'Brackets' && lastEle.name != '(') { /* 不存在运算符 */
            this.eleAddFormulaHandle(this.formulaMap[operator]);
          }
          this.eleAddFormulaHandle(e);
        })
      } else {
        if (this.curSeleEleIndex === -1 || this.curSeleEleIndex === this.selectEleFormula.length - 1) { /* 没选择值或者选择最后一个的时候直接添加符号 */
          this.eleAddFormulaHandle(this.formulaMap[operator]);
        } else { /* 选择中间的值，如果下一个是符号这替换，反之则在指定的位置添加 */
          this.randomaddOperator(this.formulaMap[operator])
        }
      }
      this.itemList = [];
    },
    //随机插入运算符
    randomaddOperator(ele) {
      // 取消所有元素的选中状态
      this.selectEleFormula.forEach(item => {
        item.selected = false;
      });
      let item = {
        type: 'Operator',
        name: this.symbolReg.exec(ele.name)[1],
        selected: true,
        template: ele.template
      }
      let index = Number(this.curSeleEleIndex);
      let currentName = this.selectEleFormula[index]
      if (currentName.type === 'Operator') { /* 选择的符号的时候，直接替换 */
        this.selectEleFormula.splice(index, 1, item)
      } else { /* 选择元素的时候，如果下一个是符号则替换，如果下一个是元素则添加 */

        let size = index + 1;
        let lastName = this.selectEleFormula[size]

        if (lastName.type === 'Operator') { /* 是符号，替换 */
          this.selectEleFormula.splice(size, 1, item)
        } else { /* 是元素，添加 */
          this.selectEleFormula.splice(size, 0, item)
          this.curSeleEleIndex = size;  // 光标移动到新添加的位置
        }
      }
    },
    //把元素加到公式里
    eleAddFormulaHandle(ele) {
      let newElementIndex = -1; // 记录新添加元素的索引

      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: [],
          })
          newElementIndex = this.deleEleIndex; // 新元素索引就是插入位置
          this.deleEleIndex = -1;
        } else {
          this.selectEleFormula.push({
            type: 'Element',
            name: ele.eName,
            id: ele.id,
            selected: false,
            tableElementKey: ele.tableElementKey,
            children: [],
          })
          newElementIndex = this.selectEleFormula.length - 1; // 新元素索引是最后一个
          this.deleEleIndex = -1;
        }
        // 选中新添加的元素并更新光标位置
        this.setActiveElement(newElementIndex);

      } 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
        })
        newElementIndex = this.selectEleFormula.length - 1;
        this.setActiveElement(newElementIndex);

      } else if (ele.type == 'Brackets') {
        //括号
        this.selectEleFormula.splice(ele.selectIndex, 0, {
          type: 'Brackets',
          name: ele.name,
          selected: false,
        })
        newElementIndex = ele.selectIndex;
        this.setActiveElement(newElementIndex);

      } else if (ele.type == 'Text') {
        //输入值
        this.selectEleFormula.push({
          type: 'Text',
          name: ele.name,
          selected: false,
        })
        newElementIndex = this.selectEleFormula.length - 1;
        this.setActiveElement(newElementIndex);

      } else if (ele.k) {
        //节点参数
        this.selectEleFormula.push({
          type: 'ParamData',
          name: ele.name,
          selected: false,
          id: ele.id,
          v: ele.v,
          k: ele.k,
          children: [],
        })
        newElementIndex = this.selectEleFormula.length - 1;
        this.setActiveElement(newElementIndex);
      }
    },
    // 新增：设置指定索引的元素为选中状态并更新光标
    setActiveElement(index) {
      console.log('setActiveElement-index', index);
      this.$nextTick(() => {
        // 取消所有元素的选中状态
        this.selectEleFormula.forEach(item => {
          item.selected = false;
        });

        // 选中新添加的元素
        if (this.selectEleFormula[index]) {
          this.selectEleFormula[index].selected = true;
          this.curSeleEleIndex = index; // 更新光标索引
        }

        // 确保容器获得焦点
        this.$el.querySelector('.sele-ele-box1').focus();
      });
    },


    //添加括号
    addBrackets(text, type) {
      let lastEle = this.selectEleFormula[this.selectEleFormula.length - 1];
      if (type) {  // 如果是true 表示为 ')' 右括号
        if (this.selectEleFormula.length === 0) {
          this.$message.warning('公式开头不能是右括号');
          return;
        }

        if (lastEle.type === 'Operator') {
          this.$message.warning('右括号无法连续出现在运算符号后面');
          return;
        }

        if (lastEle.type === 'Brackets' && lastEle.name === '(') {
          this.$message.warning('右括号无法连续出现在左括号后面');
          return;
        }
      } else if (this.selectEleFormula.length !== 0) { // 如果是false 表示为 '(' 左括号
        if (lastEle.type === 'Brackets' && lastEle.name === ')') {
          this.$message.warning('左括号无法连续出现在右括号后面');
          return;
        }

        if (['Element', 'Text'].includes(lastEle.type)) {
          this.$message.warning('左括号无法连续出现在元素或输入值后面');
          return;
        }
      }
      this.eleAddFormulaHandle({
        type: 'Brackets',
        name: text,
        selectIndex: Number(this.curSeleEleIndex) + 1
      })
      //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(obj, index) {
      // 先取消所有选中状态
      this.selectEleFormula.forEach(item => {
        item.selected = false;
      });

      // 设置当前选中项
      obj.item.selected = obj.selected;
      this.curSeleEleIndex = index;

      // 确保容器获得焦点以接收键盘事件
      this.$el.querySelector('.sele-ele-box1').focus();
      // 处理类型为ELEMENT的元素，提取tableElementKey
      console.log(obj.item, 'obj.item.');

      if (obj.item.type === 'Element' && obj.item.tableElementKey) {
        // 从类似"m_20220928142210_1575007943793836032:key_1"的格式中提取key部分
        const keyParts = obj.item.tableElementKey.split('key');
        this.selectedTableKey = keyParts.length > 1 ? 'key' + keyParts[1] : null;


      } else {
        // 非ELEMENT类型清空选中状态
        this.selectedTableKey = null;
      }

    },


    //取消勾选
    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) {
      this.checkGsId = item.id
      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 = '';
      }
    },
    //获取当前元素的表名
    getItemTableName(item) {
      if (item.type === "Element") {
        this.rightDict.forEach((ele) => {
          if (ele.ekey === item.tableElementKey) {
            item.tableName = ele.tableName
          }
        })
      }
    },

    //在等式模式下点选计算式
    equationSelect(index, indexPath) {
      debugger
      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;
      }
      //alert(JSON.stringify(expression.template))
      //debugger
      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",
        };
      }

      let tg = obj.template.args.findIndex(x => x.m !== '常量');
      obj.arguments[tg] = 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() {
      console.log('保存1-edit1', this.pid);
      console.log(this.processFormula, 'this.processFormula1111111112333');
      console.log(this.resultFormula, 'this.resultFormula1111111112333');
      console.log(this.$refs.dynamicComponent, 'this.$refs.dynamicComponent');
      // let obj = formulaArrayToString(this.processFormula,this.resultFormula);
      if (this.$refs.dynamicComponent && this.$refs.dynamicComponent.length > 0 && this.$refs.dynamicComponent[0] && this.$refs.dynamicComponent[0].symbol == 'more') {
        //多条件保存公式

        console.log('this.$refs.conditionList[0]', this.$refs.dynamicComponent[0]);
        const resMore = formatArrayMore(this.$refs.dynamicComponent[0].conditionList);
        const resJson = generateResult(this.$refs.dynamicComponent[0].conditionList);
        const remark = this.$refs.dynamicComponent[0].remark;
        const method = this.$refs.dynamicComponent[0].method;
        // console.log(remark, 'remark');

        console.log(resJson, 'resJson');


        if (this.formulaid) {
          updateFormula({
            id: this.formulaid,
            formula: '',
            formulas: resMore,
            remark: remark,
            method: method,
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: JSON.stringify(resJson),
            scope: this.globaltype,
            // projectId:this.curProjiect.id||this.projectId,
            projectId: this.curProjiect.id || this.pid,
            dev: deviationRangeText
          }).then(() => {
            this.formulaStringToArray();
            this.$message({
              type: "success",
              message: "修改成功"
            });
          })
        } else {
          saveFormula({
            formula: '',
            formulas: resMore,
            remark: remark,
            method: method,
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: JSON.stringify(resJson),
            scope: this.globaltype,
            dev: deviationRangeText,

            projectId: this.curProjiect.id || this.pid,
            ver: this.version
          }).then((res) => {
            if (res.data.data) {
              this.formulaid = res.data.data;
            }
            this.formulaStringToArray();
            this.$message({
              type: "success",
              message: "保存成功"
            });
          })
        }

        return;


      } else if (this.$refs.dynamicComponent && this.$refs.dynamicComponent.length > 0 && this.$refs.dynamicComponent[0] && this.$refs.dynamicComponent[0].symbol == 'getData') {
        //数据获取保存公式
        const dataRes = this.$refs.dynamicComponent[0].getDataConditionData();
        console.log(dataRes, 'dataRes');
        const result = dataRes.result;
        const mapEle = JSON.stringify(dataRes.mapEle);
        console.log(mapEle, 'mapEle');


        if (this.formulaid) {
          updateFormula({
            id: this.formulaid,
            formula: "FC.switchCase" + '(' + result + ')',

            remark: '',
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: mapEle,
            scope: this.globaltype,
            // projectId:this.curProjiect.id||this.projectId,
            projectId: this.curProjiect.id || this.pid,
            dev: deviationRangeText
          }).then(() => {
            this.formulaStringToArray();
            this.$message({
              type: "success",
              message: "修改成功"
            });
          })
        } else {
          saveFormula({
            formula: "FC.switchCase" + '(' + result + ')',

            remark: '',
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: mapEle,
            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.formulaStringToArray();
            this.$message({
              type: "success",
              message: "保存成功"
            });
          })
        }

        return;

      } else if (this.$refs.dynamicComponent && this.$refs.dynamicComponent.length > 0 && this.$refs.dynamicComponent[0] && this.$refs.dynamicComponent[0].formData) {
        console.log(this.$refs.dynamicComponent[0], 'this.$refs.dynamicComponent[0');
        const resForm = this.$refs.dynamicComponent[0].getDataChangeList();
        console.log(resForm, 'resForm');

        //数据自变保存

        if (this.formulaid) {
          updateFormula({
            id: this.formulaid,
            formula: resForm.test,
            remark: '',
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: JSON.stringify(resForm.map),
            scope: this.globaltype,
            // projectId:this.curProjiect.id||this.projectId,
            projectId: this.curProjiect.id || this.pid,
            dev: deviationRangeText
          }).then(() => {
            this.formulaStringToArray();
            this.$message({
              type: "success",
              message: "修改成功"
            });
          })
        } else {
          saveFormula({
            formula: resForm.test,
            remark: '',
            nodeId: this.nodeid,
            elementId: this.eleid,
            scale: this.isRetain ? this.retainNum : '',
            number: number,
            map: JSON.stringify(resForm.map),
            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.formulaStringToArray();
            this.$message({
              type: "success",
              message: "保存成功"
            });
          })
        }
        return
      }

      let arr = JSON.parse(JSON.stringify(this.processFormula));
      console.log("aaaaaaaaaaaaaaaa===processFormula", arr,);
      let filteredArr = arr.filter(item => item.id === this.checkGsId);
      console.log("bbbbbbbbbbbbbbbb===filteredArr", filteredArr,);
      //  let obj = formulaArrayToString(filteredArr,this.resultFormula);
      let obj
      let obj2
      obj = formulaArrayToString(this.processFormula, this.resultFormula);
      console.log("ccccccccccccccccc===obj", obj,);
      obj2 = formulaArrayToString(filteredArr, this.resultFormula);
      console.log("ccccccccccccccccc===obj2", obj2,);
      // 判断 obj2.text 是否包含 FC.ifelse
      if (obj2.text && obj2.text.includes('FC.ifelse')) {
        obj = obj2; // 如果包含 FC.ifelse,使用 obj2
      }
      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("55555555555", obj, obj.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((result) => {
          let msg = '修改成功';
          if (result.data.msg == '公式已删除') { this.formulaid = ''; msg = result.data.msg; }
          this.formulaStringToArray();
          this.$message({
            type: "success",
            message: msg
          });

        })
      } 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||this.projectId,
          projectId: this.curProjiect.id || this.pid,
          dev: deviationRangeText,
          ver: this.version
        }).then((res) => {
          if (res.data.data) {
            this.formulaid = res.data.data;
          }
          this.formulaStringToArray();
          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('formulaStringToArray', detail.formula);
      this.remark == detail.remark;
      //判断公式特殊处理
      if (detail && detail.formula.includes('FC.ifelseMulti')) {
        detail.formula = detail.formula.replace('FC.ifelseMulti', 'FC.ifelse');
        this.isMore = true;
        this.formulaDetailMap = detail.map;
        this.method = detail.method;
        this.moreConditions = restoreArrayMore(detail.formulas, this.formulaDetailMap)

      } else if (detail && detail.formula.includes('FC.switchCase')) {
        //数据获取
        this.formulaDetailMap = detail.map;
        detail.formula = detail.formula.replace('FC.switchCase', 'FC.ifelse');
        this.isGetData = true;
        this.dataListGet = detail.formula
        console.log(this.dataListGet, ' this.dataListGet');

      } else if (detail && detail.formula.includes('FC.dataChange')) {
        //数据自变
        this.formulaDetailMap = detail.map;

        this.isDataChange = true;
        this.dataForm = detail.formula
        console.log(this.dataForm, ' this.dataListGet');

      }
      else {
        this.isMore = false;
        this.moreConditions = []
        this.formulaDetailMap = {}
        this.isGetData = false;
        this.dataListGet = ''
        this.isDataChange = false;
        this.dataForm = '';

      }
      if (detail && detail.id) {
        //获取右边元素的字典
        let dictMap = detail.dict
        let dictArr = []
        //遍历：
        for (let i in dictMap) {
          dictArr.push(dictMap[i])

        }
        this.rightDict = dictArr
        this.formulaid = detail.id;
        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 && detail.scale != null && detail.scale >= 0) {
        this.isRetain = true;
        this.retainNum = detail.scale;
      } else {
        this.isRetain = false;
        this.retainNum = 2
      }
    },


    //设置动态组件里面的元素
    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 || data.isLinkTable === 2) {
        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;
          }
        })
        //  放出来的代码结束
        this.eleTableList = [this.curData] || []
        this.eleTableId = this.eleTableList[0].id;
      }
      else {
        this.eleListable = true;
        this.eleList = []
        this.page.total = 0
        setTimeout(() => {
          this.eleListable = false
        }, 1000);
      }


    },



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

    searchChange() {
      this.eleListable = true;
      getTableElments(this.treeId, this.inputEle).then((res) => {
        this.eleList = res.data.data;
        this.eleListable = false;
      })
    },
    searchChangePian() {
      this.eleListCompLoading = true;
      getTableElments(this.treeId, this.inputElePian).then((res) => {
        this.eleListComp = res.data.data;
        this.eleListCompLoading = false;
      })

    },
    searchChangeJudge() {
      this.eleListJudge = true;
      getTableElments(this.treeId, this.inputEleJudge).then((res) => {
        this.eleListComp = res.data.data;
        this.eleListJudge = false;
      })

    },
    clearInput() {
      this.eleListable = true;
      getTableElments(this.treeId).then((res) => {
        this.eleList = res.data.data;
        this.eleListable = false;
      })
    },
    clearInputPian() {
      // eleListComp
      this.eleListCompLoading = true;
      getTableElments(this.treeId).then((res) => {
        this.eleListComp = res.data.data;
        this.eleListCompLoading = false

      })
    },
    clearInputJudge() {
      this.eleListJudge = true;
      getTableElments(this.treeId).then((res) => {
        this.eleListComp = res.data.data;
      })
      this.eleListJudge = false;
    },



    getNodeDetailComp(data, node) {
      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
      }
    },



    //取消方法下面 元素勾选
    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();
        })
      })
    },
    // 左箭头导航
    handleLeftArrow(e) {
      e.preventDefault(); // 阻止默认行为
      if (this.curSeleEleIndex > 0) {
        // 取消当前选中项
        if (this.selectEleFormula[this.curSeleEleIndex]) {
          this.selectEleFormula[this.curSeleEleIndex].selected = false;
        }

        // 选中左侧项
        this.curSeleEleIndex--;
        this.selectEleFormula[this.curSeleEleIndex].selected = true;
        // this.selectedTableKey = this.selectEleFormula[this.curSeleEleIndex].tableElementKey;
        console.log(this.selectEleFormula[this.curSeleEleIndex].tableElementKey);
        if (this.selectEleFormula[this.curSeleEleIndex].tableElementKey) {
          const keyParts = this.selectEleFormula[this.curSeleEleIndex].tableElementKey.split('key');
          this.selectedTableKey = keyParts.length > 1 ? 'key' + keyParts[1] : null;
        }

      }
    },

    // 右箭头导航
    handleRightArrow(e) {
      e.preventDefault(); // 阻止默认行为
      if (this.curSeleEleIndex < this.selectEleFormula.length - 1) {
        // 取消当前选中项
        if (this.selectEleFormula[this.curSeleEleIndex]) {
          this.selectEleFormula[this.curSeleEleIndex].selected = false;
        }

        // 选中右侧项
        this.curSeleEleIndex++;
        this.selectEleFormula[this.curSeleEleIndex].selected = true;
        // this.selectedTableKey = this.selectEleFormula[this.curSeleEleIndex].tableElementKey;
        console.log(this.selectEleFormula[this.curSeleEleIndex].tableElementKey);
        if (this.selectEleFormula[this.curSeleEleIndex].tableElementKey) {
          const keyParts = this.selectEleFormula[this.curSeleEleIndex].tableElementKey.split('key');
          this.selectedTableKey = keyParts.length > 1 ? 'key' + keyParts[1] : null;
        }

      }
    },

    // 处理删除操作
    handleDelete(e) {
      e.preventDefault();

      // 增加更严格的索引检查
      if (
        this.curSeleEleIndex === null ||
        this.curSeleEleIndex === undefined ||
        this.curSeleEleIndex < 0 ||
        this.curSeleEleIndex >= this.selectEleFormula.length
      ) {

        return;
      }

      // 保存当前要删除的元素索引（避免后续操作影响）
      const indexToDelete = this.curSeleEleIndex;
      const itemToDelete = this.selectEleFormula[indexToDelete];



      // 处理元素取消勾选
      if (itemToDelete && itemToDelete.type === 'Element') {
        this.deleEleIndex = indexToDelete;
        this.unCheckEleFormulac(itemToDelete.id);
      }

      // 执行删除（只删除指定索引的1个元素）
      const deletedItems = this.selectEleFormula.splice(indexToDelete, 1);


      // 正确更新当前选中索引
      if (this.selectEleFormula.length > 0) {
        // 如果删除的是第一个元素，选中第一个元素
        this.curSeleEleIndex = indexToDelete == 0 ? 0 : indexToDelete - 1;
        // 如果删除的是最后一个元素，选中前一个
        // this.curSeleEleIndex = Math.min(
        //   indexToDelete - 1,
        //   this.selectEleFormula.length - 1
        // );
        if (this.selectEleFormula[this.curSeleEleIndex].tableElementKey) {
          const keyParts = this.selectEleFormula[this.curSeleEleIndex].tableElementKey.split('key');
          this.selectedTableKey = keyParts.length > 1 ? 'key' + keyParts[1] : null;
        }

        // 确保选中状态正确
        this.selectEleFormula.forEach((item, idx) => {
          item.selected = idx === this.curSeleEleIndex;
        });
      } else {
        this.curSeleEleIndex = -1;
        this.selectedTableKey = null;
      }
    },
    checkDefaultSelection() {
      const hasSelected = this.selectEleFormula.some(item => item.selected);
      if (!hasSelected && this.selectEleFormula.length > 0) {
        // 取消所有选中
        this.selectEleFormula.forEach(item => {
          item.selected = false;
        });

        // 选中最后一个元素
        const lastIndex = this.selectEleFormula.length - 1;
        this.selectEleFormula[lastIndex].selected = true;
        this.curSeleEleIndex = lastIndex;

      }
    },
  },


};
</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;
    display: flex;
    align-items: center;
    padding: 0 10px;

    .unit {
        padding-left: 6px;
    }
}
.edit-text {
  font-size: 26px;
  margin-left: 20px;
  display: flex;
  flex-wrap: wrap;
}

.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;
}
</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>
<style scoped lang="scss">
.operation-symbol-box {
  display: flex;
  align-items: center;
  border: 1px solid rgb(229, 231, 235);
  background-color: #F9FAFB;
  padding: 10px 10px;
  border-radius: 5px 5px 0px 0px;
  margin-top: 10px;

  span {
    margin-right: 10px;
    font-size: 16px;
  }

  ::v-deep .el-link {
    font-size: 16px;
    margin-right: 10px;
  }

}

.sele-ele-box1 {
  padding: 10px;
  border: 1px solid rgb(229, 231, 235);
  border-radius: 0px 0px 5px 5px;
  overflow-y: scroll;
  height: 50px;

  .pane-box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
}
</style>