<template>
  <el-dialog
   class="dialog-set"
    :visible.sync="visible"
    width="70%"
    append-to-body
  >
    <div slot="title" class="dialog-title">
        <div>
             <i class="el-icon-s-tools" ></i>
             <span style="margin-left: 10px;">条件设置</span>
        </div>
      <div class="marginTop-10">设置样品信息和技术指标的关联关系，满足条件时回显对应参数</div>

    </div>
    <div class="conditions-container">
      <!-- 左侧条件列表 -->
      <div class="conditions-left">
        <div class="condition-header">
            <i class="el-icon-s-operation" style="color: rgb(46, 123, 115);"></i>
          <span>参数列表</span>
          
        </div>
        <div class="condition-list">
          <div class="condition-item">
           <span 
                v-for="(item, index) in paramList" 
                :key="index"
                :class="{ active: activeIndex === index }"
                @click="handleSelect1(index, item)"
               

                >
                {{ item.symbolName }}
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧操作列表 -->
      <div class="conditions-right">
       <div class="condition-header1">
            <div class="header-left">
                <i class="el-icon-s-operation" style="color: rgb(46, 123, 115);"></i>
                <span>条件列表</span>
            </div>
            <div class="header-right">
                <el-button 
                type="primary"
                size="small"
                :style="{ background: 'rgb(37, 80, 162)', borderColor: 'rgb(37, 80, 162)' }"
                @click="addCondition"
                >
                <i class="el-icon-plus"></i>
                添加条件
                </el-button>
                <el-button 
                type="success" 
                size="small"
                @click="saveCondition"
                >
                <i class="el-icon-check"></i>
                保存条件
                </el-button>
            </div>
            </div>
        <div class="condition-list">
          <div class="condition-item1">
           <div 
                v-for="(item, index) in paramList[activeIndex].standardInfos" 
                :key="index"
              
                >
          <div>
            <span>
                <div class="condition-header-content">
                <div style="color: black;">
                    {{item.name}}
                </div>
                <i class="el-icon-close" @click.stop="handleDeleteItem(item,index)"></i>
                </div>
                <div class="code-list">
                <div  class="code-item">
                    {{ item.standardInfoGroupNameVO.name }}
                </div>
                </div>
            </span>
            </div>
                
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="result-container">
            <div class="condition-header">
               <i class="el-icon-connection" style="color: rgb(46, 123, 115);"></i>
            <span>关联关系</span>
            </div>
            <div class="link-list">
                <div v-for="(item, index) in linkListData" :key="index" class="link-item" :class="{ clicked: item.clicked }" @click="toggleClick(item, index)">
                    <i class="el-icon-close" @click.stop="handleDeleteLinkItem(item,index)"></i>
                    <div class="link-name">
                        <span>{{ item.symbolName }}</span>
                    </div>
                  <div>
                       <i class="el-icon-connection" style="color: black; font-size: larger;"></i>
                  </div>
                  <div class="code-list">
                    <div v-for="(codeItem, codeIndex) in item.standardInfos" :key="codeIndex" class="code-item">
                        <div class="code-title">{{ codeItem.name }}</div>
                        <div class="code-detail">{{ codeItem.standardInfoGroupNameVO.name }}</div>
                    </div>

                  </div>
                 
                </div>
            </div>
            
          </div>

    
    <div slot="footer" class="dialog-footer">
   
      <el-button type="primary" @click="handleConfirm" :style="{ background: 'rgb(37, 80, 162)', borderColor: 'rgb(37, 80, 162)' }">保存</el-button>
    </div>

     <el-dialog
        class="dialog-set"
        :visible.sync="addDialogVisible"
        width="30%"
        append-to-body
        close-on-click-modal="false"
        >
         <div slot="title" class="dialog-title">
        <div>
             <i class="el-icon-plus" ></i>
             <span style="margin-left: 10px;">添加条件</span>
        </div>
      <div class="marginTop-10">同次设置的条件为“或者”关系，不同次设置的条件为“并且”关系</div>

    </div>
        <el-form ref="addForm" :model="addForm" label-width="80px">
            <el-form-item label="样品信息">
            <el-select v-model="addForm.codeNameId" placeholder="请选择"  style="width: 100%;"  @change="handleSelectCodeName">
                <el-option
                v-for="item in sampleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            </el-form-item>
            <el-form-item label="基础信息">
            <el-select v-model="addForm.codeValueList" placeholder="请选择" multiple style="width: 100%;" @change="handleSelectCode">
                <el-option
                v-for="item in basicOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
           
       
            <el-button type="primary" @click="confirmAdd" :style="{ background: 'rgb(37, 80, 162)', borderColor: 'rgb(37, 80, 162)' }">确认添加</el-button>
        </div>
    </el-dialog>  
  </el-dialog>
      
       
</template>

<script>
import {getInfoPage,saveConditionSet,getConditionSet,deleteConditionSet } from "@/api/ruleManage/fileRule.js";
export default {
  name: 'ConditionsSet',
  data() {
    return {
      visible: false,
       paramList: [
        {
          symbolName: '',
          standardInfos:[
            {name: '', 
            rightStandardInfos: [
              {}
            ],
            standardInfoGroupNameVO:{
              name: ''
            }

            
          },
            {codeName: '', codeValue: []},
          ]

        }
       ] , // 参数列表数据
       activeIndex: 0, // 当前选中的参数索引
       addDialogVisible: false,
        addForm: {
            codeName: '',
            codeValueList: [],
            codeValueName: '',
            codeNameId: ''
        },
        sampleOptions: [
          
            // 添加更多选项...
        ],
        basicOptions: [],
      linkListData: [
       
           
      ], // 关联关系数据
      id:'', // 传入的ID规范文件id
      jId:'',//技术指标Id
      addObj:{}


    }
  },
  methods: {
    show(val,id,Jid) {
      console.log(id,'id');
      this.jId = Jid
      this.id = id
      this.getSampleOptions(id)
      this.visible = true
      if(val.length > 0&&val[0].symbolName) {
       this.paramList=val
       val.forEach((item,index)=>{
          this.handleSelect(index,item)
       })
      //  this.activeIndex = 0


       
      }else{
        this.paramList = []
      }
      this.activeIndex = 0
      //获取关联关系数据

      this.getLinkSetData(this.id, this.jId);
    },
    //获取样品信息列表
     getSampleOptions(id){
             getInfoPage({
                current:1,
                size:100,
                type: 1,
                standardId: id,
              }).then((res) => {
                this.ruleLoading = false;
                if (res.data.code === 200) {
                  this.sampleOptions= res.data.data.records.map(item => ({
                    value: item.id,
                    label: item.name,
                    info:item.info
                  }));
                  // 
                } else {
                  this.sampleOptions = [];
                }
              });
      },
    hide() {
      this.visible = false  
    },
    handleCancel() {
      this.hide()
      this.$emit('cancel')
    },
    handleConfirm() {

      saveConditionSet(this.linkListData,this.id).then((res)=>{
        if(res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
          })
        }else{
          this.$message({
            type: 'error',
            message: res.data.msg,
          })
        }
      })
      this.hide()
      this.$emit('confirm')
    },
    handleDeleteLinkItem(item,index){
      const {groupId}=item
      if(!groupId){
         this.linkListData.splice(index, 1);
         return
      }
        this.$confirm('删除后，数据将无法恢复，是否确认删除!', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
  
            deleteConditionSet({leftId:item.id,groupId:item.groupId}).then((res) => {
              if(res.data.code==200){
                this.$message.success(res.data.msg);
              
                this.linkListData.splice(index, 1);
                this.getLinkSetData(this.id, this.jId);
              }else{
                this.$message.error(res.data.msg);
              }
            });
          }).catch(() => {
            this.$message.info('已取消删除');
          })
    },
    addCondition() {
      // 添加条件逻辑
           this.addDialogVisible = true
           this.addForm = {}
   
           this.basicOptions = []

    },
    addOperation() {
      // 添加操作逻辑
    },
  async handleSelect(index,item) {

    

      this.paramList[index].standardInfos = []
    },
    async handleSelect1(index,item) {
      this.activeIndex = index


  //  this.linkListData.forEach(ele=>{
  //   ele.clicked = false

  //  })
       const hasClicked = this.linkListData.some(item => item.clicked === true);
        console.log(hasClicked, 'hasClicked');
        if(!hasClicked) {
          item.standardInfos=[]
           this.addObj.standardInfos=[]
        }
       

      
    },
    handleSelectCode(values) {
      if (!values || values.length === 0) {
        this.addForm.codeValueName = '';
        return;
      }
      
      // 根据选中的value值找到对应的label
      const selectedLabels = values.map(value => {
        const option = this.basicOptions.find(opt => opt.value === value);
        return option ? option.label : '';
      });

      this.addForm.codeValueName = selectedLabels.join('/');
         this.addForm.codeValue = values
    },
    handleSelectCodeName(value) {
 

      if (!value) {
        this.addForm.codeName = '';
        return;
      }
      this.basicOptions = []
      this.sampleOptions.forEach(option => {
        if (option.value === value) {
          this.addForm.codeName = option.label;
       
        }
      });
       const selectedOption = this.sampleOptions.find(option => option.value === value);
      this.basicOptions = selectedOption ? selectedOption.info.filter(item => item.name !== '').map(item => ({
        value: item.id,
        label: item.name
      })) : [];
       
    },
    handleDeleteItem(item, index) {
      this.paramList[this.activeIndex].standardInfos.splice(index, 1);
      this.addObj={
         ... this.paramList[this.activeIndex],
         standardInfos:this.paramList[this.activeIndex].standardInfos,
          clicked:false
      }
      this.$forceUpdate();
     
    },
    confirmAdd() {
      if (!this.addForm.codeName || !this.addForm.codeValue) return this.$message.error('请选择样品信息和基础信息')
      this.paramList[this.activeIndex].standardInfos.push(
        {name: this.addForm.codeName,
         standardInfoGroupNameVO: 
              {name:this.addForm.codeValueName,ids:this.addForm.codeValue}
       },
      )
      this.addObj={
        ... this.paramList[this.activeIndex],
        standardInfos: this.paramList[this.activeIndex].standardInfos,
         clicked:false
      }
      this.addDialogVisible = false
      this.addForm = {
        codeName: '',
        codeValue: []
      }
   
    },
          //保存条件
      saveCondition() {

         const {standardInfos}=this.addObj
      
         
        if(!standardInfos||standardInfos.length === 0) {
          return this.$message.error('请先添加条件')
        }
           const hasClicked = this.linkListData.some(item => item.clicked === true);
        console.log(hasClicked,'hasClicked');
          let obj=JSON.parse(JSON.stringify(this.addObj));
          console.log(obj,'obj');
          
          if (!hasClicked) {
            // 如果不存在，则将 addObj 添加到数组中
          

            this.linkListData.push(obj);
          }else{
              const clickedItem = this.linkListData.find(item => item.clicked === true);
               if (clickedItem) {
                   clickedItem.standardInfos =obj.standardInfos;
                   clickedItem.symbolName=obj.symbolName
                   clickedItem.id=obj.id


                }
          }
          this.paramList[this.activeIndex].standardInfos = []
                this.linkListData .forEach(ele => {
        ele.clicked = false;

      });
    this.addObj.standardInfos = []

   
      },
     toggleClick(item, index) {
        this.linkListData.forEach(listItem => {
          this.$set(listItem, 'clicked', false);
        });
        this.$set(item, 'clicked', !item.clicked);
        let clickedIndex = this.paramList.findIndex(listItem => listItem.id === item.id);
        console.log(clickedIndex, 'clickedIndex');
        this.activeIndex = clickedIndex;
        this.paramList[clickedIndex].standardInfos = JSON.parse(JSON.stringify(item.standardInfos));
        this.addObj = { ...item };

        console.log(item, 'item');
        
      },
    // 获取条件设置
      async getConditionSetData(id, groupId, leftId) {
        try {
          const res = await getConditionSet({ id, groupId,leftId });
          if (res.data.code === 200) {
            console.log(res.data.data, '获取的条件设置数据');
            return res.data.data; // 直接返回数据
          } else {
            this.$message.error(res.data.msg);
            throw new Error(res.data.msg); // 抛出错误，以便在调用处处理
          }
        } catch (error) {
          // 这里可以添加额外的错误处理逻辑，例如记录日志
          throw error; // 重新抛出错误，以便在调用处捕获
        }
      },
      //获取关联关系数据
     
      async getLinkSetData(id, groupId) {
        try {
          const res = await getConditionSet({ id, groupId });
          if (res.data.code === 200) {
            console.log(res.data.data, '获取的关系数据');
            this.linkListData = res.data.data; // 直接返回数据

           
          } else {
            this.$message.error(res.data.msg);
            throw new Error(res.data.msg); // 抛出错误，以便在调用处处理
          }
        } catch (error) {
          // 这里可以添加额外的错误处理逻辑，例如记录日志
          throw error; // 重新抛出错误，以便在调用处捕获
        }
      }
  }
}
</script>

<style lang="scss" scoped>
.conditions-container {
  display: flex;
  gap: 20px;
  font-weight: bold;
//   height: 200px;
.green-txt{
    color: rgb(46, 123, 115);;
}
  .conditions-left,
  .conditions-right {
    flex: 1;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
      background: #f5f7fa;
  }



  .condition-list,
  .condition-content {
    padding: 10px;
  }

  .condition-item {
    span {
      display: inline-block;
      padding: 8px 8px;
      margin: 5px;
      background: white;
      color: #409EFF;
      border-radius: 4px;
      cursor: pointer;  // 添加指针样式
      transition: all 0.3s;  // 添加过渡效果
       &.active {  // 选中状态
        background:  #67C23A;;
        color: white;
        }
    }
  }

  .content-item {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #EBEEF5;
    border-radius: 4px;

    .item-title {
      display: flex;
      gap: 10px;
      align-items: center;
      
      span {
        &:first-child {
          color: #666;
        }
        &:nth-child(2) {
          color: #409EFF;
        }
        &:last-child {
          color: #666;
        }
      }
    }
  }
}
.dialog-title {
  display: flex;
  flex-direction: column;
  color:white ;
  padding: 10px;
   font-size: 14px;

 .marginTop-20{
    margin-top: 10px;
 }
      background: rgb(37, 80, 162);
      .el-dialog__header{
        padding: 0px;
         
      
      }
}
.condition-header1 {
  display: flex;
  justify-content: space-between; // 两端对齐
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #EBEEF5;

  .header-left {
    display: flex;
    align-items: center;
    
    span {
      font-weight: bold;
      margin-left: 10px;
     
    }
  }

  .header-right {
    display: flex;
    gap: 10px; // 按钮间距

    .el-button {
      padding: 7px 15px;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
}
.code-list{
    display: flex;
            font-weight: bold;
    .code-item{
        margin-right: 5px;
        margin-top: 5px;
          flex-shrink: 0; // 防止元素在Flex容器中收缩
         min-width: 100px; 
         max-width: 200px;
         overflow-x: auto;
         white-space: nowrap;

    }
}

  .condition-item1 {
    display: flex;
    span {
        margin-left: 5px;
      display: inline-block;
      padding: 8px 8px;
    
     
    background: rgb(213, 222, 255);;
          color:  rgba(37,80,162,1);
      border-radius: 4px;
      cursor: pointer;  // 添加指针样式
      transition: all 0.3s;  // 添加过渡效果
      height: 40px;
      
    }
  }
.condition-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .delete-icon {
    color: #F56C6C;
    cursor: pointer;
    font-size: 16px;
    
    &:hover {
      opacity: 0.8;
    }
  }
}
.result-container{
  width: 100%;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background: #f5f7fa;
  margin-top: 10px;
}
  .condition-header {
    display: flex;
    // justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #EBEEF5;
  

    span {
      font-weight: bold;
      margin-left: 10px;
    }
  }
  .link-list{
    max-height: 350px;
    overflow-y: auto;
    padding: 10px;
    font-weight: bold;
   
    .link-item{
      display: flex;
      align-items: center;
      padding: 10px;
      background-color: white;
      border-radius: 10px;
      cursor: pointer; // 添加指针样式
      position: relative; // 添加相对定位
      margin-bottom: 10px;
        &.clicked {
          background-color: #e0e0e0; // 点击时的背景色
        }
       
       .el-icon-close {
                    position: absolute; // 绝对定位
                    top: 30%; // 垂直居中
                    right: 10px; // 距离右侧10px
                    transform: translateY(-50%); // 垂直方向上的偏移量，确保图标垂直居中
                    color: #F56C6C; // 删除图标的颜色
                    cursor: pointer; // 添加指针样式
                    font-size: 16px; // 图标大小

                    &:hover {
                      opacity: 0.8; // 悬停效果
                  }
          }
      .link-name{
        flex-shrink: 0;
        background-color: rgb(167, 224, 218);
        color: rgba(46, 123, 115, 1);
        border-radius: 5px;
        text-align: center;
    
        padding:8px;
        margin-right: 15px;

      }
      .code-list{
        margin-left: 15px;
        display: flex;

       
        overflow-x: auto;
           font-weight: bold;
          .code-item {
              // display: flex;
              margin-bottom: 10px;
              flex-shrink: 0;
                  margin-left: 5px;
       
                padding:8px;
              
              
              background: rgb(213, 222, 255);;
                color: #409EFF;
                border-radius: 4px;
           
                transition: all 0.3s;  // 添加过渡效果
                height: 50px;
                
              .code-title{
                color: black;
                margin-bottom: 10px;
              }
              .code-detail{
                color:  rgba(37,80,162,1);
              }
            }
      }
    }
  }
</style>
<style lang="scss">
.dialog-set {


      .el-dialog__header{
        padding: 0px;
              background: rgb(37, 80, 162);
              font-family: 16px;
      
      }
      .dialog-footer{
        text-align: center;
      }
}
</style>