<!--  -->
<template>

  <basic-container ref="heights">
    <el-row
        :gutter="20"
        :style="{height:heights-150+'px',}"
      >
        <el-col :span="16">
          <div
            class='parent hc-excel-table-form'
            id='parent'
            @click="parentClick($event)"

          >
          </div>

        </el-col>
        <el-col
        style="position: fixed;right: 13px;"
        :span="7"

        >
        <div style="margin-bottom: 20px;text-align: right;">
          <el-button @click="goBack">返回上一级</el-button>
          <el-button type="primary" @click="saveInfo" :loading="saveLoaing">保存</el-button>

        </div>
        <div class="right_box">
          <div>
            <span>选择表单</span>
            <el-select v-model="formVal" placeholder="请选择" style="width: 65%;margin-left: 10px;" @change="changeform">
              <el-option
                v-for="item in formoptions"
                :key="item.initTabId"
                :label="item.tabName"
                :value="item.initTabId">
              </el-option>
            </el-select>
          </div>
          <div>
            <span>选择元素</span>
            <el-select v-model="eleVal" placeholder="请选择" style="width: 65%;margin-left: 10px;margin-top: 15px;" @change="changeEle" filterable>
              <el-option
                v-for="item in eleOptions"
                :key="item.ekey"
                :label="item.eName"
                :value="item.ekey">
              </el-option>
            </el-select>
          </div>

            <div class="martop20 replace_box">
              <div style="width: 100%;height: 100%;overflow-y: auto;">
                  <el-row class="mb-4 ">
                    <div class="form_text">
                      <div>表单名称：{{ infoDetail.tabName }}</div>
                      <div>元素字段：{{  infoDetail.elementName }}</div>
                    </div>
                </el-row>
              </div>
            </div>
        </div>


        </el-col>
      </el-row>
  </basic-container>



</template>

<script >
import {getLinkHtml,getLinkTablist,getLinkElelist,getLinkDetail,saveLinkDetail,getLinkData} from "@/api/tentative/testcollect";
import Vue from "vue";
export default{


  data(){
    return{
      formoptions: [ ],
      eleOptions:[],
      heights: '',
      formVal:'',
      formpid:'',
      formname:'',
      classId:'',
      eleVal:'',
      eleId:'',
      clickKeyname:'',
      infoDetail:{
        elementName:'',
        tabName:'',
        id:''
      },
      saveLoaing:false,
      clickArr:[],//需要绑定的数组
      curItem:{
        elementId:'',
        elementKey:'',
        htmlKeyName:'',
        trialTabId:'',
        trialTabName:''
      },
      linkedData:[],//已经绑定的数组

    }
  },
  watch:{
    curItem:{
      handler(newVal, oldVal) {
        if(this.curItem.elementId&&this.curItem.elementKey&&this.curItem.htmlKeyName&&this.curItem.trialTabId&&this.curItem.trialTabName){
          const newItem = Object.assign({}, newVal);
          const isContained = this.containsObject(this.clickArr, "htmlKeyName", newItem.htmlKeyName);
          if(isContained){
            this.clickArr.forEach((ele)=>{
              if(ele.htmlKeyName===newItem.htmlKeyName){
                ele.elementId=newItem.elementId
                ele.elementKey=newItem.elementKey
                ele.htmlKeyName=newItem.htmlKeyName
                ele.trialTabId=newItem.trialTabId
                ele.trialTabName=newItem.trialTabName

              }
            })
          }else{
            this.clickArr.push(newItem);
          }


        }
        // 在这里执行你想要的操作
      },
      deep: true, // 指定为深度监听,

    },

  },
  methods:{
       // 判断数组中是否包含目标对象的函数
    containsObject(array, keyName, targetValue) {
        for (let i = 0; i < array.length; i++) {
            if (array[i][keyName] === targetValue) {
                return true;
            }
        }
        return false;
    },
    async getExcelHtmlCol(classId,form) {


      //获取excel模板
      const { data: res } = await getLinkHtml({ classId });
      console.log(res);
      if (res.code == 200) {
        // let _that = this
        var MyComponent = await Vue.extend({
          data() {
            return {
              formData: form,
            };
          },
            //监听数据，伪双向绑定（v-model）
            watch: {
                formData: {
                    handler(obj) {
                        this.formData=obj
                    },
                    deep: true,
                    immediate:true
                },
            },
          template: res.data,
          methods: {
             //改变表单数据
            //  setFormData(obj) {
            //         this.formData = obj
            //         _that.setFormData2(obj)
            //         console.log(this.formData,'this.formData1111111');
            //  },
            contextmenuClick() {},
            getInformation () {},
            formUploadSuccess(){},
            formUploadExceed(){},
            formUploadLoading(){},
            delTableFormFile(){},
            formUploadError(){},
            uploadprogress(){},
            formRemoteMethod(){},
            getRegularExpression(){},
            checkboxGroupChange(){},
            formRemoteChange(){},
            dateKeydown(){},
            keyupShiftUp() {},
            keyupShiftDown() {},
            keyupShiftLeft() {},
            keyupShiftRight() {},
            inputLeftClick() {},
          }
        });
        var component = new MyComponent().$mount();
        let na = document.getElementById("parent");
        na.innerHTML = `<div
        class='parent'
        id='parent'"
      ></div>`;
        document.getElementById("parent").appendChild(component.$el);
      }
    },
        //excel父节点点击检测
    async parentClick(e) {
      let target = e.target;
      let bgs = document.querySelectorAll("#parent .oldlace-bg");
      //console.log(bgs)

      let tdEle = this.getParentTD(target);
      let target1
        if(tdEle){
          let mydiv=tdEle.getElementsByTagName('div')
          target1=mydiv[0]
        }else{
          tdEle=target
          let mydiv=tdEle.getElementsByTagName('div')
          target=mydiv[0]

        }
      for (let i = 0; i < bgs.length; i++) {
        bgs[i].classList.remove("oldlace-bg");
      }
      if (
        target.getAttribute("trindex") !== null &&
        target.getAttribute("tdindex")
      ) {
        target=target
      }else{
        target=target1
      }
      //console.log(target.getAttribute('trindex'))
      if (
        target.getAttribute("trindex") !== null &&
        target.getAttribute("tdindex")
      )
      {
        let tdEle = this.getParentTD(target);
        if (tdEle) {
          target.classList.add("oldlace-bg");

          let trtd =
            target.getAttribute("trindex") +
            "_" +
            target.getAttribute("tdindex");



          this.$nextTick(() => {
            let row = document.querySelectorAll(".warning-row");
            if (row.length) {
              this.$refs.tablescroll.$el.scrollTop = row[0].offsetTop;
            }

          });
        }
        this.clickKeyname=target.getAttribute('keyname')||target1.getAttribute('keyname')
        await  this.getInfoDEtail()
        this.$set(this.curItem,'htmlKeyName',this.clickKeyname)


      }
    },
    getParentTD(ele) {
      let targetParent = ele.parentNode;
      while (targetParent.nodeName !== "TD") {
        if (targetParent.id == "parent") {
          return null;
        }
        targetParent = targetParent.parentNode;
      }
      return targetParent;
    },
    setFormData2(obj){
      console.log(obj,'obj');
    },
    goBack(){
      this.$router.go(-1)
    },
    //获取表单类别
    async getFormoptions(){
      const { data: res } = await getLinkTablist({
                classId:this.classId,
          });

          if (res.code === 200) {
           this.formoptions=res.data

          } else {
          this.formoptions=[]
        }
    },
    //获取当前清表表所有已匹配的映射字段列表
   async getLinkedData(){
      const { data: res } = await getLinkData({
                id:this.classId,
          });
          if (res.code === 200) {

           this.linkedData=res.data
           const mappedObject = Object.fromEntries(res.data.map(item => [item.htmlKeyName, item.elementValue]));
          this.linkedData=mappedObject
          } else {
          this.linkedData=[]
        }
    },
    //选择表单获
    changeform(val){
      this.getEleList(val)
      this.formoptions.forEach((ele)=>{

        if(ele.initTabId===val){
          this.formpid=ele.pkeyId
          this.formname=ele.initTableName
          this.infoDetail.tabName=ele.tabName
          this.$set(this.curItem,'trialTabId',ele.pkeyId)
          this.$set(this.curItem,'trialTabName',ele.initTableName)

        }
      })
    },
    changeEle(val){
      this.eleOptions.forEach((ele)=>{
        if(ele.ekey===val){
          this.eleId=ele.id
          this.infoDetail.elementName=ele.eName
          this.$set(this.curItem,'elementKey',val)
          this.$set(this.curItem,'elementId',ele.id)
        }
      })
    },
    //获取元素列表
   async getEleList(val){
      const { data: res } = await getLinkElelist({
                id:val,
          });
          console.log(res);
          if (res.code === 200) {
           this.eleOptions=res.data

          } else {
          this.eleOptions=[]
        }
    },
   //获取数据映射源
   async getInfoDEtail(){
      const { data: res } = await getLinkDetail({
            classId:this.classId,
            keyName:this.clickKeyname
          });
          if (res.code === 200) {
              this.infoDetail=res.data

              if(this.infoDetail&&this.infoDetail.id){
                this.formoptions.forEach((ele)=>{
                  if(ele.tabName===this.infoDetail.tabName){
                    this.formVal=ele.initTabId
                    this.$set( this.curItem,'trialTabName',ele.initTableName)
                    this.$set( this.curItem,'trialTabId',ele.pkeyId)
                  }
                  })
                await this.getEleList(this.formVal)
                  this.eleOptions.forEach((ele)=>{
                  if(ele.eName===this.infoDetail.elementName){
                    this.eleVal=ele.ekey
                    // this.curItem.elementId=ele.id
                    // this.curItem.elementKey=ele.ekey
                    this.$set( this.curItem,'elementId',ele.id)
                    this.$set( this.curItem,'elementKey',ele.ekey)
                  }
                  })



              }else{
                this.infoDetail={}
                this.formVal=''
                this.eleVal=''
                this.curItem={}
                // this.curItem.htmlKeyName=this.clickKeyname
                this.$set( this.curItem,'htmlKeyName',this.clickKeyname)
              }

           } else {
                this.infoDetail={}
           }


    },

    //映射数据保存
   async saveInfo(){
    console.log(this.clickArr,'this.clickArr');
    if(this.clickArr.length===0){
      this.$message.warning('请进行数据映射配置')
      return
    }

    this.saveLoaing=true
        const { data: res } = await saveLinkDetail({
                    classId:this.classId,
                    reflectionBeanList:this.clickArr
        });
        console.log(res);
        this.saveLoaing=false
        if (res.code === 200) {
          this.$message({
            type: "success",
            message:res.msg,
          });
          await this.getLinkedData()
          await this.getExcelHtmlCol(this.classId,this.linkedData); //获取excel模板
          this.clickArr=[]

        }
    }
  },
 async created(){
      this.classId = this.$route.query.classId;
      await this.getLinkedData()
     await this.getExcelHtmlCol(this.classId,this.linkedData); //获取excel模板
      this.getFormoptions()

  },
  mounted(){
    this.heights = this.$refs.heights.clientHeight

  },

}
</script>
<style lang="scss" scoped>


.parent{
  /deep/ .select-td{
    border-width: 4px;
    border-color: #E6A23C;
    border-style: solid;
  }

  /deep/ .oldlace-bg{
    background-color: oldlace;
  }
}

.right_box{

  height: calc(100vh - 235px);

  padding-left: 20px;
  padding-top: 20px;
  text-align: left;
}

.replace_box{
  margin-top: 80px;
  border-top: 1px gray dashed;
  width: 95%;

  position: relative;
  padding-top: 20px;
  padding-left: 15px;



}
.replace_box::after {
				content: '映射数据来源';
				position: absolute;
				right: 34%;
				top: -15px;
        background-color: white;
				text-align: center;
				font-size: 18px;
				color: orange;
        font-weight: 900;
		}
    .form_text{
      width: 100%;
      text-align: left;
      line-height: 30px;
    }

</style>
