<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 class="pane-box">
                        <formula-item-big v-for="(item, index) in resultFormula" :key="index" :item="item"
                            @click="(obj) => equationClick(obj, index, 'resultFormula')" :isShowCursor="false">
                        </formula-item-big>
                    </div>
                    <span style="margin-left: 5px; margin-right: 5px">=</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 class="flex">
                    <div>选择参数设置</div>
                    <div style="margin-left: 29%; font-weight: 700">公式配置</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" :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="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.tableName"
                                            :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>
            </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" @clickTag="handleClickTagElse" :method="method">
                                    </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="padding: 0 20px">
                                        <el-select v-model="eleTableIdComp" @change="getTableEleComp"
                                            placeholder="请选择元素表" style="width: 45%" size="small" clearable>
                                            <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!==null&&item.pkeyId!==-1)"></el-option> -->
                                            <el-option v-for="item in eleTableListComp" :key="item.id"
                                                :label="item.tableName" :value="item.pkeyId"></el-option>
                                        </el-select>
                                    </div>
                                    <div class="mg-t-10 no-mb-col flex1">
                                        <el-scrollbar style="height: 520px">
                                            <tableFormWrite :pkeyId="eleTableIdComp" @element-selected="
                                                (obj, val) =>
                                                    handleElementSelectedComp(obj, val, index)
                                            " :initTableName="initTableNameComp" :key="2" :container-id="'excel-container-2'"
                                                :selectedTableKey="selectedTableKeyComp"></tableFormWrite>
                                        </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" @clickTag="handleClickTag"></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="padding: 0 20px">
                            <el-select v-model="eleTableIdComp" @change="getTableEleComp" placeholder="请选择元素表"
                                style="width: 45%" clearable size="small">
                                <el-option v-for="item in eleTableListComp" :key="item.id" :label="item.tableName"
                                    :value="item.pkeyId"></el-option>
                            </el-select>
                        </div>
                        <div class="mg-t-10 mg-b-10 no-mb-col" style="width: 100%">
                            <el-scrollbar style="height: 520px">
                                <tableFormWrite :pkeyId="eleTableIdComp" @element-selected="setDeviationRangeEle"
                                    :initTableName="initTableNameDev" :key="4" :container-id="'excel-container-4'"
                                    :selectedTableKey="selectedTableKeyDev"></tableFormWrite>
                            </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="80%" 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="请选择元素表" size="small">
                                <el-option v-if="paramDataList.length" label="选择节点参数3" value="选择节点参数"></el-option>
                                <template>
                                    <el-option v-for="item in eleTableList" :key="item.id" :label="item.tableName"
                                        :value="item.pkeyId !== null && item.pkeyId !== -1
                                                ? item.pkeyId
                                                : item.id
                                            "></el-option>
                                </template>
                            </el-select>
                        </div>
                        <div class="mg-t-10 mg-b-10 no-mb-col">
                            <el-scrollbar style="height: 460px">
                                <tableFormWrite :pkeyId="eleTableId" :multiple-select="true" @element-selected="
                                    (obj, val, list) =>
                                        handleElementSelectedList(obj, val, list)
                                " :initTableName="initTableName" :key="tableKey" :container-id="'excel-container-' + tableKey"
                                    :selectedTableKey="selectedTableKeyList"></tableFormWrite>
                            </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>
            <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 getEleDetail } 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 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 {
    formatArrayMore,
    restoreArrayMore,
    generateResult,
} from "../component/funComponent/multiIfElseTools";
import dataChange from "../component/funComponent/dataChange";
import tableFormWrite from "../component/table-form-write.vue";
// import { log } from "@antv/g2plot/lib/utils";

export default {
    components: {
        draggable,

        formulaItem,
        formulaItemBig,
        formulaTemplate,

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

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

        deviationRange,
        dataChange,
        tableFormWrite,
    },
    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: () => ({}),
        },
        iswbstype: {
            //是否是公共wbs
            type: String,
            default: "",
        },
        pkeyId: {
            type: String,
            default: "", //表单pkeyId
        },
    },
    mounted() {
        // 初始时让容器获得焦点
        this.$nextTick(() => {
            this.$el.querySelector(".sele-ele-box1").focus();
        });
    },
    data() {
        return {
            // wbsid: "", //从哪个wbs树过来的
            // eleid: "", //元素id
            // nodeid:'',//所在树节点id
            // pid:'',//项目id 私有树才有
            formulaid: "",

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

            isRetain: false, //是否保留小数
            retainNum: 2, //保留几位小数
            formulaList: {},
            formulaMap: {},
            activeIndex: "1-1", //当前选择的公式
            itemList: [],
            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: [], //=等号右边的数组
            rightDict: [], //等号右边元素的字典
            processType: "", //选中的元素在等号哪边
            processSelectIndex: 0, //选中的索引
            actiFunIndex: 0, //元素下挂载的计算式的索引
            chooseEleVisible: false, //选择元素弹窗
            argumenObj: {},
            checkGsId: "", //选中的元素表id

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

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

            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,
            isMore: false, //是否是多条件判断
            moreConditions: [], //多条件判断数组
            formulaDetailMap: {}, //公式详情map
            dataListGet: "",
            isGetData: false, //是否获取数据
            isDataChange: false, //是否数据自变
            dataForm: "",
            remark: "", //备注
            initTableName: "", //初始表名
            containerFocused: false, //公式编辑区域是否聚焦
            selectedTableKey: "", // 存储选中的表格元素key
            initTableNameComp: "", //初始表名组件
            selectedTableKeyComp: "", // 存储选中的表格元素key 组件
            // initTableNameList:'',//初始表名 选择元素弹窗
            selectedTableKeyList: "", // 存储  选择元素弹窗  选中的表格元素key
            seleList: [], //选择元素弹窗 选中的元素列表
            tableKey: "3",
            initTableNameDev: "", //初始表名 允许偏差值范围
            selectedTableKeyDev: "", // 存储
            method: "",
        };
    },
    computed: {
        ...mapGetters(["userInfo"]),

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

        //等式中选中的元素
        equationSelectEle: function () {
            if (this.processType) {
                console.log(this[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 私有树才有
        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();
        },

        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", this.operationVisible);
            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.checkDefaultSelection();
            const keyParts =
                this.selectEleFormula[this.curSeleEleIndex].tableElementKey.split(":");
            this.selectedTableKey = keyParts.length > 1 ? keyParts[1] : null;
            // 确保容器获得焦点
            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" ||
                    lastEle.name == "("
                ) {
                    /* 存在运算符 */
                    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){
        //   this.eleAddFormulaHandle(this.formulaMap[operator]);
        // },
        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; // 光标移动到新添加的位置
                }
            }
        },
        addOperator(operator) {
            console.log("addOperator", operator);
            // 保存添加前的长度用于计算新索引
            const initialLength = this.selectEleFormula.length;

            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 = [];

            // 计算新添加运算符的索引并选中它
            this.$nextTick(() => {
                // 计算新添加元素的索引
                const newIndex =
                    this.selectEleFormula.length > initialLength
                        ? this.selectEleFormula.length - 1
                        : this.curSeleEleIndex + 1; // 处理替换情况

                // 取消所有选中状态
                this.selectEleFormula.forEach((item) => {
                    item.selected = false;
                });

                // 选中新添加的运算符
                if (this.selectEleFormula[newIndex]) {
                    this.selectEleFormula[newIndex].selected = true;
                    this.curSeleEleIndex = newIndex;
                }

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

        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("取消");
        },
        //把元素加到公式里
        eleAddFormulaHandle(ele) {
            let newElementIndex = -1; // 记录新添加元素的索引

            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: [],
                    });
                    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) {
            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;
        //   }
        // },
        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;
        //   }
        // },
        // 检查是否有选中的元素，如果没有则选中最后一个
        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;
                //   const keyParts = this.selectEleFormula[ this.curSeleEleIndex].tableElementKey.split(':');
                // this.selectedTableKey = keyParts.length > 1 ? keyParts[1] : null;
            }
        },
        // 点击元素时的处理
        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;
            }
        },

        // 左箭头导航
        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;
                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;
                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,
                //   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;
            }
        },
        //取消勾选
        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) {
            this.checkGsId = item.id;

            console.log(item, selected);

            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) {
            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);
            console.log(this.equationSelectEle, "equationSelectEle11111111111111");
            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() {
            this.seleList.forEach((element, index) => {
                this.setEleToArgumen(element, index + this.argumenObj.index);
            });

            this.chooseEleVisible = false;
            this.tableKey = Date.now();
        },
        // 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;
        //         }
        //     }
        // },
        //设置元素到指定位置参数
        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) {
            console.log("999999999999999", argumenObj);
            const { item } = argumenObj;

            if (item) {
                const keyParts = item.tableElementKey.split("key");
                this.selectedTableKeyList =
                    keyParts.length > 1 ? "key" + keyParts[1] : null;
            } else {
                this.selectedTableKeyList = null;
            }
            this.argumenObj = argumenObj;
            this.chooseEleVisible = true;
        },
        // 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("保存-edit", this.pid);
            console.log(this.processFormula, "this.processFormula1111111112333");
            console.log(this.resultFormula, "this.resultFormula1111111112333");
            console.log(this.$refs.dynamicComponent, "this.$refs.dynamicComponent");

            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].conditionList
                );
                let resMore = formatArrayMore(
                    this.$refs.dynamicComponent[0].conditionList
                );
                const resJson = generateResult(
                    this.$refs.dynamicComponent[0].conditionList
                );
                let remark = this.$refs.dynamicComponent[0].result;
                let method = this.$refs.dynamicComponent[0].method;
                console.log(method, "method");

                console.log(remark, "remark");

                console.log(resJson, "resJson");

                if (this.formulaid) {
                    updateFormula({
                        id: this.formulaid,
                        formula: "",
                        formulas: resMore,
                        remark: remark,
                        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,
                        method: method,
                    }).then(() => {
                        this.formulaStringToArray();
                        this.$message({
                            type: "success",
                            message: "修改成功",
                        });
                    });
                } else {
                    saveFormula({
                        formula: "",
                        formulas: resMore,
                        remark: remark,
                        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.projectId,
                        projectId: this.curProjiect.id || this.pid,
                        ver: this.version,
                        method: method,
                    }).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;
            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")) ||
                obj2.text.includes("''")
            ) {
                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(() => {
                    this.formulaStringToArray();
                    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.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(detail, "detail");
            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,
                    detail.remark
                );
            } 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 = "";
            }

            console.log("detail", detail);

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

                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
                );
                console.log("formula99999999999", formula, 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;

                console.log("this.resultFormula", this.resultFormula);

                //允许偏差值范围
                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) {
            console.log(item, "item");
            console.log(index, "index");
            if (value) {
                //console.log(this.$refs.dynamicComponent[index])
                this.$refs.dynamicComponent[index].setELe(item);
            }
        },

        //设置动态组件里面的元素
        setDeviationRangeEle(item, value) {
            if (value) {
                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!==null?this.eleTableList[0].pkeyId:this.eleTableList[0].id;
                            let tabId = this.pkeyId
                                ? this.pkeyId
                                : this.eleTableList[0].pkeyId !== -1 &&
                                    this.eleTableList[0].pkeyId !== null
                                    ? this.eleTableList[0].pkeyId
                                    : this.eleTableList[0].id;
                            console.log(this.pkeyId, "this.pkeyId");

                            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 !== null
                                ? 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 = [];
                    }
                });
            }
        },
        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: [],
                    },
                ];
            });
        },
        getTableEle(tableId) {
            console.log("getTableEle", tableId, this.eleTableList);
            this.initTableName = "";
            this.eleTableList.forEach((item) => {
                if (item.pkeyId === tableId) {
                    this.initTableName = item.initTableName;
                }
            });
            console.log("getTableEle==this.initTableName", this.initTableName);

            this.input3 = "";
            if (tableId === "选择节点参数") {
                this.eleList = this.paramDataList;
                this.eleList1 = this.paramDataList;
            } else {
                selectFormElements(tableId, {
                    nodeId: this.nodeid,
                    type: this.iswbstype,
                }).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, this.pid, "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.eleTableIdComp = this.eleTableListComp[0].pkeyId;
                            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;
                        let tabId =
                            this.eleTableList[0].pkeyId !== -1 &&
                                this.eleTableList[0].pkeyId !== null
                                ? this.eleTableList[0].pkeyId
                                : this.eleTableList[0].id;
                        this.getTableEleComp(tabId);
                    } 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 = "";
            console.log("this.iswbstype", this.iswbstype);

            if (tableId === "选择节点参数") {
                this.eleListComp = this.paramDataList;
                this.eleListComp1 = this.paramDataList;
            } else {
                selectFormElements(tableId, {
                    nodeId: this.nodeid,
                    type: this.iswbstype,
                }).then((res) => {
                    this.eleListComp = res.data.data;
                    this.eleListComp1 = res.data.data;
                });
                console.log(this.eleTableListComp, "eleTableListComp");

                this.eleTableListComp.forEach((item) => {
                    if (item.pkeyId === tableId) {
                        this.initTableNameComp = item.initTableName;
                        this.initTableNameDev = item.initTableName;
                    }
                });
            }
        },

        //取消方法下面 元素勾选
        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();
                    });
            });
        },

        // 修改元素选择处理方法，实现替换或添加逻辑
        handleElementSelected(item, value) {
            console.log(item, "item");
            if (!item.eName) {
                this.$message({
                    type: "warning",
                    message: "当前位置未配置元素，请重新选择或配置元素后再试",
                });
                return;
            }

            if (value) {
                // 检查是否有选中的公式项
                if (
                    this.curSeleEleIndex !== -1 &&
                    this.curSeleEleIndex < this.selectEleFormula.length
                ) {
                    const selectedItem = this.selectEleFormula[this.curSeleEleIndex];

                    // 如果当前选中的是Element类型，执行替换操作
                    if (selectedItem.type === "Element") {
                        this.replaceSelectedElement(item);
                        return; // 替换后退出，不执行添加逻辑
                    }
                }

                // 执行添加逻辑（当前没有选中项或选中项不是Element类型）
                // 简单语法判断
                if (this.selectEleFormula.length > 0) {
                    let lastEle = this.selectEleFormula[this.selectEleFormula.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;
                    }
                }

                // 检查是否可以添加元素
                if (
                    this.selectEleFormula.length === 0 ||
                    ["Operator", "Brackets"].includes(
                        this.selectEleFormula[this.selectEleFormula.length - 1].type
                    ) ||
                    this.selectEleFormula[this.selectEleFormula.length - 1].name === "("
                ) {
                    console.log("可以添加元素");
                    this.eleAddFormulaHandle(item);
                } else {
                    console.log("不能添加元素");
                    // 可以根据需要添加错误提示
                }
            } 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);
                }
            }
        },
        handleElementSelectedComp(item, value, index) {
            item.name = item.eName;
            if (value) {
                //console.log(this.$refs.dynamicComponent[index])
                this.$refs.dynamicComponent[index].setELe(item);
            }
        },
        handleElementSelectedList(item, value, list) {
            console.log(item, value, list, "1111list");

            this.seleList = list;
            this.seleList.forEach((element, index) => {
                element.name = element.eName;
            });
            // list.forEach((element,index) => {
            //     this.setEleToArgumen(element,index+this.argumenObj.index);
            //   });
        },

        // 新增：替换当前选中的元素
        replaceSelectedElement(newItem) {
            if (
                this.curSeleEleIndex === -1 ||
                this.curSeleEleIndex >= this.selectEleFormula.length
            ) {
                return;
            }

            const currentIndex = this.curSeleEleIndex;

            // 取消原元素的勾选状态
            const oldItem = this.selectEleFormula[currentIndex];
            this.unCheckEleFormulac(oldItem.id);

            // 替换元素
            this.selectEleFormula.splice(currentIndex, 1, {
                type: "Element",
                name: newItem.eName,
                id: newItem.id,
                selected: false,
                tableElementKey: newItem.tableElementKey,
                children: [],
            });

            // 更新选中状态和光标位置
            this.setActiveElement(currentIndex);
        },
        //偏差值范围选择元素
        handleClickTag(item) {
            const keyParts = item.tableElementKey.split("key");
            this.selectedTableKeyDev =
                keyParts.length > 1 ? "key" + keyParts[1] : null;
        },
        //逻辑判断回显元素
        handleClickTagElse(item) {
            this.selectedTableKeyComp = null;
            const keyParts = item.tableElementKey.split("key");
            this.selectedTableKeyComp =
                keyParts.length > 1 ? "key" + keyParts[1] : null;
        },
    },
};
</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;
    // 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%;
    }
}

.operation-box-inset {
    display: flex;
    flex-direction: column;
}
</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>
