<template>
  <div class="ifelse-box">
    <div class="flex jc-al-c">
      <span v-if="symbol !== '|'">IF条件执行</span>
      <el-select v-model="symbol" @change="setCondition()" size="medium" placeholder="请选择">
        <el-option label="大于等于" value=">="></el-option>
        <el-option label="小于等于" value="<="></el-option>
        <el-option label="大于" value=">"></el-option>
        <el-option label="小于" value="<"></el-option>
        <el-option label="等于" value="="></el-option>
        <el-option label="小于且大于" value="<&&<"></el-option>
        <el-option label="小于等于且大于等于" value="<=&&<="></el-option>
        <el-option label="试验判断" value="|"></el-option>
        <el-option label="多条件" value="more"></el-option>
        <el-option label="数据获取" value="getData"></el-option>
      </el-select>
      <span class="mg-l-20 mg-r-10" v-if="symbol !== '|'">执行结果</span>
      <el-select v-model="result" @change="setTF()" size="medium" placeholder="请选择"
        v-if="symbol !== '|' && symbol !== 'getData'">
        <el-option label="真假值" value="1"></el-option>
        <el-option label="运算" value="2"></el-option>
      </el-select>
      <el-select v-model="result" size="medium" placeholder="请选择" v-if="symbol == 'getData'">
        <el-option label="数据获取" value="3"></el-option>
      </el-select>
      <el-select v-model="method" size="medium" placeholder="请选择" v-if="symbol == 'more'" class="mg-l-10">
        <el-option label="总数" value="sum"></el-option>
        <el-option label="平均值" value="avg"></el-option>
      </el-select>
      <el-button class="mg-l-10" size="small" type="info" @click="showSelectEle">选择参数</el-button>
    </div>

    <!-- 多条件其他的 -->
    <template v-if="symbol !== 'more' && symbol !== 'getData'">
      <div class="mg-t-20 flex jc-al-c">
        <span class="textblod mg-r-20" v-if="symbol !== '|'">IF</span>
        <div class="flex jc-al-c" v-if="symbol == '<&&<' || symbol == '<=&&<='">
          <vue-tags-input v-model="tag1" :tags="tags1" @focus="curFocusIndex = 1" @blur="inputBlur(1)"
            placeholder="输入/参数111" @before-adding-tag="beforeAddingTag" />
          <span v-if="symbol == '<&&<'" class="mg-l-20 mg-r-20">&lt;</span>
          <span v-if="symbol == '<=&&<='" class="mg-l-20 mg-r-20">≤</span>
        </div>
        <vue-tags-input v-model="tag2" :tags="tags2" @focus="curFocusIndex = 2" @blur="inputBlur(2)"
          placeholder="输入/参数222" @before-adding-tag="beforeAddingTag" @tag-clicked="handleTagClick($event, 2)"
          ref="tagsInput2" />
        <span class="mg-l-20 mg-r-20">
          <span v-if="symbol == '>='">≥</span>
          <span v-if="symbol == '<='">≤</span>
          <span v-if="symbol == '>'">&gt;</span>
          <span v-if="symbol == '<'">&lt;</span>
          <span v-if="symbol == '='">=</span>
          <span v-if="symbol == '<&&<'">&lt;</span>
          <span v-if="symbol == '|'">|</span>

        </span>
        <vue-tags-input v-model="tag3" :tags="tags3" @focus="curFocusIndex = 3" @blur="inputBlur(3)" placeholder="输入/参数"
          @before-adding-tag="beforeAddingTag" @tag-clicked="handleTagClick($event, 3)" ref="tagsInput3" />
      </div>
      <div class="flex jc-al-c mg-t-20" v-if="result == 1">
        <span class="textblod mg-r-10">真值</span>
        <vue-tags-input v-model="tag4" :tags="tags4" @focus="curFocusIndex = 4" @blur="inputBlur(4)" placeholder="输入/参数"
          @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp" @tag-clicked="handleTagClick($event, 4)"
          ref="tagsInput4" />
        <span class="textblod mg-r-10 mg-l-20">假值</span>
        <vue-tags-input v-model="tag5" :tags="tags5" @focus="curFocusIndex = 5" @blur="inputBlur(5)" placeholder="输入/参数"
          @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp" @tag-clicked="handleTagClick($event, 5)"
          ref="tagsInput5" />
      </div>
      <div class="mg-t-20" v-if="result == 2">
        <div class="flex">
          <span class="textblod mg-r-10">真值</span>
          <div class="border-grey sele-ele-box flex1" :class="{ 'border-green': curFocusIndex == 6 }"
            @click="curFocusIndex = 6">
            <div class="flex jc-sb mg-b-20">
              <div class="icon-box">
                <el-link :underline="false" icon="el-icon-delete" type="danger" @click="removeSelect"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('+')"
                  icon="el-icon-circle-plus-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('-')"
                  icon="el-icon-remove-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('*')"
                  icon="el-icon-circle-close"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('%')">÷</el-link>
              </div>
              <div>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('(', false)">(</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(')', true)">)</el-link>
                <el-link :underline="false" type="primary" @click="addText">输入值</el-link>
              </div>
            </div>
            <draggable v-model="selectEleFormula">
              <formula-item v-for="(item, index) in selectEleFormula" :key="index" :item="item"
                @click="obj => eleFormulaClick(obj, index)">
              </formula-item>
            </draggable>
          </div>
        </div>
        <div class="flex mg-t-10">
          <span class="textblod mg-r-10">假值</span>
          <div class="border-grey sele-ele-box flex1" :class="{ 'border-green': curFocusIndex == 7 }"
            @click="curFocusIndex = 7">
            <div class="flex jc-sb mg-b-20">
              <div class="icon-box">
                <el-link :underline="false" icon="el-icon-delete" type="danger" @click="removeSelect"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('+')"
                  icon="el-icon-circle-plus-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('-')"
                  icon="el-icon-remove-outline"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('*')"
                  icon="el-icon-circle-close"></el-link>
                <el-link :underline="false" type="primary" @click="addOperator('%')">÷</el-link>
              </div>
              <div>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('(', false)">(</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(')', true)">)</el-link>
                <el-link :underline="false" type="primary" @click="addText">输入值</el-link>
              </div>
            </div>
            <draggable v-model="selectEleFormula2">
              <formula-item v-for="(item, index) in selectEleFormula2" :key="index" :item="item"
                @click="obj => eleFormulaClick(obj, index)">
              </formula-item>
            </draggable>
          </div>
        </div>
      </div>
    </template>
    <!-- 多条件 -->
    <template v-if="symbol == 'more'">

      <div v-for="(item, conditionIndex) in conditionList" :key="conditionIndex">
        <!-- 从第二个条件开始显示“条件X”和删除按钮 -->
        <div v-if="conditionIndex >= 1" class="condition-header flex al-c  mg-t-20">
          <span class="textblod">条件{{ conditionIndex + 1 }}</span>
          <el-button type="danger" size="mini" @click="removeCondition(conditionIndex)" class=" mg-l-20">删除</el-button>
        </div>
        <div v-for="(innerItem, innerIndex) in conditionList[conditionIndex].formulaIfElse">
          <!-- 逻辑符号选择框 - 从第二个条件开始显示（innerIndex >= 1） -->
          <div v-if="innerIndex >= 1" style="margin-left: 25%;" class="mg-t-10 mg-b-10">
            <el-select v-model="conditionList[conditionIndex].formulaIfElse[innerIndex].logicSymbol"
              @change="setConditionMulti(conditionIndex, innerIndex)" size="medium" placeholder="请选择"
              style="width:120px">
              <el-option label="或者" value="||"></el-option>
              <el-option label="并且" value="&&"></el-option>
            </el-select>
          </div>

          <!-- if条件内容 -->
          <div class="mg-t-20 flex jc-al-c" :key="innerIndex">
            <span class="textblod mg-r-20">IF</span>

            <vue-tags-input :ref="`multiTagsInput_${conditionIndex}_${innerIndex}_tag2`"
              v-model="conditionList[conditionIndex].formulaIfElse[innerIndex].tag2"
              :tags="conditionList[conditionIndex].formulaIfElse[innerIndex].tags2"
              @focus="setMultiFocus(conditionIndex, innerIndex, 'tag2')"
              @blur="inputBlurMulti(conditionIndex, innerIndex, 'tag2')" placeholder="输入/参数"
              @before-adding-tag="beforeAddingTag"
              @tag-clicked="handleMultiTagClick($event, conditionIndex, innerIndex, 'tag2')" />
            <span class="mg-l-20 mg-r-20">
              <el-select v-model="conditionList[conditionIndex].formulaIfElse[innerIndex].symbol1"
                @change="setConditionMulti(conditionIndex, innerIndex)" size="medium" placeholder="请选择"
                style="width:120px">
                <el-option label=">=" value=">="></el-option>
                <el-option label="<=" value="<="></el-option>
                <el-option label="=" value="="></el-option>
                <el-option label=">" value=">"></el-option>
                <el-option label="<" value="<"></el-option>
                <el-option label="≠" value="!= "></el-option>
                <!-- <el-option label="包含" value="包含"></el-option>
                <el-option label="不包含" value="不包含"></el-option> -->
              </el-select>
            </span>
            <vue-tags-input :ref="`multiTagsInput_${conditionIndex}_${innerIndex}_tag3`"
              v-model="conditionList[conditionIndex].formulaIfElse[innerIndex].tag3"
              :tags="conditionList[conditionIndex].formulaIfElse[innerIndex].tags3"
              @focus="setMultiFocus(conditionIndex, innerIndex, 'tag3')"
              @blur="inputBlurMulti(conditionIndex, innerIndex, 'tag3')" placeholder="输入/参数"
              @before-adding-tag="beforeAddingTag"
              @tag-clicked="handleMultiTagClick($event, conditionIndex, innerIndex, 'tag3')" />
            <i class="el-icon-circle-plus-outline mg-l-20" style="color: #409EFF;cursor: pointer;"
              @click="addConditionItem(conditionIndex, innerIndex)"></i>
            <i class="el-icon-delete mg-l-20" style="color: red;cursor: pointer;"
              @click="removeConditionItem(conditionIndex, innerIndex)" v-if="innerIndex > 0 || conditionIndex > 0"></i>
          </div>
        </div>
        <div class="flex jc-al-c mg-t-20" v-if="result == 1">
          <span class="textblod mg-r-10">满足</span>
          <vue-tags-input :ref="`multiTagsInput_${conditionIndex}_${innerIndex}_tag4`"
            v-model="conditionList[conditionIndex].tag4" :tags="conditionList[conditionIndex].tags4"
            @focus="setMultiFocus(conditionIndex, null, 'tag4')" @blur="inputBlurMulti(conditionIndex, null, 'tag4')"
            placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
            @tag-clicked="handleMultiTagClick($event, conditionIndex, innerIndex, 'tag4')" />

          <!-- 只在最后一个条件显示"不满足"输入框 -->
          <template v-if="conditionIndex === conditionList.length - 1">
            <span class="textblod mg-r-10 mg-l-20">不满足</span>
            <vue-tags-input :ref="`multiTagsInput_${conditionIndex}_${innerIndex}_tag5`"
              v-model="conditionList[conditionIndex].tag5" :tags="conditionList[conditionIndex].tags5"
              @focus="setMultiFocus(conditionIndex, null, 'tag5')" @blur="inputBlurMulti(conditionIndex, null, 'tag5')"
              placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
              @tag-clicked="handleMultiTagClick($event, conditionIndex, innerIndex, 'tag5')" />
          </template>

          <!-- 只在最后一个条件显示"添加其他条件"按钮 -->
          <div class="mg-l-20" v-if="conditionIndex === conditionList.length - 1">
            <el-button size="small" type="primary" @click="addCondition(conditionIndex)">添加其他条件</el-button>
          </div>
        </div>
        <template v-if="result == 2">
          <div class="mg-t-20">
            <div class="flex">
              <span class="textblod mg-r-10">满足</span>
              <div class="border-grey sele-ele-box flex1"
                :class="{ 'border-green': isCurFocus(conditionIndex, null, 'formula1') }"
                @click="setMultiFocus(conditionIndex, null, 'formula1')">
                <div class="flex jc-sb mg-b-20">
                  <div class="icon-box">
                    <el-link :underline="false" icon="el-icon-delete" type="danger"
                      @click="removeSelectMulti(conditionIndex, 'formula1')"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '+', 'formula1')"
                      icon="el-icon-circle-plus-outline"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '-', 'formula1')"
                      icon="el-icon-remove-outline"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '*', 'formula1')" icon="el-icon-circle-close"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '%', 'formula1')">÷</el-link>
                  </div>
                  <div>
                    <el-link :underline="false" type="primary" class="mg-r-10"
                      @click="addBracketsMulti(conditionIndex, '(', false, 'formula1')">(</el-link>
                    <el-link :underline="false" type="primary" class="mg-r-10"
                      @click="addBracketsMulti(conditionIndex, ')', true, 'formula1')">)</el-link>
                    <el-link :underline="false" type="primary"
                      @click="addTextMulti(conditionIndex, 'formula1')">输入值</el-link>
                  </div>
                </div>
                <draggable v-model="conditionList[conditionIndex].formula1">
                  <formula-item v-for="(item, index) in conditionList[conditionIndex].formula1" :key="index" :item="item"
                    @click="obj => eleFormulaClickMulti(obj, index, conditionIndex, 'formula1')">
                  </formula-item>
                </draggable>
              </div>
            </div>

            <!-- 只在最后一个条件显示"不满足"公式框 -->
            <div class="flex mg-t-10" v-if="conditionIndex === conditionList.length - 1">
              <span class="textblod mg-r-10">不满足</span>
              <div class="border-grey sele-ele-box flex1"
                :class="{ 'border-green': isCurFocus(conditionIndex, null, 'formula2') }"
                @click="setMultiFocus(conditionIndex, null, 'formula2')">
                <div class="flex jc-sb mg-b-20">
                  <div class="icon-box">
                    <el-link :underline="false" icon="el-icon-delete" type="danger"
                      @click="removeSelectMulti(conditionIndex, 'formula2')"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '+', 'formula2')"
                      icon="el-icon-circle-plus-outline"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '-', 'formula2')"
                      icon="el-icon-remove-outline"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '*', 'formula2')" icon="el-icon-circle-close"></el-link>
                    <el-link :underline="false" type="primary"
                      @click="addOperatorMulti(conditionIndex, '%', 'formula2')">÷</el-link>
                  </div>
                  <div>
                    <el-link :underline="false" type="primary" class="mg-r-10"
                      @click="addBracketsMulti(conditionIndex, '(', false, 'formula2')">(</el-link>
                    <el-link :underline="false" type="primary" class="mg-r-10"
                      @click="addBracketsMulti(conditionIndex, ')', true, 'formula2')">)</el-link>
                    <el-link :underline="false" type="primary"
                      @click="addTextMulti(conditionIndex, 'formula2')">输入值</el-link>
                  </div>
                </div>
                <draggable v-model="conditionList[conditionIndex].formula2">
                  <formula-item v-for="(item, index) in conditionList[conditionIndex].formula2" :key="index" :item="item"
                    @click="obj => eleFormulaClickMulti(obj, index, conditionIndex, 'formula2')">
                  </formula-item>
                </draggable>
              </div>
            </div>

            <!-- 只在最后一个条件显示"添加条件"按钮 -->
            <el-button size="small" @click="addCondition(conditionIndex)" type="primary"
              v-if="conditionIndex === conditionList.length - 1">添加条件</el-button>
          </div>
        </template>

      </div>
    </template>
    <!-- 数据获取配置框 - 修改部分 -->
    <template v-if="symbol === 'getData'">
      <div class="mg-t-10">
        <div v-for="(item, index) in getDataList" :key="index" class="mg-t-10">
          <div class="flex jc-al-c">
            <div class="textblod mg-r-10" :style="{ opacity: index === 0 ? 1 : 0 }">
              当
            </div>
            <div class="mg-r-10" :style="{ opacity: index === 0 ? 1 : 0 }">
              <vue-tags-input v-model="item.tagWhenLeft" :tags="item.tagsWhenLeft"
                @focus="setDataFocus(index, 'tagWhenLeft')" @blur="dataInputBlur(index, 'tagWhenLeft')"
                placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
                @tag-clicked="handleDataTagClick($event, index, 'tagWhenLeft')" :ref="`dataTag_${index}_tagWhenLeft`" />
            </div>
            <div class="mg-r-10">
              <el-select v-model="item.condition" @change="setDataCondition(index)" size="medium" placeholder="请选择"
                style="width:120px">
                <el-option label=">=" value=">="></el-option>
                <el-option label="<=" value="<="></el-option>
                <el-option label="=" value="="></el-option>
                <el-option label=">" value=">"></el-option>
                <el-option label="<" value="<"></el-option>
                <el-option label="≠" value="≠"></el-option>
                <el-option label="包含" value="包含"></el-option>
                <el-option label="不包含" value="不包含"></el-option>
              </el-select>
            </div>
            <div class="mg-r-10">
              <vue-tags-input v-model="item.tagWhenRight" :tags="item.tagsWhenRight"
                @focus="setDataFocus(index, 'tagWhenRight')" @blur="dataInputBlur(index, 'tagWhenRight')"
                placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
                @tag-clicked="handleDataTagClick($event, index, 'tagWhenRight')"
                :ref="`dataTag_${index}_tagWhenRight`" />
            </div>

            <div class="mg-r-10 textblod">则</div>
            <vue-tags-input v-model="item.tagThenLeft" :tags="item.tagsThenLeft"
              @focus="setDataFocus(index, 'tagThenLeft')" @blur="dataInputBlur(index, 'tagThenLeft')"
              placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
              @tag-clicked="handleDataTagClick($event, index, 'tagThenLeft')" :ref="`dataTag_${index}_tagThenLeft`" />
            <span class="mg-r-10 mg-l-10">=</span>
            <div class="mg-r-10">
              <vue-tags-input v-model="item.tagThenRight" :tags="item.tagsThenRight"
                @focus="setDataFocus(index, 'tagThenRight')" @blur="dataInputBlur(index, 'tagThenRight')"
                placeholder="输入/参数" @before-adding-tag="beforeAddingTag" @keyup.native="btKeyUp"
                @tag-clicked="handleDataTagClick($event, index, 'tagThenRight')"
                :ref="`dataTag_${index}_tagThenRight`" />
            </div>
            <i class="el-icon-circle-plus-outline mg-l-20" style="color: #409EFF;cursor: pointer;"
              @click="addDataItem(index)"></i>
            <i class="el-icon-delete mg-l-20" style="color: red;cursor: pointer;" @click="removeDataItem(index)"
              v-if="getDataList.length > 1"></i>
          </div>

        </div>
        <div class="mg-t-10  ">
          <div class="textblod ">否则</div>
          <div class="flex jc-al-c " style="float: right; margin-top: -28px;">
            <vue-tags-input v-model="elseTagLeft" :tags="elseTagsLeft" @focus="setElseFocus('left')"
              @blur="elseInputBlur('left')" placeholder="请选择参数" @before-adding-tag="beforeAddingTag"
              @keyup.native="btKeyUp" class="mg-r-10" @tag-clicked="handleElseTagClick($event, 'left')"
              ref="elseTagLeft" />
            <span class="mg-r-10">=</span>
            <vue-tags-input v-model="elseTagRight" :tags="elseTagsRight" @focus="setElseFocus('right')"
              @blur="elseInputBlur('right')" placeholder="请选择/输入参数" @before-adding-tag="beforeAddingTag"
              @keyup.native="btKeyUp" @tag-clicked="handleElseTagClick($event, 'left')" ref="elseTagLeft" />
          </div>
        </div>
      </div>
    </template>


    <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>
  </div>
</template>

<script>
import VueTagsInput from '@johmun/vue-tags-input';
import formulaItem from "../formulaItem";
import draggable from 'vuedraggable';
import { transformData, generateElementMap, restoreData } from './multiIfElseTools'

export default {
  name: "ifelse",
  components: {
    draggable,
    VueTagsInput,
    formulaItem,
  },
  props: {
    formulainfo: {
      type: Object,
      default: function () {
        return {};
      }
    },
    curele: {
      type: Object,
      default: function () {
        return {};
      }
    },

    formulamap: {
      type: Object,
      default: function () {
        return {};
      }
    },
    isMore: {
      type: Boolean,
      default: false
    },
    moreConditions: {
      type: Array,
      default: function () {
        return [];
      }
    },
    conditionIndex: {//当前是多条件中的哪一个
      type: Number,
      default: 0
    },
    isGetData: {
      type: Boolean,
      default: false
    },
    dataListGet: {
      type: String,
      default: ''
    },
    map: {
      type: String,
      default: ''
    },
    remark: {
      type: String,
      default: '',
    },
    method: {
      type: String,
      default: '',
    }


  },
  data() {
    return {
      symbol: '>=',
      result: '1',


      selectEleFormula: [],
      selectEleFormula2: [],

      curFocusIndex: 0,//当前在哪个输入框
      curSeleEleIndex: -1,//公式文字里面选中的元素索引
      // 多条件下的焦点信息
      multiFocus: {
        conditionIndex: -1,
        innerIndex: -1,
        field: ''
      },
      // 数据获取部分的焦点信息
      dataFocus: {
        index: -1,
        field: ''
      },
      symbolReg: /(\+|-|\*|\/)（.+）/,
      inputVisible: false,
      inputText: '',

      tag1: '',
      tags1: [],
      tag2: '',
      tags2: [],
      tag3: '',
      tags3: [],
      tag4: '',
      tags4: [],
      tag5: '',
      tags5: [],
      symbol1: '',
      // 重构多条件列表结构，包含独立的tags和公式
      conditionList: [
        {
          formulaIfElse: [
            {
              tag2: '',
              tags2: [],
              tag3: '',
              tags3: [],
              symbol1: '',
              logicSymbol: ''
            }
          ],
          tag4: '',
          tags4: [],
          tag5: '',
          tags5: [],
          formula1: [],
          formula2: []
        }
      ],//多条件的条件列表
      // 修改getDataList结构，为每个项添加独立属性
      getDataList: [
        {
          tagWhenLeft: '',
          tagsWhenLeft: [],
          condition: '',
          tagWhenRight: '',
          tagsWhenRight: [],
          tagThenLeft: '',
          tagsThenLeft: [],
          tagThenRight: '',
          tagsThenRight: []
        }
      ],//数据获取列表
      // 否则部分的属性
      elseTagLeft: '',
      elseTagsLeft: [],
      elseTagRight: '',
      elseTagsRight: [],
      elseFocus: '', // 用于跟踪否则部分的焦点


    }
  },
  watch: {
    // 监视getDataList的变化
    getDataList: {
      deep: true,
      handler(newVal) {
        // 只有当数组中有至少一个元素时才处理
        if (newVal.length > 0) {
          // 获取第一个元素的tagWhenLeft值
          const firstTagWhenLeft = newVal[0].tagWhenLeft;
          const firstTagsWhenLeft = newVal[0].tagsWhenLeft;

          // 如果第一个元素有值，同步到其他元素
          if ((firstTagWhenLeft && firstTagWhenLeft.trim() !== '') ||
            (firstTagsWhenLeft && firstTagsWhenLeft.length > 0)) {

            // 遍历从第二个元素开始的所有元素
            for (let i = 1; i < newVal.length; i++) {
              // 避免触发不必要的watch循环
              if (newVal[i].tagWhenLeft !== firstTagWhenLeft ||
                JSON.stringify(newVal[i].tagsWhenLeft) !== JSON.stringify(firstTagsWhenLeft)) {

                this.$set(newVal[i], 'tagWhenLeft', firstTagWhenLeft);
                this.$set(newVal[i], 'tagsWhenLeft', [...firstTagsWhenLeft]);
              }
            }
          }
        }
      }
    }
  },
  mounted() {
    console.log(this.formulainfo, this.isMore, 'this.formulainfo333333');
    let args0 = this.formulainfo.arguments[0];
    let args1 = this.formulainfo.arguments[1];
    let args2 = this.formulainfo.arguments[2];
    this.initCondition(args0);

    if ((typeof args1 == 'string' || (typeof args1 == 'object' && (args1.type == 'Element' || args1.type == 'ParamData'))) &&
      (typeof args2 == 'string' || (typeof args2 == 'object' && (args2.type == 'Element' || args2.type == 'ParamData')))
    ) {
      this.initTFInput(args1, args2);
    } else if (Array.isArray(args1) || Array.isArray(args2)) {
      //
      if (!this.isMore) {
        this.result = '2';
      }
      this.initTFFormula(args1, args2)
    }
    if (this.isMore) {
      this.symbol = 'more';

      console.log(this.moreConditions, ' this.moreConditions;');

      // if(formula1.length>1 || formula2>1){
      //   this.result = '2';
      // }else{
      //   this.result = '1';
      // }
      this.result = this.remark || '1'
      this.conditionList = this.moreConditions.map(item => this.clearTagsIfHasValue(item));

    } else if (this.isGetData) {
      this.symbol = 'getData';
      this.result = '3';
      console.log(this.dataListGet, 'dataListGet');
      const str = this.dataListGet;
      let resultStr = ''
      // 找到第一个左括号的位置
      const startIndex = str.indexOf('(');
      // 找到最后一个右括号的位置
      const endIndex = str.lastIndexOf(')');

      // 提取括号内的内容
      if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
        const result = str.substring(startIndex + 1, endIndex);
        resultStr = result
        console.log(result);
      } else {
        console.log("未找到有效的括号对");
      }

      const resObj = restoreData(resultStr, JSON.parse(this.map))
      console.log(resObj, 'resObj');
      this.getDataList = resObj.getDataList
      this.elseTagLeft = resObj.elseTagLeft;
      this.elseTagsLeft = resObj.elseTagsLeft;
      this.elseTagRight = resObj.elseTagRight;
      this.elseTagsRight = resObj.elseTagsRight;
    }
    else {
      // this.conditionList=[]
    }

    // // 初始化数据获取列表
    // if (this.symbol === 'getData' && this.formulainfo.arguments && this.formulainfo.arguments.length > 0) {
    //   console.log(this.dataListGet,'dataListGet');

    //   // this.initGetDataList(this.formulainfo.arguments[0]);
    // }
  },
  methods: {
    // 初始化数据获取列表
    initGetDataList(data) {
      if (Array.isArray(data)) {
        this.getDataList = data.map(item => ({
          tagWhenLeft: item.tagWhenLeft || '',
          tagsWhenLeft: item.tagsWhenLeft || [],
          condition: item.condition || '',
          tagWhenRight: item.tagWhenRight || '',
          tagsWhenRight: item.tagsWhenRight || [],
          tagThenLeft: item.tagThenLeft || '',
          tagsThenLeft: item.tagsThenLeft || [],
          tagThenRight: item.tagThenRight || '',
          tagsThenRight: item.tagsThenRight || []
        }));
      }
    },

    // 设置数据获取部分的焦点
    setDataFocus(index, field) {
      this.elseFocus = false
      this.dataFocus = { index, field };
    },

    // 数据获取部分输入框失焦处理
    dataInputBlur(index, field) {
      const item = this.getDataList[index];
      const tagNumber = field.replace('tag', '');

      if (item[field]) {
        if (item[`tags${tagNumber}`] && item[`tags${tagNumber}`][0]) {
          this.$emit('uncheck', item[`tags${tagNumber}`][0].id);
        }
        item[`tags${tagNumber}`] = [];
      }

      this.setGetDataCondition();
    },

    // 添加数据获取项
    addDataItem(index) {
      // 获取第一个元素的值作为模板
      const firstItem = this.getDataList[0];

      const newItem = {
        // 新添加的项直接使用第一个元素的tagWhenLeft相关值
        tagWhenLeft: firstItem.tagWhenLeft,
        tagsWhenLeft: [...firstItem.tagsWhenLeft],
        condition: '',
        tagWhenRight: '',
        tagsWhenRight: [],
        tagThenLeft: '',
        tagsThenLeft: [],
        tagThenRight: '',
        tagsThenRight: []
      };

      this.getDataList.splice(index + 1, 0, newItem);
      this.setGetDataCondition();
    },

    // 删除数据获取项
    removeDataItem(index) {
      if (this.getDataList.length > 1) {
        this.getDataList.splice(index, 1);
        this.setGetDataCondition();
      } else {
        this.$message({ type: "warning", message: "至少保留一个数据获取条件" });
      }
    },

    // 设置数据获取条件
    setDataCondition(index) {
      this.setGetDataCondition();
    },

    // 保存数据获取条件到公式信息
    setGetDataCondition() {
      this.formulainfo.arguments[0] = {
        conditions: this.getDataList.map(item => ({
          tagWhenLeft: item.tagWhenLeft,
          tagsWhenLeft: item.tagsWhenLeft,
          condition: item.condition,
          tagWhenRight: item.tagWhenRight,
          tagsWhenRight: item.tagsWhenRight,
          tagThenLeft: item.tagThenLeft,
          tagsThenLeft: item.tagsThenLeft,
          tagThenRight: item.tagThenRight,
          tagsThenRight: item.tagsThenRight
        })),
        elseCase: {
          tagLeft: this.elseTagLeft,
          tagsLeft: this.elseTagsLeft,
          tagRight: this.elseTagRight,
          tagsRight: this.elseTagsRight
        }
      };
    },

    clearTagsIfHasValue(obj) {
      // 复制对象以避免修改原对象
      const result = JSON.parse(JSON.stringify(obj));
      console.log(result, 'result');
      // 检查tags数组中是否存在name不为空的元素
      const hasNonEmptyNameElement = (tagsArray) => {
        return tagsArray && Array.isArray(tagsArray) &&
          tagsArray.length > 0 &&
          tagsArray.some(item => typeof item.name === 'string' && item.name.trim() !== '');
      };

      // 检查tags数组中是否存在name为空字符串的元素
      const hasEmptyNameElement = (tagsArray) => {
        return tagsArray && Array.isArray(tagsArray) &&
          tagsArray.length > 0 &&
          tagsArray.some(item => typeof item.name === 'string' && item.name.trim() === '');
      };
      // 处理顶层的tags4和tags5
      if (hasEmptyNameElement(result.tags4)) {
        result.tags4 = [];  // 赋值为null
      }
      if (hasEmptyNameElement(result.tags5)) {
        result.tags5 = [];  // 赋值为null
      }
      // 处理顶层的tag4和tag5
      if (hasNonEmptyNameElement(result.tags4)) {
        result.tag4 = "";  // 清空对应的tag值
      }
      if (hasNonEmptyNameElement(result.tags5)) {
        result.tag5 = "";  // 清空对应的tag值
      }

      // 处理formulaIfElse数组中的tag2和tag3
      if (result.formulaIfElse && Array.isArray(result.formulaIfElse)) {
        result.formulaIfElse.forEach(item => {
          if (hasNonEmptyNameElement(item.tags2)) {
            item.tag2 = "";   // 清空对应的tag值
          }
          if (hasNonEmptyNameElement(item.tags3)) {
            item.tag3 = "";   // 清空对应的tag值
          }
          if (hasEmptyNameElement(item.tags2)) {
            item.tags2 = [];   // 赋值为null
          }
          if (hasEmptyNameElement(item.tags3)) {
            item.tags3 = [];   // 赋值为null
          }
        });
      }

      return result;
    },

    showSelectEle() {
      this.$set(this.formulainfo, 'showSelectEle', !this.formulainfo.showSelectEle);
    },

    beforeAddingTag() {

    },
    btKeyUp(e) {
      //把中文标点符号转换成英文的
      e.target.value = e.target.value.replace(/“/g, '"');
      e.target.value = e.target.value.replace(/”/g, '"');
      e.target.value = e.target.value.replace(/’/g, "'");
      e.target.value = e.target.value.replace(/‘/g, "'");
    },
    inputHook() {
      console.log(111)
    },

    inputBlur(num) {
      if (this['tag' + num]) {
        if (this['tags' + num] && this['tags' + num][0]) {
          this.$emit('uncheck', this['tags' + num][0].id)
        }
        this['tags' + num] = [];
      }


      if (num >= 1 && num <= 3) {
        this.setCondition();
      } else if (num >= 4 && num <= 5) {
        this.setTF();
      }
    },

    // 多条件下的输入框失焦处理
    inputBlurMulti(conditionIndex, innerIndex, field) {
      const conditionItem = this.conditionList[conditionIndex];
      let target;

      if (innerIndex !== null) {
        target = conditionItem.formulaIfElse[innerIndex];
      } else {
        target = conditionItem;
      }

      if (target[field]) {
        if (target[`tags${field.charAt(3)}`] && target[`tags${field.charAt(3)}`][0]) {
          this.$emit('uncheck', target[`tags${field.charAt(3)}`][0].id);
        }
        target[`tags${field.charAt(3)}`] = [];
      }

      this.setConditionMulti(conditionIndex, innerIndex);
    },

    addText() {
      this.inputVisible = true;
    },

    //把元素加到公式里
    eleAddFormulaHandle(ele) {
      let eleFormula;
      if (this.curFocusIndex == 6) {
        eleFormula = this.selectEleFormula;
      } else if (this.curFocusIndex == 7) {
        eleFormula = this.selectEleFormula2;
      } else {
        return;
      }

      if (ele.tableElementKey) {
        //元素

        //简单语法判断
        if (eleFormula.length != 0) {
          let lastEle = eleFormula[eleFormula.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;
          }
        }

        eleFormula.push({
          type: 'Element',
          name: ele.eName,
          id: ele.id,
          selected: false,
          tableElementKey: ele.tableElementKey,
          children: [],
        })
      } else if (ele.template && ele.example) {
        //运算符号

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

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

      this.setTF();
    },

    // 多条件下添加元素到公式
    eleAddFormulaHandleMulti(ele, conditionIndex, formulaType) {
      const eleFormula = this.conditionList[conditionIndex][formulaType];

      if (ele.tableElementKey) {
        //元素的简单语法判断
        if (eleFormula.length != 0) {
          let lastEle = eleFormula[eleFormula.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;
          }
        }

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

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

      this.setTFMulti(conditionIndex);
    },

    //点选公式中的元素
    eleFormulaClick({ selected, item }, index) {
      let eleFormula;
      if (this.curFocusIndex == 6) {
        eleFormula = this.selectEleFormula;
      } else if (this.curFocusIndex == 7) {
        eleFormula = this.selectEleFormula2;
      } else {
        return;
      }

      if (selected) {
        eleFormula.forEach((ele) => {
          ele.selected = false;
        })
        item.selected = true;
        this.curSeleEleIndex = index;
      } else {
        this.curSeleEleIndex = -1;
      }
    },

    // 多条件下点选公式中的元素
    eleFormulaClickMulti({ selected, item }, index, conditionIndex, formulaType) {
      const eleFormula = this.conditionList[conditionIndex][formulaType];
      console.log(eleFormula, 'eleFormula');

      if (selected) {
        eleFormula.forEach((ele) => {
          ele.selected = false;
        })
        item.selected = true;
        this.curSeleEleIndex = index;
      } else {
        this.curSeleEleIndex = -1;
      }
    },

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

    // 多条件下快捷添加运算符号
    addOperatorMulti(conditionIndex, operator, formulaType) {
      this.eleAddFormulaHandleMulti(this.formulamap[operator], conditionIndex, formulaType);
    },

    //删除点选公式中的元素
    removeSelect() {
      let eleFormula;
      if (this.curFocusIndex == 6) {
        eleFormula = this.selectEleFormula;
      } else if (this.curFocusIndex == 7) {
        eleFormula = this.selectEleFormula2;
      } else {
        return;
      }


      if (this.curSeleEleIndex > -1) {
        eleFormula.splice(this.curSeleEleIndex, 1);
        this.curSeleEleIndex = -1;
      }

      this.setTF();
    },

    // 多条件下删除点选公式中的元素
    removeSelectMulti(conditionIndex, formulaType) {
      const eleFormula = this.conditionList[conditionIndex][formulaType];

      if (this.curSeleEleIndex > -1) {
        eleFormula.splice(this.curSeleEleIndex, 1);
        this.curSeleEleIndex = -1;
      }

      this.setTFMulti(conditionIndex);
    },

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

    // 多条件下添加括号
    addBracketsMulti(conditionIndex, text, type, formulaType) {
      if (this.curSeleEleIndex == Number(this.curSeleEleIndex)) {
        this.eleAddFormulaHandleMulti({
          type: 'Brackets',
          name: text,
          selectIndex: type ? Number(this.curSeleEleIndex) + 1 : this.curSeleEleIndex
        }, conditionIndex, formulaType);

        //如果在左边插入index要增1
        if (!type) {
          this.curSeleEleIndex = Number(this.curSeleEleIndex) + 1;
        }
      }
    },

    //添加输入值
    addTextHandle() {
      let eleFormula;
      if (this.curFocusIndex == 6) {
        eleFormula = this.selectEleFormula;
      } else if (this.curFocusIndex == 7) {
        eleFormula = this.selectEleFormula2;
      } else if (this.symbol === 'more' && this.multiFocus.conditionIndex !== -1 &&
        (this.multiFocus.field === 'formula1' || this.multiFocus.field === 'formula2')) {
        // 多条件下处理
        eleFormula = this.conditionList[this.multiFocus.conditionIndex][this.multiFocus.field];

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

        eleFormula.push({
          type: 'Text',
          name: this.inputText,
          selected: false,
        });

        this.setTFMulti(this.multiFocus.conditionIndex);
        this.inputVisible = false;
        this.inputText = '';
        return;
      } else if (this.symbol === 'getData' && this.dataFocus.index !== -1) {
        // 数据获取部分处理
        const { index, field } = this.dataFocus;
        const item = this.getDataList[index];
        const formulaType = field;

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

        // 添加输入值到相应字段
        const tagField = field;
        const tagsField = `tags${field.replace('tag', '')}`;

        item[tagsField].push({
          type: 'Text',
          name: this.inputText,
          text: this.inputText,
          style: 'background-color: #409EFF'
        });
        item[tagField] = '';

        this.setGetDataCondition();
        this.inputVisible = false;
        this.inputText = '';
        return;
      } else {
        return;
      }

      //简单语法判断
      if (eleFormula.length != 0) {
        let lastEle = eleFormula[eleFormula.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;
      this.inputText = '';
    },

    // 多条件下添加输入值
    addTextMulti(conditionIndex, formulaType) {
      this.multiFocus.conditionIndex = conditionIndex;
      this.multiFocus.field = formulaType;
      this.inputVisible = true;
    },

    setELe(ele) {

      if (this.symbol === 'getData' && this.elseFocus) {
        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: [],
          }
        }

        // 根据当前焦点位置设置对应的标签
        const position = this.elseFocus;
        const tagField = `elseTag${position.charAt(0).toUpperCase() + position.slice(1)}`;
        const tagsField = `elseTags${position.charAt(0).toUpperCase() + position.slice(1)}`;

        // 清除之前选择的元素
        if (this[tagsField] && this[tagsField][0]) {
          this.$emit('uncheck', this[tagsField][0].id);
        }

        // 设置新选择的元素
        obj.text = obj.name;
        obj.style = 'background-color: #409EFF';
        this[tagsField] = [obj];
        this[tagField] = '';

        this.setGetDataCondition();
        return;
      }
      // 处理数据获取情况
      if (this.symbol === 'getData' && this.dataFocus.index !== -1) {
        const { index, field } = this.dataFocus;
        const item = this.getDataList[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: [],
          }
        }

        // 清除之前选择的元素
        const tagsField = `tags${field.replace('tag', '')}`;
        if (item[tagsField] && item[tagsField][0]) {
          this.$emit('uncheck', item[tagsField][0].id);
        }

        // 设置新选择的元素
        obj.text = obj.name;
        obj.style = 'background-color: #409EFF';
        item[tagsField] = [obj];
        item[field] = '';

        this.setGetDataCondition();
        return;
      }

      // 处理多条件情况
      if (this.symbol === 'more' && this.multiFocus.conditionIndex !== -1) {
        const { conditionIndex, innerIndex, field } = this.multiFocus;
        const conditionItem = this.conditionList[conditionIndex];
        let target;

        // 确定目标对象
        if (innerIndex !== null) {
          target = conditionItem.formulaIfElse[innerIndex];
        } else {
          target = conditionItem;
        }

        // 处理公式类型的字段
        if (field === 'formula1' || field === 'formula2') {
          this.eleAddFormulaHandleMulti(ele, conditionIndex, field);
          return;
        }

        // 处理标签类型的字段
        if (target && field) {
          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 (target[`tags${field.charAt(3)}`] && target[`tags${field.charAt(3)}`][0]) {
            this.$emit('uncheck', target[`tags${field.charAt(3)}`][0].id);
          }

          // 设置新选择的元素
          obj.text = obj.name;
          obj.style = 'background-color: #409EFF';
          target[`tags${field.charAt(3)}`] = [obj];
          target[field] = '';

          // 更新条件
          this.setConditionMulti(conditionIndex, innerIndex);
        }
        return;
      }

      // 原逻辑处理单条件情况
      if (this.curFocusIndex) {
        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 (this.curFocusIndex == 6 || this.curFocusIndex == 7) {
          this.eleAddFormulaHandle(ele)
        } else {
          if (this['tags' + this.curFocusIndex] && this['tags' + this.curFocusIndex][0]) {
            this.$emit('uncheck', this['tags' + this.curFocusIndex][0].id)
          }

          obj.text = obj.name;
          obj.style = 'background-color: #409EFF';
          this['tags' + this.curFocusIndex] = [obj];
          this['tag' + this.curFocusIndex] = '';

          if (this.curFocusIndex == 4 || this.curFocusIndex == 5) {
            this.setTF();
          } else {
            this.setCondition();
          }
        }
      }
    },

    // 设置多条件下的焦点
    setMultiFocus(conditionIndex, innerIndex, field) {
      this.multiFocus = {
        conditionIndex,
        innerIndex,
        field
      };
    },

    // 检查是否是当前焦点
    isCurFocus(conditionIndex, innerIndex, field) {
      return this.multiFocus.conditionIndex === conditionIndex &&
        this.multiFocus.innerIndex === innerIndex &&
        this.multiFocus.field === field;
    },

    //初始化真假值判断if(xxx)部分
    initCondition(args0) {


      if (args0) {
        if (args0.length == 3) {
          //运算符号
          this.symbol = args0[1];

          //第二个空
          if ((typeof args0[0]) == 'object' && (args0[0].type == 'Element' || args0[0].type == 'ParamData')) {
            let ele = args0[0];
            this.tags2 = [
              Object.assign({
                text: ele.name,
                style: 'background-color: #409EFF',
              }, ele)]
          } else if ((typeof args0[0]) == 'string') {
            this.tag2 = args0[0];
          }

          //第三个空
          if ((typeof args0[2]) == 'object' && (args0[2].type == 'Element' || args0[2].type == 'ParamData')) {
            let ele = args0[2];
            this.tags3 = [
              Object.assign({
                text: ele.name,
                style: 'background-color: #409EFF',
              }, ele)]
          } else if ((typeof args0[2]) == 'string') {
            this.tag3 = args0[2];
          }
        } else if (args0.length == 7) {
          //运算符号
          this.symbol = args0[1] + args0[3] + args0[5];

          //第一个空
          if ((typeof args0[0]) == 'object' && (args0[0].type == 'Element' || args0[0].type == 'ParamData')) {
            let ele = args0[0];
            this.tags1 = [
              Object.assign({
                text: ele.name,
                style: 'background-color: #409EFF',
              }, ele)]
          } else if ((typeof args0[0]) == 'string') {
            this.tag1 = args0[0];
          }

          //第二个空
          if ((typeof args0[2]) == 'object' && (args0[2].type == 'Element' || args0[2].type == 'ParamData')) {
            let ele = args0[2];
            this.tags2 = [
              Object.assign({
                text: ele.name,
                style: 'background-color: #409EFF',
              }, ele)]
          } else if ((typeof args0[2]) == 'string') {
            this.tag2 = args0[2];
          }

          //第三个空
          if ((typeof args0[6]) == 'object' && (args0[6].type == 'Element' || args0[6].type == 'ParamData')) {
            let ele = args0[6];
            this.tags3 = [
              Object.assign({
                text: ele.name,
                style: 'background-color: #409EFF',
              }, ele)]
          } else if ((typeof args0[6]) == 'string') {
            this.tag3 = args0[6];
          }
        } else if (typeof args0 == 'object' && (args0.type == 'Element' || args0.type == 'ParamData')) {
          let ele = args0;
          this.tags2 = [
            Object.assign({
              text: ele.name,
              style: 'background-color: #409EFF',
            }, ele)]
        }
      }
    },

    // 初始化多条件数据
    initMultiConditions(args0) {
      if (Array.isArray(args0)) {
        this.conditionList = args0.map(condition => {
          // 处理内部条件列表
          const formulaIfElse = Array.isArray(condition.formulaIfElse) ?
            condition.formulaIfElse.map(inner => ({
              tag2: inner.tag2 || '',
              tags2: inner.tags2 || [],
              tag3: inner.tag3 || '',
              tags3: inner.tags3 || [],
              symbol1: inner.symbol1 || '',
              logicSymbol: inner.logicSymbol || ''
            })) : [{
              tag2: '',
              tags2: [],
              tag3: '',
              tags3: [],
              symbol1: '',
              logicSymbol: ''
            }];

          return {
            formulaIfElse,
            tag4: condition.tag4 || '',
            tags4: condition.tags4 || [],
            tag5: condition.tag5 || '',
            tags5: condition.tags5 || [],
            formula1: condition.formula1 || [],
            formula2: condition.formula2 || []
          };
        });
      }
    },

    //写入参数真假值判断if(xxx)部分
    setCondition() {
      if (this.symbol == '<&&<' || this.symbol == '<=&&<=' || this.symbol !== 'more' && this.symbol !== 'getData') {
        // 处理单条件情况
        if (this.symbol == '<&&<' || this.symbol == '<=&&<=') {
          let arr = new Array(7).fill('');
          let symbolArr = this.symbol.split('&&');
          if (this.tags1.length == 0) {
            arr[0] = this.tag1;
          } else {
            arr[0] = this.tags1[0];
          }
          arr[1] = symbolArr[0];
          if (this.tags2.length == 0) {
            arr[2] = this.tag2;
            arr[4] = this.tag2;
          } else {
            arr[2] = this.tags2[0];
            arr[4] = this.tags2[0];
          }
          arr[3] = '&&';
          arr[5] = symbolArr[1];
          if (this.tags3.length == 0) {
            arr[6] = this.tag3;
          } else {
            arr[6] = this.tags3[0];
          }
          this.formulainfo.arguments[0] = arr;
        } else {
          let arr = new Array(3).fill('');
          if (this.tags2.length == 0) {
            arr[0] = this.tag2;
          } else {
            arr[0] = this.tags2[0];
          }
          arr[1] = this.symbol;
          if (this.tags3.length == 0) {
            arr[2] = this.tag3;
          } else {
            arr[2] = this.tags3[0];
          }
          this.formulainfo.arguments[0] = arr;
        }
      } else if (this.symbol == 'more') {
        // this.result=this.remark||'1'
        // 处理多条件情况
        this.formulainfo.arguments[0] = this.conditionList.map(condition => ({
          formulaIfElse: condition.formulaIfElse.map(inner => ({
            tag2: inner.tag2,
            tags2: inner.tags2,
            tag3: inner.tag3,
            tags3: inner.tags3,
            symbol1: inner.symbol1,
            logicSymbol: inner.logicSymbol
          })),
          tag4: condition.tag4,
          tags4: condition.tags4,
          tag5: condition.tag5,
          tags5: condition.tags5,
          formula1: condition.formula1,
          formula2: condition.formula2
        }));
      } else if (this.symbol == 'getData') {
        this.result = '3'
        // 数据获取情况已在setGetDataCondition中处理
      }
    },

    // 多条件下设置条件
    setConditionMulti(conditionIndex, innerIndex) {
      this.setCondition();
    },

    //初始化输入框的真假值
    initTFInput(args1, args2) {
      if ((typeof args1) == 'object' && (args1.type == 'Element' || args1.type == 'ParamData')) {
        let ele = args1;
        this.tags4 = [
          Object.assign({
            text: ele.name,
            style: 'background-color: #409EFF',
          }, ele)]
      } else if ((typeof args1) == 'string') {
        this.tag4 = args1;
      }

      if ((typeof args2) == 'object' && (args2.type == 'Element' || args2.type == 'ParamData')) {
        let ele = args2;
        this.tags5 = [
          Object.assign({
            text: ele.name,
            style: 'background-color: #409EFF',
          }, ele)]
      } else if ((typeof args2) == 'string') {
        this.tag5 = args2;
      }
    },

    //初始化运算的真假值
    initTFFormula(args1, args2) {
      if (Array.isArray(args1)) {
        args1.forEach((a, index) => {
          if (typeof a == 'string') {
            this.$set(args1, index, {
              type: 'Text',
              name: a,
              selected: false,
            })
          }
        })
        this.selectEleFormula = args1;
      } else if (typeof args1 == 'object' && (args1.type == 'Element' || args1.type == 'ParamData')) {
        this.selectEleFormula = [Object.assign({}, args1)];
      } else if (typeof args1 == 'string') {
        this.selectEleFormula = [{
          type: 'Text',
          name: args1,
          selected: false,
        }]
      }

      if (Array.isArray(args2)) {
        args2.forEach((a, index) => {
          if (typeof a == 'string') {
            this.$set(args2, index, {
              type: 'Text',
              name: a,
              selected: false,
            })
          }
        })
        this.selectEleFormula2 = args2;
      } else if (typeof args2 == 'object' && (args2.type == 'Element' || args2.type == 'ParamData')) {
        this.selectEleFormula2 = [Object.assign({}, args2)];
      } else if (typeof args2 == 'string') {
        this.selectEleFormula2 = [{
          type: 'Text',
          name: args2,
          selected: false,
        }]
      }
    },

    //写入参数真假值
    setTF() {
      if (this.symbol !== 'more' && this.symbol !== 'getData') {
        if (this.result == 1) {
          if (this.tags4.length == 0) {
            this.formulainfo.arguments[1] = this.tag4;
          } else {
            this.formulainfo.arguments[1] = this.tags4[0];
          }
          if (this.tags5.length == 0) {
            this.formulainfo.arguments[2] = this.tag5;
          } else {
            this.formulainfo.arguments[2] = this.tags5[0];
          }
        } else if (this.result == 2) {
          this.formulainfo.arguments[1] = this.selectEleFormula;
          this.formulainfo.arguments[2] = this.selectEleFormula2;
        }
      }
      if (this.symbol == 'more') {
        console.log(this.result, 'this.result');

        this.remark = this.result
      }
      // 多条件情况在setCondition中处理
    },

    // 多条件下设置真假值
    setTFMulti(conditionIndex) {
      this.setCondition();
    },

    //添加条件
    addCondition(index) {
      // 复制最后一个条件的结构作为新条件的基础
      const newCondition = JSON.parse(JSON.stringify(this.conditionList[index]));
      // 清空值但保留结构
      newCondition.formulaIfElse = [
        {
          tag2: '',
          tags2: [],
          tag3: '',
          tags3: [],
          symbol1: '',
          logicSymbol: ''
        }
      ];
      newCondition.tag4 = '';
      newCondition.tags4 = [];
      newCondition.tag5 = '';
      newCondition.tags5 = [];
      newCondition.formula1 = [];
      newCondition.formula2 = [];

      this.conditionList.splice(index + 1, 0, newCondition);
      this.setCondition();
    },

    //删除条件
    removeCondition(index) {
      if (this.conditionList.length > 1) {
        this.conditionList.splice(index, 1);
        this.setCondition();
      } else {
        this.$message({ type: "warning", message: "至少保留一个条件" });
      }
    },

    // 添加内部条件项
    addConditionItem(conditionIndex, innerIndex) {
      const newInnerItem = {
        tag2: '',
        tags2: [],
        tag3: '',
        tags3: [],
        symbol1: '',
        logicSymbol: ''
      };

      this.conditionList[conditionIndex].formulaIfElse.splice(innerIndex + 1, 0, newInnerItem);
      this.setCondition();

    },

    // 删除内部条件项
    removeConditionItem(conditionIndex, innerIndex) {
      if (this.conditionList[conditionIndex].formulaIfElse.length > 1) {
        this.conditionList[conditionIndex].formulaIfElse.splice(innerIndex, 1);
        this.setCondition();
      } else {
        this.$message({ type: "warning", message: "至少保留一个条件项" });
      }
    },
    // 设置否则部分的焦点
    setElseFocus(position) {
      this.elseFocus = position;
    },

    // 否则部分输入框失焦处理
    elseInputBlur(position) {
      const tagField = `elseTag${position.charAt(0).toUpperCase() + position.slice(1)}`;
      const tagsField = `elseTags${position.charAt(0).toUpperCase() + position.slice(1)}`;

      if (this[tagField]) {
        if (this[tagsField] && this[tagsField][0]) {
          this.$emit('uncheck', this[tagsField][0].id);
        }
        this[tagsField] = [];
      }

      this.setGetDataCondition();
    },
    //返回数据获取相关的数据
    getDataConditionData() {
      const inputData = {
        // 获取数据列表的函数
        getDataList: this.getDataList,
        // 左侧else标签
        elseTagLeft: this.elseTagLeft,
        elseTagsLeft: this.elseTagsLeft,
        // 左侧else标签集合
        elseTagRight: this.elseTagRight,
        elseTagsRight: this.elseTagsRight,
      }
      console.log(inputData, 'inputData');

      const result = transformData(inputData);
      const mapEle = generateElementMap(inputData)
      return {
        // 获取数据列表的函数
        getDataList: this.getDataList,
        elseTagsLeft: this.elseTagsLeft,
        // 左侧else标签
        elseTagLeft: this.elseTagLeft,
        // 左侧else标签集合
        elseTagRight: this.elseTagRight,
        elseTagsRight: this.elseTagsRight,
        result,
        mapEle


      };
    },
    //选择元素回显处理
    handleTagClick(info, index) {
      console.log(info, 'info');
      const { tag } = info;
      this.curFocusIndex = index
      const refName = `tagsInput${this.curFocusIndex}`;
      this.$refs[refName].focus(); // 动态获取ref并调用focus方法
      this.$emit('clickTag', tag)
    },
    // 处理多条件下的标签点击事件
    handleMultiTagClick(info, conditionIndex, innerIndex, field) {
      const { tag } = info;
      // 设置当前焦点信息
      this.setMultiFocus(conditionIndex, innerIndex, field);
      // 获取对应的ref并聚焦
      const refName = `multiTagsInput_${conditionIndex}_${innerIndex}_${field}`;
      console.log(refName, 'refName');
      console.log(this.$refs, 'this.$refs');

      if (this.$refs[refName]) {
        this.$refs[refName][0].focus();
      }
      // 向父组件传递点击的标签信息
      this.$emit('clickTag', tag);
    },
    // 处理数据获取部分（循环项）的标签点击
    handleDataTagClick(info, index, field) {
      const { tag } = info;
      // 1. 设置当前焦点
      this.setDataFocus(index, field);
      // 2. 聚焦到当前输入框
      const refName = `dataTag_${index}_${field}`;
      const tagInput = this.$refs[refName];
      if (tagInput) {
        const instance = Array.isArray(tagInput) ? tagInput[0] : tagInput;
        if (instance && typeof instance.focus === 'function') {
          instance.focus();
        }
      }
      // 3. 向父组件传递选中的tag
      this.$emit('clickTag', tag);
    },

    // 处理“否则”部分的标签点击
    handleElseTagClick(info, position) {
      const { tag } = info;
      // 1. 设置当前焦点
      this.setElseFocus(position);
      // 2. 聚焦到当前输入框
      const refName = `elseTag${position.charAt(0).toUpperCase() + position.slice(1)}`;
      const instance = this.$refs[refName];
      if (instance && typeof instance.focus === 'function') {
        instance.focus();
      }
      // 3. 向父组件传递选中的tag
      this.$emit('clickTag', tag);
    },

  }
}
</script>
<style scoped lang="scss">
.textblod {
  font-weight: bold;
  font-size: 18px;
}

.sele-ele-box {
  height: 100px;
  padding: 10px;
  // margin-top: 10px;
}

.icon-box .el-link {
  font-size: 20px;
  margin-right: 10px;
}

.icon-btn {
  color: #409EFF;
  cursor: 409EFF;
}

.border-green {
  border-color: green !important;
}

.border-grey {
  border: 1px solid #ddd;
}
</style>
