<template>
  <div>
    <div class="flex jc-al-c">
      <span>允许偏差值范围：</span>
      <el-select v-model="symbol" @change="setCondition()" size="medium" placeholder="请选择">
        <el-option label="【min,max】" value="【min,max】"></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 class="mg-l-20 mg-r-10">模式</span>
      <el-select v-model="result" size="medium" @change="setModel" placeholder="请选择">
        <el-option label="普通" value="1"></el-option>
        <el-option label="自定义" value="2"></el-option>
      </el-select>
      <el-button class="mg-l-10" size="small" type="info" @click="showSelectEle">选择参数</el-button>
    </div>
    
    <div class="flex jc-al-c mg-t-20" v-if="result == 1">
      <span style="width:60px"></span>
      <template v-if="!(symbol == '<' || symbol== '≤')">
        <span class="textblod mg-r-10"></span>
        <vue-tags-input v-model="tag1" :tags="tags1" @focus="curFocusIndex = 1" @blur="inputBlur(1)" placeholder="输入/参数" @before-adding-tag="beforeAddingTag"  @tag-clicked="handleTagClick($event,1)" ref="tagsInput1"/>
        <span style="width:20px"></span>
      </template>
      <template v-if="!(symbol == '>' || symbol== '≥')">
        <span class="textblod mg-r-10"></span>
        <vue-tags-input v-model="tag2" :tags="tags2" @focus="curFocusIndex = 2" @blur="inputBlur(2)" placeholder="输入/参数" @before-adding-tag="beforeAddingTag"  @tag-clicked="handleTagClick($event,2)" ref="tagsInput2"/>
      </template>
    </div>

    <div class="mg-t-20" v-if="result == 2">
      <div class="flex" v-show="!(symbol == '<' || symbol== '≤')">
        <span class="textblod mg-r-10">参数1</span>
        <div class="border-grey sele-ele-box flex1" :class="{'border-green':curFocusIndex == 3}" @click="curFocusIndex = 3">
          <div class="flex jc-sb mg-b-20">
            <!-- <div>定位数据位置:</div> -->
            <div class="icon-box">
              <el-link :underline="false" icon="el-icon-delete" type="danger" @click="removeSelect"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('+')" icon="el-icon-circle-plus-outline"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('-')" icon="el-icon-remove-outline"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('*')" icon="el-icon-circle-close"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('%')">÷</el-link>
            </div>
            <div>
              <el-link :underline="false" type="primary" class="mg-r-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" v-show="!(symbol == '>' || symbol== '≥')">
        <span class="textblod mg-r-10">参数2</span>
        <div class="border-grey sele-ele-box flex1" :class="{'border-green':curFocusIndex == 4}" @click="curFocusIndex = 4">
          <div class="flex jc-sb mg-b-20">
            <!-- <div>定位数据位置:</div> -->
            <div class="icon-box">
              <el-link :underline="false" icon="el-icon-delete" type="danger" @click="removeSelect"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('+')" icon="el-icon-circle-plus-outline"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('-')" icon="el-icon-remove-outline"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('*')" icon="el-icon-circle-close"></el-link>
              <el-link :underline="false" type="primary" @click="addOperator('%')">÷</el-link>
            </div>
            <div>
              <el-link :underline="false" type="primary" class="mg-r-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>

    <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';
export default {
  name: "deviationRange",
  components: {
    draggable,

    VueTagsInput,

    formulaItem,
  },
  props: {
    formulainfo: {
      type: Object,
      default: function () {
        return {};
      }
    },
    formulamap:{
      type: Object,
      default: function () {
        return {};
      }
    }
  },
  data(){
    return{
      symbol:'【min,max】',
      result:'1',

      rangeReg:/^[([](.*),(.*)[)\]]$/,

      curFocusIndex:0,//当前在哪个输入框
      curSeleEleIndex:-1,//公式文字里面选中的元素索引
      symbolReg:/(\+|-|\*|\/)（.+）/,
      inputVisible:false,
      inputText:'',

      selectEleFormula:[],
      selectEleFormula2:[],

      tag1: '',
      tags1: [],
      tag2: '',
      tags2: [],
    }
  },
  mounted(){
    //console.log(this.formulainfo)
    this.initDatas();
  },
  methods:{
    initDatas(){
      this.symbol = this.formulainfo.datas.symbol;

      this.result = this.formulainfo.datas.model;

      if(Array.isArray(this.formulainfo.datas.arguments1)&& this.formulainfo.datas.arguments1.length>1
        || Array.isArray(this.formulainfo.datas.arguments2)&& this.formulainfo.datas.arguments2.length>1){
          this.selectEleFormula = this.formulainfo.datas.arguments1;
          this.selectEleFormula2 = this.formulainfo.datas.arguments2;
      }else{
        //console.log(typeof this.formulainfo.datas.arguments1)
        if(typeof this.formulainfo.datas.arguments1 == 'string'){
          this.tag1 = this.formulainfo.datas.arguments1;
        }else{
          this.tags1 = this.formulainfo.datas.arguments1;
        }

        if(typeof this.formulainfo.datas.arguments2 == 'string'){
          this.tag2 = this.formulainfo.datas.arguments2;
        }else{
          this.tags2 = this.formulainfo.datas.arguments2;
        }
      }
    },

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

    beforeAddingTag(){

    },

    setCondition(){
      this.formulainfo.datas.symbol = this.symbol;
    },

    setModel(){
      this.formulainfo.datas.model = this.result;
    },

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

      //console.log(this['tag'+num])
      this.formulainfo.datas['arguments'+num] = this['tag'+num];
    },

    setELe(ele){
      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 == 3 || this.curFocusIndex ==4){
          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] = '';

          this.formulainfo.datas['arguments'+this.curFocusIndex] = [obj];
        }
      }
    },

        //把元素加到公式里
    eleAddFormulaHandle(ele){
      let eleFormula;
      if(this.curFocusIndex == 3){
        eleFormula = this.selectEleFormula;
      }else if(this.curFocusIndex == 4){
        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.setArguments(eleFormula);
    },

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

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

    //添加括号
    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;
        }
      }
    },

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


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

    setArguments(eleFormula){
      switch (this.curFocusIndex) {
        case 3:
          this.formulainfo.datas.arguments1 = eleFormula;
          break;
        case 4:
          this.formulainfo.datas.arguments2 = eleFormula;
          break;
      }
    },

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

       //添加输入值
    addTextHandle(){
      let eleFormula;
      if(this.curFocusIndex == 3){
        eleFormula = this.selectEleFormula;
      }else if(this.curFocusIndex == 4){
        eleFormula = this.selectEleFormula2;
      }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;
    },
    handleTagClick(info,index) {
     
       const {tag}=info;

       
      this.curFocusIndex = index
     
      
      // 调用对应输入框的 focus() 方法
        if (this.curFocusIndex === 1) {
          this.$refs.tagsInput1.focus(); // 注意：确保组件已挂载，使用可选链避免报错
        } else {
          this.$refs.tagsInput2.focus();
        }

  
       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;
  }
</style>