<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-connection" ></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="saveEle"
                >
                <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].group" 
                :key="index"
              
                >
          <div>
            <span>
                <div class="condition-header-content">
                <div style="color: black;">
                    {{item.privateName}}
                </div>
                <i class="el-icon-close" @click.stop="handleDeleteItem(item,index)"></i>
                </div>
                <div class="code-list">
                <div class="code-item">
                     {{ item.elementNames}}
                </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.group" :key="codeIndex" class="code-item">
                        <div class="code-title">{{ codeItem.privateName }}</div>
                        <div class="code-detail">{{ codeItem.elementNames }}</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>

    <div style="height: 100%;">
       <el-drawer
        class="dialog-set"
            :visible.sync="addDialogVisible"
          width="80%"
          height="80%"

          append-to-body
            direction="ttb"

            >
            <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>
            <div class="condition-header1-title">
              <span>选择表单</span>
            </div>
            <div class="condition-header1-table">
                  <el-table
                    :data="tableData"
                    height="250"
                    border
                    style="width: 100%">
                    <el-table-column
                      prop="tableName"
                      label="表单名称"
                    >
                    </el-table-column>
                    <el-table-column
                      align="center"
                      prop="tableType"
                      :formatter="formatTableType"
                      width="100"
                      label="表单类型"
                    ></el-table-column>
                  <el-table-column
                      width="150"
                      label="操作"
                    >
                      <template slot-scope="scope">
                        <el-button
                          v-if="!scope.row.isSelected"
                          type="text"
                          size="small"
                          @click="handleRowSelect(scope.row)"
                        >
                          选择
                        </el-button>
                        <el-button
                          v-else
                          type="text"
                          size="small"
                          style="color: #F56C6C;"
                          @click="handleCancelSelect(scope.row)"
                        >
                          取消选择
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
            </div>
            <div class="condition-header1-title" style="margin-top: 10px;">
              <span>选择元素</span>
            </div>

            <div class="condition-header1-html-box">
              <check-ele-html 
              :key="pkeyId"
                :pkeyId="pkeyId"
                @element-selected="handleElementSelected"
              ></check-ele-html>
            </div>
            <div class="dialog-footer">
              
          
                <el-button type="primary" @click="confirmAdd" :style="{ background: 'rgb(37, 80, 162)', borderColor: 'rgb(37, 80, 162)' }">确认添加</el-button>
            </div>
        </el-drawer> 
    </div>
  </el-dialog>
      
       
</template>

<script>
import { getDictionary } from "@/api/system/dict";
import { findNodeTableByCondition as selectByNodeTable} from "@/api/manager/wbsprivate";
import checkEleHtml from "./checkEleHtml.vue";
import {saveElementJoin,deleteElementJoin,getElementJoin } from "@/api/ruleManage/fileRule.js";
export default {
  name: 'ConditionsSet',
  components: {
    checkEleHtml
  },
  data() {
    return {
      visible: false,
      treeId: '', // 树节点pid
      treePid: '', // 树节点父id
      deatailId: '', // 详情ID
      jId: '', // 技术指标ID


      paramList: [
        {
          symbolName: '',
          group:[
  
          ]

        }
       ] , // 参数列表数据
       activeIndex: 0, // 当前选中的参数索引

       addDialogVisible: false,
      tableData: [
        
      ],
      tableTypelist: [],
      pkeyId: '', // 主键ID
      id:'',
      projectid:'',
      checkTableRow: {}, // 当前选中的表单行数据
      checkEleList: [], // 存储选中的元素
      linkListData: [
       
      
           
      ], // 关联关系数据

    
   

    }
  },
  methods: {
    show(val,treeId,id,projectid,deatailId,tid,Jid) {

      this.jId = Jid;
      this.getTableTypelist();
      this.visible = true
      if(val.length > 0&&val[0].name) {
        this.treeId = treeId
        this.id = id
        this.deatailId = deatailId
        this.projectid = projectid
        this.paramList=val
        this.treePid=tid
        val.forEach((item,index)=>{
          this.handleSelect(index)
       })
       this.activeIndex = 0
      }else{
        this.paramList = []
          this.treeId = ''
      }
      
      this.getLinkSetData(this.deatailId,this.jId);
    },
     async getLinkSetData(id, groupId) {
        try {
          const res = await getElementJoin({ 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; // 重新抛出错误，以便在调用处捕获
        }
      },
    async handleSelect(index) {
      this.activeIndex = index
      let leftId = this.paramList[index].id
     let arr= await this.getRelationData(this.deatailId,this.Jid,leftId)
     
      if(arr.length>0){
          this.$nextTick(()=>{
              // this.paramList[index].group = arr[0]['group']
              this.$set(this.paramList, index, { ...this.paramList[index], group: arr[0]['group'] });
          })

      }else{
        this.paramList[index].group = []
      }
      
    },
   async getRelationData(id, groupId,leftId){
          try {
          const res = await getElementJoin({ 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; // 重新抛出错误，以便在调用处捕获
        }
    },
     getTableTypelist() {
      getDictionary({
        code:'trial_table_type',
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.tableTypelist = res.data.data;
      });
    },
    async getTableData(){
        const { data: res } = await selectByNodeTable( this.treePid,this.projectid, this.id);
          if (res.code === 200) {
            console.log(Array.isArray(res.data));
            if (Array.isArray(res.data)) {
              this.tableData = res.data
            
            } else {
              this.tableData = []
              this.$message.error('获取表单数据失败，请先关联清表');
            }
          }
    },
    hide() {
      this.visible = false  
    },
  
    handleConfirm() {
      
      saveElementJoin(this.linkListData,this.deatailId).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')
    },
    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;
        
    },
    handleDeleteLinkItem(item,index){
        this.$confirm('删除后，数据将无法恢复，是否确认删除!', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
  
            deleteElementJoin({leftId:item.id}).then((res) => {
              if(res.data.code==200){
                this.$message.success(res.data.msg);
              
                this.linkListData.splice(index, 1);
                this.getLinkSetData(this.deatailId);
              }else{
                this.$message.error(res.data.msg);
              }
            });
          }).catch(() => {
            this.$message.info('已取消删除');
          })
    },
    addCondition() {
      // 添加条件逻辑
           this.addDialogVisible = true
           this.pkeyId = ''

      this.getTableData();
    },
   handleSelect1(index) {
      this.activeIndex = index
    },

 
    handleDeleteItem(item, index) {
      this.paramList[this.activeIndex].group.splice(index, 1)
       this.$forceUpdate();
    },
    confirmAdd() {
      if (this.checkEleList.length === 0) {
        this.$message.error('请先选择元素');
        return;
      }
      if (this.checkTableRow.pkeyId === undefined || this.checkTableRow.pkeyId === '') {
        this.$message.error('请先选择表单');
        return;
      }
      const selectedCodes = this.checkEleList.map(ele => ({
        colName: ele.keyName,
        colKey: ele.elementId 
      }));
      console.log(selectedCodes,'selectedCodes');
      console.log(this.paramList,'this.paramList');
      let objArr={}
       const elementNames = selectedCodes.map(code => code.colName).join(' ');
        objArr={
          
          privateName: this.checkTableRow.tableName,
          privateId: this.checkTableRow.pkeyId,
          elementNames: elementNames,
          keys: selectedCodes,
        
        }
  
        
        this.paramList[this.activeIndex].group.push(objArr);
    
  
         

      this.addDialogVisible = false;
      this.$message.success('添加成功');
    },
    handleElementSelected(val) {
      console.log(val, '选中的元素');
      this.checkEleList = val;
      
    },
    //保存条件
    saveEle(){
      console.log(this.paramList,'保存条件');
      
        const filteredArr = this.paramList.filter(item => item.group.length !== 0);
        this.linkListData = JSON.parse(JSON.stringify(filteredArr));

    },
    formatTableType(row, column, cellValue) {
      for (let i = 0; i < this.tableTypelist.length; i++) {
        if (this.tableTypelist[i].dictKey == cellValue) {
          return this.tableTypelist[i].dictValue;
        }
      }
      return cellValue;
    
    },
    handleRowSelect(row) {
      // 设置选中状态
     // 先取消其他行的选中状态
      this.tableData.forEach(item => {
        if(item !== row) {
          this.$set(item, 'isSelected', false)
        }
      })
      this.pkeyId = row.pkeyId; // 更新主键ID
      this.checkTableRow = row; // 更新当前选中的表单行数据

      // 设置当前行选中状态
      this.$set(row, 'isSelected', true)

    },

    handleCancelSelect(row) {
       this.checkTableRow = {}; // 清除当前选中的表单行数据
      this.pkeyId = ''; // 清除主键ID
      // 取消选中状态
      this.$set(row, 'isSelected', false)

    }
  }
}
</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-drawer__header{
        padding: 0px;
              background: rgb(37, 80, 162);
              font-family: 16px;
      
      }
        // ...现有样式...
  .el-drawer {
    height: 95% !important; // 增加抽屉高度

    .el-drawer__body {
      height: calc(100% - 100px); // 减去头部和底部的高度
      overflow-y: auto; // 添加滚动
      padding: 20px;
    }

    
    .dialog-footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 10px 20px;
      text-align: center;
      background: white;
      border-top: 1px solid #EBEEF5;
    }
  }
      
      
}

</style>