<template>
  <div class="layout-container">
    <div class="panel" ref="panel1">
      <div class="parent hc-excel-table-form" id="parent" @click="parentClick($event)"></div>
    </div>
    <div class="splitter"></div>
    <div class="panel" ref="panel2">
      <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>
      <template v-if="listArr.length > 0">
        <div class="right_box" v-for="(eleItem, index) in listArr" :key="index">

          <div>
            <span>选择表单</span>
            <el-select v-model="eleItem.initTabId" placeholder="请选择" style="width: 65%; margin-left: 10px"
              @change="changeform($event, index)">
              <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="eleItem.elementId" placeholder="请选择"
              style="width: 65%; margin-left: 10px; margin-top: 15px" @change="changeEle($event, index)" filterable>
              <el-option v-for="item in eleOptions" :key="item.id" :label="item.eName" :value="item.id">
              </el-option>
            </el-select>
          </div>

          <div class="martop10 replace_box">
            <div style="width: 100%; height: 100%; overflow-y: auto">
              <el-row class="mb-4">
                <div class="form_text">
                  <div>表单名称：{{ eleItem.tabName }}</div>
                  <div>元素字段：{{ eleItem.elementName }}</div>
                </div>
              </el-row>
              <div class="martop20">
                <el-button type="primary" size="small" @click="addList(index)">新增元素</el-button>
                <el-button type="danger" size="small" v-if="index > 0" @click="delList(index, eleItem)">删除元素</el-button>
              </div>

            </div>
          </div>

        </div>
      </template>
      <el-empty description="暂无数据" v-else></el-empty>


    </div>
  </div>
</template>
<script>
import {
  getLinkHtml,
  getLinkTablist,
  getLinkElelist,
  getLinkDetail,
  removeLinkData,
  getLinkData,
  saveLinkDetail
} from "@/api/tentative/testcollect";
import Vue from "vue";
import Split from "split.js";
export default {
  data() {
    return {
      formoptions: [],
      eleOptions: [],
      heights: "",
      initTabId: "",
      formpid: "",
      formname: "",
      classId: "",
      elementId: "",
      eleId: "",
      clickKeyname: "",
      infoDetail: {
        elementName: "",
        tabName: "",
        id: "",
      },
      saveLoaing: false,
      clickArr: [], //需要绑定的数组
      curItem: {
        elementId: "",
        elementKey: "",
        htmlKeyName: "",
        trialTabId: "",
        trialTabName: "",
      },
      linkedData: [], //已经绑定的数组
      listArr: [
        {}
      ],
    };
  },
  watch: {

  },
  methods: {

    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: {

            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");
      target.classList.add("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");
        this.$set(this.curItem, "htmlKeyName", this.clickKeyname);
        this.listArr.forEach((ele) => {
          ele.htmlKeyName = this.clickKeyname

        })
        await this.getInfoDEtail();


      }
    },
    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, index) {
      this.getEleList(val);
      this.formoptions.forEach((ele) => {
        if (ele.initTabId === val) {
          // this.listArr[index].trialTabId= ele.pkeyId
          // this.listArr[index].trialTabName= ele.initTableName
          // this.listArr[index].tabName= ele.tabName
          this.$set(this.listArr[index], "trialTabId", ele.pkeyId)
          this.$set(this.listArr[index], "trialTabName", ele.initTableName)
          this.$set(this.listArr[index], "tabName", ele.tabName)
          this.$set(this.listArr[index], "elementId", null)
        }
      });
    },
    changeEle(val, index) {
      this.eleOptions.forEach((ele) => {
        if (ele.id === val) {
          // console.log(ele, "ele");
          // this.listArr[index].elementName = ele.eName
          this.$set(this.listArr[index], "elementName", ele.eName)
          this.$set(this.listArr[index], "elementId", ele.id)
        }
      });
    },
    //获取元素列表
    async getEleList(val) {
      const { data: res } = await getLinkElelist({
        id: val,
      });

      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.listArr = res.data.length > 0 ? res.data : [{}]
        this.listArr.forEach((ele) => {
          ele.htmlKeyName = this.clickKeyname

        })
        this.formoptions.forEach((ele) => {
          this.listArr.forEach(async (eleItem, eleIndex) => {
            if (ele.pkeyId === eleItem.trialTabId) {
              eleItem.initTabId = ele.initTabId
              await this.getEleList(ele.initTabId)
              this.changeEle(eleItem.elementId, eleIndex)


            }

          })
        })





      } else {
        this.listArr = [{}]

      }
    },

    //映射数据保存
    async saveInfo() {


      if (this.listArr.length === 0) {
        this.$message.warning("请进行数据映射配置");
        return;
      }
      const isValid = this.listArr.every(item =>
        item.elementId && item.initTabId
      );

      if (!isValid) {
        this.$message.warning("请确保选择了所有表单和元素字段！");
        return;
      }
      this.saveLoaing = true;
      const { data: res } = await saveLinkDetail({
        classId: this.classId,
        reflectionBeanList: this.listArr,
      });

      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 = [];
        this.curItem = {}
      }
    },
    addList(index) {
      const currentItem = this.listArr[index];
      if (!currentItem.elementId || !currentItem.initTabId) {
        this.$message({
          type: "warning",
          message: "请选择元素和表单",
        });
        return; // 不满足条件则不添加
      }
      this.listArr.splice(index + 1, 0, {
        htmlKeyName: this.clickKeyname
        ,

        tabName: '',
        elementName: ''
      });
    },
    delList(index, item) {
      if (!item.id) {
        this.listArr.splice(index, 1);
        return;
      } else {
        this.$confirm('删除后，数据将无法恢复，是否确认删除!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 接口调用时添加 catch 处理接口错误
          removeLinkData({ id: item.id })
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success(res.data.msg);
                this.listArr.splice(index, 1);
                this.getLinkedData();
                this.getExcelHtmlCol(this.classId, this.linkedData);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              // 处理接口调用失败（如网络错误、500错误等）
              this.$message.error('删除接口调用失败，请重试');
              console.error('删除失败：', err); // 方便调试
            });
        }).catch(() => {
          // 这里仅处理用户点击“取消”的情况
          this.$message.info('已取消删除');
        });
      }
    }
  },
  async created() {
    this.classId = this.$route.query.classId;
    await this.getLinkedData();
    await this.getExcelHtmlCol(this.classId, this.linkedData); //获取excel模板
    this.getFormoptions();
  },
  mounted() {
    Split([this.$refs.panel1, this.$refs.panel2], {
      direction: "horizontal", // 设置分割方向，'horizontal' 或 'vertical'
      gutterSize: 10, // 设置分割条的大小
      sizes: [75, 25], // 初始化各个面板的宽度比例
      minSize: 100, // 设置面板的最小尺寸
      onDragEnd: () => {
        // 拖动结束后的回调，可以执行一些额外的操作
        console.log("Panel sizes adjusted");
      },
    });
  },
};
</script>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  width: 100%;
}

.panel {
  background: white;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
}

.panel:nth-child(odd) {
  background: white;
}

.gutter {
  background-color: #eee;
  background-repeat: no-repeat;
  background-position: 50%;
}

#parent ::v-deep .oldlace-bg {
  background-color: oldlace;
}
</style>
<style>
.gutter-horizontal {
  background-image: url('/img/split.png') !important;
  cursor: col-resize;
  background-repeat: no-repeat;
  background-position: center;
}

.right_box {
  margin-bottom: 15px;
}
</style>
