<template>
  <div>
   
    <!-- 弹窗 -->
    <el-dialog title="参数信息" :visible.sync="dialogVisible" width="60%" append-to-body @close="closeParamDialog">
      <div>
        <div class="sub-title">{{ params.paramName }}</div>
        <!-- 搜索栏 -->
        <div class="search-container">
            <div>
              <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="small" >
                  <el-form-item label="" prop="projectName">
                      <el-select v-model="searchForm.projectName" placeholder="项目名称" @change="changeProject" clearable >
                          <el-option
                          v-for="item in projectList"
                          :key="item.id"
                          :label="item.projectName"
                          :value="item.projectId">
                          </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="contractSection">
                      <el-select v-model="searchForm.contractId" placeholder="合同段" clearable >
                          <el-option
                          v-for="item in contractList"
                          :key="item.id"
                          :label="item.contractName"
                          :value="item.id">
                          </el-option>
                      </el-select>
                     </el-form-item>
                     <el-form-item>
                        <el-input v-model="searchForm.elementName"  placeholder="元素名称" clearable></el-input>
                      </el-form-item>
                      <el-form-item>
                          <el-button type="primary" @click="searchElement">搜索</el-button>
                      </el-form-item>
              </el-form>
          </div>

          <!-- 新增按钮 -->
          <div>
            <el-button type="success" @click="handleAdd" size="small" >新增元素</el-button>
            <el-button type="primary" @click="handleEditParam" size="small" >编辑参数</el-button>
            <el-button type="danger" @click="handleDelteParam" size="small" >删除参数</el-button>
          </div>
          
        </div>

        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%;" border v-loading="tableLoading"  max-height="350">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="elementName" label="元素名称"></el-table-column>
          <el-table-column prop="type" label="是否全局参数">
            <template slot-scope="scope">
                {{ scope.row.type===1?'是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="projectName" label="项目名称"></el-table-column>
          <el-table-column prop="contractName" label="合同段"></el-table-column>
          <el-table-column prop="name" label="创始人"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-link size="mini" @click="handleEdit(scope.$index, scope.row)"  type="primary" >编辑</el-link>
              <el-link size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"  class="mg-l-10">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog :title="form.id?'元素编辑':'元素新增'" :visible.sync="addDialogVisible" width="40%" append-to-body @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-position="left">
        <el-form-item label="元素名称" label-width="120px">
          <el-input v-model="form.elementName" :disabled="form.selectedElement.length>0"></el-input>
        </el-form-item>
        <el-form-item label="选择元素" label-width="120px" v-if="!isEdit">
            <el-button style="width: 100%;" @click="checkEle" v-if="form.selectedElement.length===0" :disabled="form.elementName.length>0">点击选择元素</el-button>
            <div class="bottom-box" v-else @click="checkEle">
              <el-tag type="info"  closable v-for="item in form.selectedElement" :key="id" class="mr-5"   @close="handleClose(tag)">{{ item.eName }}</el-tag>
            </div>
        </el-form-item>
        <el-form-item label="是否全局参数" label-width="120px" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
       
        <div class="form-container1" v-if="form.type===2" >
            <el-button  type="warning" class="add-button" size="small" @click="addProData"  v-if="form.type===2&&!form.id">新增</el-button>
            <div v-if="form.type===2" class="form-container" v-for="(item,index) in proData" :key="index"  :style="{ marginTop: index === 0 ? '40px' : '0' }"> 
                <!-- 删除图标 -->
              <el-button type="danger" size="mini" v-if="index !== 0"
                icon="el-icon-delete" 
                circle 
                class="delete-icon" 
                @click="removeProData(index)">
              </el-button>
                    <el-form-item label="选择项目" prop="contractSection"  label-width="120px">
                            <el-select v-model="item.projectName" placeholder="请选择项目" @change="changeProject" clearable  style="width: 100%;">
                                <el-option
                                v-for="item1 in projectList1"
                                :key="item1.id"
                                :label="item1.projectName"
                                :value="item1.id">
                                </el-option>
                            </el-select>
              </el-form-item>
              <el-form-item label="选择合同段" prop="contractSection"   label-width="120px"  >
                            <el-select v-model="item.contractSection" placeholder="请选择合同段" clearable  multiple  class="multiple-select">
                                <el-option
                                v-for="item2 in contractList"
                                :key="item2.id"
                                :label="item2.contractName"
                                :value="item2.id">
                                </el-option>
                            </el-select>
              </el-form-item>
            
            </div>
        </div>
  
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 选择元素弹窗 -->
     <checkEleDialog ref="checkEleDialogRef" @confirmCheck="confirmCheck"></checkEleDialog>
     <!-- 编辑参数弹窗 -->
      <addParamDialog :visible.sync="editDialogVisible"   :params="params" @add-parameter="addCardFinish" ref="addParamDialogRef"/>
  </div>
</template>

<script>
import checkEleDialog from './checkEleDialog.vue';
import { getProjectList } from "@/api/manager/projectinfo";
import { findContractByProjectId } from "@/api/manager/contractinfo";
import addParamDialog from './addParamDialog.vue';
import { remove,getProjectContractByParam,submitElement,getParameterElementList,removeElement} from "../../../api/paramter/parmter.js";
export default {
    components:{
        checkEleDialog,
        addParamDialog
    },
    props:{
            params:Object
    },
    watch: {
      params: {
        handler: function(n) {
          this.params=n
        
        },
        deep: true,
      },
   },
  data() {
    return {
      dialogVisible: false,
      projectList: [],
      projectList1:[],
      contractList: [
      ],
      searchForm: {
        projectName: '',
        contractId: '',
        elementName: '',
      },
      tableData: [],
      tableLoading:false,
      addDialogVisible:false,
      isEdit:false,
      form: {
        elementName: '',
        selectedElement: [],
        type: false
      },
      proData:[{}],
      rules: {
      
        type: [
          { required: true, message: '请选择是否全局参数', trigger: 'change' }
        ]
      },
      editDialogVisible:false,
      paramId:''
    };
  },
  methods: {
    show(id) {
      this.paramId = id
      this.dialogVisible = true;
      this.getProjectListData(id)
      this.getTableData(id)
    },
    closeParamDialog(){
   
      this.$emit('finshDetail')
      this.dialogVisible = false;
      this.addDialogVisible=false;
   
    },
    onSearch() {
      // 实现搜索逻辑
      console.log('搜索条件:', this.searchForm);
    },
    handleAdd() {
      // 实现新增逻辑
      this.addDialogVisible=true;
 
      this.getProjectListData1()
      this.isEdit=false
      this.form={
        elementName: '',
        selectedElement: [],
        type: false
      }
      this.proData=[{}]
    },
    closeDialog(){
      this.addDialogVisible=false;
      
      this.isEdit=false
      this.contractList=[]
    },
    handleEditParam(item){
      // this.editDialogVisible=true
      this.$refs.addParamDialogRef.show( this.params)
   
      
   
    },
    addCardFinish(){
          console.log('编辑完成');
          this. closeParamDialog()
          
    },
    handleEdit(index, row) {;
      this.addDialogVisible=true;
      this.getProjectListData1()
      this.changeProject(row.projectId)
      this.isEdit=true
      console.log(row,'row');
      
      this.form=row
      let arr=[{
        projectName:row.projectId,
        contractSection:row.contractId?row.contractId.split(','):[]
      }]
      this.proData=arr
      this.form.selectedElement=[]
    },
    handleDelteParam(){
      this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove({
              id:this.params.id
            });
          })
          .then((res) => {
            this.$message({
              type: "success",
              message:res.data.msg
            });

            this.dialogVisible=false
            this.$emit('finshDetail');
          });
    },
    handleDelete(index, row) {
      // 实现删除逻辑
      console.log('删除:', index, row);
      this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeElement({
              id:row.id
            });
          })
          .then((res) => {
            this.$message({
              type: "success",
              message:res.data.msg
            });

 
            this.getTableData( this.paramId)
          });
    },
      //获取项目列表
    getProjectListData(id) {
      if(!id ){
        getProjectList(1, 999).then((res) => {
          this.projectList = res.data.data.records;
        });
      }else{
        getProjectContractByParam({
          parameterId: id
        }).then((res) => {
          this.projectList = res.data.data;
        });
      }
        
    },
    getProjectListData1() {
      getProjectList(1, 999).then((res) => {
          this.projectList1 = res.data.data.records;
        });
    },
    changeProject(val){
 
         //根据项目id获取合同段列表
         findContractByProjectId(val).then((res) => {
            this.contractList = res.data.data;
       
    
          });
    },
    searchElement(){
      this.getTableData()
    },
    //获取元素列表
    getTableData(id){
      this.tableLoading=true
      getParameterElementList({
        parameterId:  this.paramId,
        contractId:this.searchForm.contractId,
        projectId:this.searchForm.projectName,
        elementName:this.searchForm.elementName
      }).then((res)=>{
        this.tableLoading=false
        this.tableData = res.data.data||[];
        this.tableLoading=false
      })
    },
    confirmAdd(){
      console.log(this.form,'form');
      const {selectedElement}=this.form;
      if(!this.form.elementName&&selectedElement.length==0){
        this.$message.error('请选择元素或者完善元素名称');
        return;
      }
      let subArr=[]
      let projectList=[]
      let proData=this.proData
      console.log(proData,'proData');
      
      if(proData.length>0&&proData[0].projectName){
        proData.forEach(item=>{
          projectList.push({
            projectId:item.projectName,
            contractId:item.contractSection.join(','),
          })
        })
      }
      if(selectedElement.length>0){
        selectedElement.forEach(item=>{
          subArr.push({
             id:this.form.id,
             parameterId: this.params.id,
             type:this.form.type,
             elementName:item.eName,
             projectList:this.form.type===2?projectList:[]
          })
        })
      }else if(this.form.elementName){
        subArr.push({
             id:this.form.id,
             parameterId: this.params.id,
             type:this.form.type,
             elementName:this.form.elementName,
             projectList:this.form.type===2?projectList:[]
        })
      }
      console.log(subArr,'subArr');
      console.log(this.proData,'proData');
      if(this.form.type===2&&this.proData&&!this.proData[0]['projectName']){
        this.$message.warning('请先选择项目');
        return;
        
      }
      
      submitElement(subArr).then((res) => {
            if(res.data.code==200){
                this.$message.success(res.data.msg)
                this.addDialogVisible=false
              }else{
                this.$message.error(res.data.msg)
              }
              this.addDialogVisible=false
              this.getTableData()
            });
    },
    addProData(){
      this.proData.push({})
    },
    removeProData(index){
      this.proData.splice(index,1)
    },
    //选择元素
    checkEle(){
      this.$refs.checkEleDialogRef.show( this.form.selectedElement)
    },
    confirmCheck(selectedData){
    this.form.selectedElement=selectedData
      console.log('选择的元素1111111111:', selectedData);

    },
    handleClose(tag) {
      this.form.selectedElement.splice(this.form.selectedElement.indexOf(tag), 1);
      },
  }
};
</script>

<style scoped>
.form-container1{
  position: relative;
  max-height: 400px;
  overflow-y: auto;
 
}
.form-container {
  border: 1px solid #ccc; /* 淡灰色边框 */

 padding: 20px 40px 0px 20px;
 margin-bottom: 15px;
 position: relative; 
 
}
.delete-icon {
  position: absolute;
  top: 5px;
  right:5px;
  z-index: 1000;
}
.add-button {

  margin-left: 20px;
  position: absolute;
  top: 0px;
  right: 5px;
  z-index: 1000;
}


.multiple-select {
  width: 100%;
}


.search-container {
  display: flex;
  justify-content: space-between; /* 使子元素两端对齐 */
  align-items: center; /* 垂直居中对齐 */
}
.bottom-box{
  width: 100%;
  height: 20%;
  border: 1px solid #DBDBDB;
  margin-top: 10px;
  padding: 10px;
}
.mr-5{
  margin-right: 5px;
}
.sub-title{
  margin-bottom: 15px;
  font-weight: bold;
  font-size: 16px
}
</style>