<template>
  <div style="height:100%;" ref="heights">
    <basic-container class="editElement">
      <div class="flex" style="position:fixed;left:30px;top:0;">
        <h2 class="mg-r-10">编辑元素</h2>
      </div>
      <div class="header" style="padding-bottom:20px;">
        提示：鼠标右键功能：更换匹配元素字段、新增元素字段、删除匹配元素字段、公式配置&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 红色：代表匹配不成功、蓝色代表推荐匹配元素字段、绿色代表匹配成功
      </div>
      <el-row :gutter="20" :style="{ height: heights - 150 + 'px', }">
        <el-col :span="16" style="height: 100%;">
          <div class='parent hc-excel-table-form' style="position: relative;height: 100%;width: 100%;overflow: auto;"
            id='parent'>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="text-align: right;">
            <el-button @click="toBack">返回上一级</el-button>
            <el-button type="warning" @click="adjustExcel">进入表单调整</el-button>
          </div>
          <div>
            <div class="martop20" style="font-weight: bold;font-size: 18px;">
              <i class="el-icon-edit" style="color: #52B200;"></i>
              替换操作栏
            </div>
            <div class="martop20">
              <div style="font-weight: bold;">选中的元素</div>
              <div class="check_box">
                <span v-for="(item, index) in checkList" :key="index" style="margin-right: 4px;">{{ item.name }}</span>
              </div>
            </div>
            <div class="tihuan" style="font-weight: bold;">替换为：
              <span style="color: orange;">选择下方“未进行匹配的元素字段”可快速选择元素</span>

            </div>
            <el-select style="width:100%;" v-model="value" filterable placeholder="输入元素名称搜索">
              <el-option v-for="item in options" :key="item.id" :label="item.eName" :value="item.id">
              </el-option>
            </el-select>
            <div class="martop20 save-btn">
              <el-button type="primary" :disabled="tag" @click="saveReplace()">保存</el-button>
            </div>
            <div class="martop20" style="font-weight: bold;font-size: 18px;">
              <i class="el-icon-s-order" style="color: #E3B8E1;"></i>
              未匹配元素快速选择栏
            </div>
            <div class=" replace_box" v-if="true">
              <div style="width: 100%;height: 100%;overflow-y: auto;">
                <el-row class="mb-4 ">
                  <div style="width: 100%;">
                    <el-button type="warning" plain v-for="(item, index) in unMatchItems" @click="unMatchClick(item)"
                      :key="index" style="margin-bottom: 10px ;" size="small">{{ item.eName }}</el-button>
                  </div>
                </el-row>
              </div>
            </div>
            <div class="message-box ">
              <div>
                <i class="el-icon-warning"></i>操作提示
                <ul>
                  <li style="margin-bottom: 8px;">选中表单上的元素，选择替换的元素后，点击【保存】即可完成元素替换。</li>
                  <li style="margin-bottom: 8px;">点击“未匹配元素”可快速选择目标元素。</li>
                  <li>元素、电签、默认值配置完成后，请保存表单配置方案用于快速替换。</li>
                </ul>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-dialog append-to-body :show-close="false" width="360px" :modal='false' class="cascader-dialog" top="0"
        :visible.sync="cascaderPanel" :style="{ position: 'absolute', top: top + 'px', left: left + 'px' }">
        <el-cascader-panel :props="{ expandTrigger: 'hover' }" :options="options2" @change="takuangchangge"
          ref="cascader"></el-cascader-panel>
      </el-dialog>

      <el-dialog title="添加新元素字段" :visible="AddNewElementField == '新增元素'" width="60%" :before-close="handleClose"
        :close-on-click-modal="false" append-to-body>
        <div>
          <i @click="addyuansu" class="el-icon-circle-plus marbottom10"
            style="color:red; font-size:24px; float: right;cursor: pointer;"></i>
          <el-table :data="tableData" height="250" border style="width: 100%">
            <el-table-column prop="date" label="清表元素名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.eName" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="元素数据类型">
              <template slot-scope="scope">
                <el-select style="width:100%;" v-model="scope.row.eType" placeholder="请选择">
                  <el-option v-for="item in dataType" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="assist" label="是否公式辅助元素" width="140">
              <template slot-scope="scope">
                <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.assist"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column prop="date" align="center" width="120" label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="deleteziduan(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button type="primary" v-throttle='2000' :disabled="tableData.length === 0"
            @click="pushNewElementField()">确定
          </el-button>
        </span>
      </el-dialog>

      <!-- 公式 -->
      <el-dialog title="元素公式" :visible.sync="formulaCompVisible" fullscreen append-to-body class="full-dialog">
        <FormulaEdit :wbsid="wbsid" :nodeid="nodeid" :eleid="eleid" :projectid="pid"
          @hideDialog="formulaCompVisible = false" v-if="formulaCompVisible" :globaltype="globaltype"
          :fromcurNode="editElementQuery"></FormulaEdit>
      </el-dialog>
      <el-dialog title="" :visible.sync="formulaCompVisible1" fullscreen append-to-body class="full-dialog">
        <FormulaEditone :wbsid="wbsid" :nodeid="nodeid" :eleid="eleid" :elementType="elementType" :projectid="pid"
          :fromcurNode="curEleTable" :globaltype="globaltype" @hideDialog="formulaCompVisible1 = false"
          v-if="formulaCompVisible1">
        </FormulaEditone>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import FormulaEdit from '@/views/formula/edit.vue'
import FormulaEditone from '@/views/formula/edit1.vue'

import { getExcelHtml } from '@/api/exctab/excelmodel'
import { getElementInfoByTabId, submit, submit2, dictionarydataType, submitBatch, getUnMatchField } from '@/api/exctab/editelement'
import Vue from 'vue'



export default {
  components: {
    FormulaEdit,
    FormulaEditone
  },
  props: {
    pkeyId: {
      type: String,
      default: ''
    },
    excelId: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    initTableName: {
      type: String,
      default: ''
    },
    initTableId: {
      type: String,
      default: ''
    },
    pid: {
      type: String,
      default: ''
    },
    wbsid: {
      type: String,
      default: ''
    },
    nodeid: {
      type: String,
      default: ''
    },
    globaltype: {
      type: Number,
      default: 10
    },
    elementType: {
      type: Boolean,
      default: false
    },
    curEleTable: {
      type: Object,
      default: {}
    },
    editElementQuery: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      heights: '',
      dataType: [],//数据类型
      tag: false,
      table: {

      },//table表鼠标右键事件
      AddNewElementField: '',
      setTimeout: '',
      top: 0,
      left: 0,
      cascaderPanel: false,
      options: [],
      value: '',
      names: '',//替换元素得值
      tableData: [],//table表
      options2: [{
        value: '编辑元素字段',
        label: '编辑元素字段',
        children: [{
          value: '替换元素',
          label: '替换元素'
        }, {
          value: '新增元素',
          label: '新增元素'
        }, {
          value: '删除文本信息',
          label: '删除文本信息'
        }]
      }, {
        value: '公式配置',
        label: '公式配置',
      }],

      ekeyReg: /(key_\d+)/,

      isMultiple: false,
      eleData: [],

      formulaCompVisible: false,//公式弹框节点公式
      formulaCompVisible1: false,//公式弹框全局公式
      eleid: '',//当前元素
      unMatchItems: [

      ],
      checkList: []//需要替换的数组

    }
  },
  mounted() {
    // 捕获阶段监听，比 Element 内部更早,捕获阶段冒泡阶段都可以触发(select组件点击问题)
    const parent = document.getElementById('parent');
    if (parent) {
      parent.addEventListener('click', this.parentClick, true);   // true = 捕获
    }
    this.cop()
    this.heights = this.$refs.heights.clientHeight
  },
  created() {
    this.getElementInfoByTabId()
    this.getUnMatchFieldData()
    this.AddNewElementField = '替换元素'
  },
  beforeDestroy() {
    const parent = document.getElementById('parent');
    if (parent) {
      parent.removeEventListener('click', this.parentClick, true);
    }
  },
  methods: {
    //获取未匹配的元素字段
    getUnMatchFieldData() {
      getUnMatchField({
        pkeyId: this.pkeyId,
        tabId: this.initTableId
      }).then((res) => {
        console.log(res, 'res');
        this.unMatchItems = res.data.data
      })
    },
    //选择未匹配的字段
    unMatchClick(item) {
      console.log(item, 'item');
      this.value = item.id
      this.names = item.eName

    },
    takuangchangge(value) {//切换事件
      if (value[value.length - 1] == '替换元素') {
        this.AddNewElementField = '替换元素'
        this.cascaderPanel = false
        clearTimeout(this.setTimeout)
      } else if (value[value.length - 1] == '新增元素') {
        if (this.dataType.length == 0) {
          this.dictionarydataType()
        }
        this.tableData = []
        this.AddNewElementField = '新增元素'//打开新增元素弹框
        this.cascaderPanel = false
        clearTimeout(this.setTimeout)
      } else if (value[value.length - 1] == '删除文本信息') {
        this.AddNewElementField = '删除文本信息'//打开新增元素弹框
        this.deleteelement()
        this.cascaderPanel = false
        clearTimeout(this.setTimeout)
      } else if (value[value.length - 1] == '公式配置') {
        this.cascaderPanel = false
        clearTimeout(this.setTimeout)

        this.toFormulaEdit();
      }
    },

    mouseout22() {//鼠标移出事件
      clearTimeout(this.setTimeout)
      this.setTimeout = setTimeout(() => {
        this.cascaderPanel = false
      }, 500)
    },
    mousemove22() {//鼠标移入事件
      clearTimeout(this.setTimeout)
      this.setTimeout = setTimeout(() => {
        this.cascaderPanel = true
      }, 500)
    },
    RightClick2(tr, td, x1, x2, y1, y2) {
      console.log("888555", event.target.getAttribute("keyname"))
      let targetkeyname = event.target.getAttribute("keyname");
      //console.log(event.target)
      let ekey = null;
      if (this.ekeyReg.test(targetkeyname)) {
        ekey = targetkeyname.match(this.ekeyReg)[1]
      }
      this.table = {
        tr,
        td,
        ekey
      }


      this.left = window.event.clientX - 80
      let Y = window.event.clientY - 54
      if (window.outerHeight - Y > 200) {
        this.top = window.event.clientY - 80 + 65
      } else {
        this.top = window.event.clientY - 270 + 65
      }
      this.cascaderPanel = true
      clearTimeout(this.setTimeout)
      this.setTimeout = setTimeout(() => {
        this.cascaderPanel = false
      }, 3000)

      let curTdEle = this.getTd(event.target);
      console.log(curTdEle, 'curTdEle');
      if (this.isMultiple) {
        //是否已经存在了
        for (let i = 0; i < this.eleData.length; i++) {
          if (this.eleData[i].tr == tr && this.eleData[i].td == td) {
            //存在就移除
            this.eleData[i].tdEle.classList.remove('select-td');
            this.eleData.splice(i, 1);
            return;
          }
        }

        //添加
        this.eleData.push({
          tr,
          td,
          tdEle: curTdEle,
          name: curTdEle.getAttribute("title")
        })
      } else {
        this.clearSelect();
        this.eleData = [{
          tr,
          td,
          tdEle: curTdEle,
          name: curTdEle.getAttribute("title")
        }]
      }

      curTdEle.classList.add('select-td')

      this.$nextTick(() => {
        //隐藏日期弹框
        let pickers = document.querySelectorAll('.el-date-picker__header')
        for (let i = 0; i < pickers.length; i++) {
          pickers[i].parentNode.parentNode.parentNode.style.display = 'none'
        }
      })
    },
    LeftClick(event, key) {
      console.log('点击左11111', event.target, key);
    },

    getTd(ele) {

      while (ele.tagName.toLowerCase() != 'td' && ele.id != 'parent') {
        ele = ele.parentNode;
        //console.log(ele);
      }

      if (ele.id == 'parent') {
        return null;
      } else {
        return ele;
      }

    },

    deleteelement() {//删除元素提示
      let _that = this
      this.$confirm('确认删除该元素？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _that.submit({
          colName: '/',
          tabId: this.pkeyId,
          tdIndex: this.table.td,
          trIndex: this.table.tr,
        })
      }).catch(() => {
        _that.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      _that.$refs.cascader.clearCheckedNodes()
      _that.AddNewElementField = ''
    },
    getInformation2(a, b, c) {
      if (this.AddNewElementField) {
        this.table = {
          tr: b,
          td: c
        }
      }
    },
    async cop() {
      let _that = this
      console.log("33")
      var MyComponent = await Vue.extend({
        template: localStorage.getItem('editElement'),
        data() {
          return {
            formData: {},
            getTokenHeader: {},
            dap_site_data: {}
          }
        },
        methods: {
          //3,1,2,5,4,4,$event
          contextmenuClick(tr, td, x1, x2, y1, y2, event) {
            _that.RightClick2(tr, td, x1, x2, y1, y2)
          },
          //鼠标右键事件
          RightClick(tr, td, x1, x2, y1, y2) {
            _that.RightClick2(tr, td, x1, x2, y1, y2)
          },
          getInformation(a, b, c) {
            _that.getInformation2(a, b, c)
          },
          getRegularExpression() { },
          dateKeydown() { },
          formUploadSuccess() { },
          formUploadExceed() { },
          formUploadLoading() { },
          delTableFormFile() { },
          formUploadError() { },
          uploadprogress() { },
          formRemoteMethod() { },
          formRemoteChange() { },
          checkboxGroupChange() { },
          keyupShiftUp() { },
          keyupShiftDown() { },
          keyupShiftLeft() {

          },
          keyupShiftRight() {
          },
          inputLeftClick(event, key) {
            _that.LeftClick(event, key)
          },
          KeyDown(e) {
            if (e.ctrlKey || e.metaKey) {
              console.log("检测到按下了control键");
            }
          },
        },
        mounted() {
          window.addEventListener("keydown", this.KeyDown, true);
        },
      })
      var component = new MyComponent().$mount()

      document.getElementById('parent').appendChild(component.$el);
      this.testTips()
    },
    async copss() {
      let _that = this
      console.log("44")
      var MyComponent = await Vue.extend({
        template: localStorage.getItem('editElement'),
        data() {
          return {
            formData: {},
            getTokenHeader: {},
            dap_site_data: {}
          }
        },
        methods: {
          contextmenuClick(tr, td, x1, x2, y1, y2, event) {
            _that.RightClick2(tr, td, x1, x2, y1, y2)
          },
          //鼠标右键事件
          RightClick(tr, td, x1, x2, y1, y2) {
            _that.RightClick2(tr, td, x1, x2, y1, y2)
          },
          getInformation(a, b, c) {
            _that.getInformation2(a, b, c)
          },
          getRegularExpression() { },
          dateKeydown() { },
          formUploadSuccess() { },
          formUploadExceed() { },
          formUploadLoading() { },
          delTableFormFile() { },
          formUploadError() { },
          uploadprogress() { },
          formRemoteMethod() { },
          formRemoteChange() { },
          checkboxGroupChange() { },
          keyupShiftUp() { },
          keyupShiftDown() { },
          keyupShiftLeft() {

          },
          keyupShiftRight() { },
          inputLeftClick(event, key) {
            _that.LeftClick(event, key)
          },
        },
      })
      var component = new MyComponent().$mount()
      let na = document.getElementById('parent')
      na.innerHTML = `<div
        class='parent'
        id='parent'
      ></div>`
      document.getElementById('parent').appendChild(component.$el);
    },
    async dictionarydataType() {
      const { data: res } = await dictionarydataType()
      console.log(res);
      if (res.code == 200) {
        this.dataType = res.data
      }
    },
    returns() {
      this.$router.push({
        path: '/project/tree',
        query: {
          pid: this.pid,
          wbsid: this.wbsid,
        }
      })
    },
    //#region 左侧替换元素
    cancelReplace() {//替换元素取消按钮
      this.AddNewElementField = ''
      this.$refs.cascader.clearCheckedNodes()//调用方法无效
    },
    saveReplace() {//保存按钮
      console.log(this.checkList, 'checkList');

      // if (this.value&& this.table) {
      //   this.tag = true
      //   this.submit({
      //     tabId: this.pkeyId,
      //     tdIndex: this.table.td,
      //     trIndex: this.table.tr,
      //     colName: "",
      //     htmlType: this.value
      //   })
      // }
      if (this.value && this.table && this.checkList.length === 0) {
        this.tag = true
        this.submit2([{
          tabId: this.pkeyId,
          tdIndex: this.table.td,
          trIndex: this.table.tr,
          colName: "",
          htmlType: this.value
        }])
      } else if (this.value && this.checkList.length > 0) {
        let arr = []
        this.checkList.forEach((ele) => {
          arr.push({
            tabId: this.pkeyId,
            tdIndex: ele.td,
            trIndex: ele.tr,
            colName: "",
            htmlType: this.value
          })
        })
        this.submit2(arr)
      }
      else {
        this.$message({
          type: "error",
          message: "请右键选择要替换的元素"
        })
      }
    },
    async getElementInfoByTabId() {//获取字段信息
      const { data: res } = await getElementInfoByTabId({ tabId: this.initTableId })
      console.log(res);
      if (res.code === 200) {
        this.options = res.data
      }
    },
    async submit(da) {//保存替换元素
      const { data: res } = await submit(da)
      if (res.code == 200) {
        const { data: res } = await getExcelHtml({ pkeyId: this.pkeyId })
        console.log(res);
        if (res.code === 200) {
          this.tag = false
          // this.value = ''
          this.options = []
          const html = res.data
            .replaceAll('<el-select', '<el-input')
            .replaceAll('<el-date-picker', '<el-date-picker :append-to-body="false"')
            .replaceAll('<el-cascader', '<el-cascader :append-to-body="false"')
            .replaceAll('<el-time-select', '<el-time-select :append-to-body="false"');
          localStorage.setItem('editElement', html)

          this.getElementInfoByTabId()
          this.copss()
          this.getUnMatchFieldData()
        }
      }
    },
    async submit2(da) {//批量保存替换元素
      const { data: res } = await submit2(da)
      if (res.code == 200) {
        const { data: res } = await getExcelHtml({ pkeyId: this.pkeyId })
        console.log(res);
        this.tag = false
        if (res.code === 200) {

          // this.value = ''
          this.checkList = []
          this.options = []
          const html = res.data
            .replaceAll('<el-select', '<el-input')
            .replaceAll('<el-date-picker', '<el-date-picker :append-to-body="false"')
            .replaceAll('<el-cascader', '<el-cascader :append-to-body="false"')
            .replaceAll('<el-time-select', '<el-time-select :append-to-body="false"');
          localStorage.setItem('editElement', html)
          this.getElementInfoByTabId()
          this.copss()
          this.getUnMatchFieldData()
        }
      }
    },
    //#endregion

    //#region 弹框事件
    handleClose() {
      console.log('取消');
      this.tableData = []
      this.$refs.cascader.clearCheckedNodes()
      this.AddNewElementField = ''
    },
    addyuansu() {//新增元素
      this.tableData.unshift({ eName: '', eType: '', assist: 0 })
    },
    deleteziduan(key) {//删除新增元素弹框字段
      this.tableData.splice(key, 1)
    },
    pushNewElementField() {//确定添加按钮
      if (this.tableData.length > 0) {
        let tag = true
        this.tableData.forEach(val => {
          if (!(val.eName && val.eType)) {
            tag = false
          }
        })
        if (tag) {
          this.submitBatch({
            projectId: this.pid,
            initTableName: this.initTableName,
            id: this.pkeyId,
            listData: this.tableData,
          })
        } else {
          this.$message({
            type: 'error',
            message: '请填写所有字段'
          });
        }
      }
    },
    async submitBatch(da) {
      const { data: res } = await submitBatch(da)
      console.log(res);
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.AddNewElementField = ''

        //更新下拉列表s
        this.getElementInfoByTabId()
        this.getUnMatchFieldData()
      }
    },
    //#endregion

    //跳转到公式配置页面
    toFormulaEdit() {
      let eleid = null;
      if (this.table.ekey) {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].ekey == this.table.ekey) {
            eleid = this.options[i].id;
            break;
          }
        }
      }

      if (eleid == null) {
        this.$message({
          type: "warning",
          message: "找不到元素id"
        })
        this.$refs.cascader.clearCheckedNodes()//调用方法无效
        return;
      }

      // this.$router.push({
      //   path: '/formula/edit',
      //   query: {
      //     wbsid: this.wbsid,
      //     eleid: eleid,
      //     nodeid:this.nodeid,
      //     projectid:this.pid
      //   }
      // });

      this.eleid = eleid;

      if (this.globaltype === 10) {
        this.formulaCompVisible = true;
      } else {
        this.formulaCompVisible1 = true;
      }
      this.$refs.cascader.clearCheckedNodes()
    },

    // 返回上一页
    toBack() {
      // this.$router.go(-1);

      this.$emit('hideDialog')

    },
    //调整表单
    adjustExcel() {
      this.$emit('hideDialog')
      this.$emit('adjustExcel', this.pkeyId)
    },


    eleDelete(index) {
      this.eleData[index].tdEle.classList.remove('select-td');
      this.eleData.splice(index, 1);
    },
    clearSelect() {
      this.eleData.forEach((data) => {
        data.tdEle.classList.remove('select-td');
      })
    },
    multipleChange(value) {
      if (!value && this.eleData.length > 1) {
        let last = this.eleData[this.eleData.length - 1];
        this.clearSelect();
        this.eleData = [last];
        this.eleData[0].tdEle.classList.add('select-td');
      }
    },



    noRepeat(tempArr) {
      for (let i = 0; i < tempArr.length; i++) {
        for (let j = i + 1; j < tempArr.length; j++) {
          if (tempArr[i].tr == tempArr[j].tr && tempArr[i].td == tempArr[j].td) {
            tempArr.splice(j, 1);
            j--;
          }
        }
      }
      return tempArr;
    },
    //excel父节点点击检测
    parentClick(e) {
      const target = e.target;

      let isNameEmpty = false;
      const { metaKey, ctrlKey } = e

      let bgs = document.querySelectorAll("#parent .oldlace-bg")

      for (let i = 0; i < bgs.length; i++) {
        bgs[i].classList.remove("oldlace-bg");
      }
      let tdEle = this.getParentTD(target);

      let target1
      if (tdEle) {
        let mydiv = tdEle.getElementsByTagName('div')
        target1 = mydiv[0]

        const hasWarnStyle = el =>
          el.classList.contains('warnstyle') ||
          el.classList.contains('el-date-editor') &&
          el.querySelector('.warnstyle-date');
        isNameEmpty = hasWarnStyle(target1) ? true : false;

        // if (target1.classList.contains('warnstyle')) {
        //   isNameEmpty = true
        // } else if (target1.classList.contains('el-date-editor')) {
        //   const div = target1.getElementsByClassName("warnstyle-date")
        //   if (div.length) {
        //     isNameEmpty = true
        //   }
        // } else {
        //   isNameEmpty = false
        // }
      } else {
        tdEle = target
        const mydiv = tdEle.getElementsByTagName('div')
        target = mydiv[0]
        isNameEmpty = false
      }

      let curTdEle = this.getTd(target);

      if (target.getAttribute('trindex') !== null && target.getAttribute('tdindex') || target1.getAttribute('trindex') !== null && target1.getAttribute('tdindex')) {
        let tdEle = this.getParentTD(target);

        if (tdEle) {
          const mydiv = tdEle.getElementsByTagName('div')
          mydiv[0].classList.add("oldlace-bg");
          if (metaKey || ctrlKey) {
            if (!target.classList.contains('select-td')) {
              const index = this.checkList.findIndex(el=> !el.isMulti)
              if (index !== -1) {
                this.checkList.splice(index, 1)
              }
              target.classList.add("select-td");
              this.checkList.push({
                tr: target.getAttribute('trindex') || target1.getAttribute('trindex'),
                td: target.getAttribute('tdindex') || target1.getAttribute('tdindex'),
                name: !isNameEmpty ? curTdEle.getAttribute("title") || '暂未匹配元素' : '暂未匹配元素',
                isMulti: true
              })
            } else {
              target.classList.remove("select-td");
              const tr = target.getAttribute('trindex') || target1.getAttribute('trindex')
              const td = target.getAttribute('tdindex') || target1.getAttribute('tdindex')
              const index = this.checkList.findIndex(ele => ele.tr === tr && ele.td === td)
              this.checkList.splice(index, 1)
              // this.checkList.forEach((ele, index) => {
              //   if (ele.tr === target.getAttribute('trindex') || ele.tr === target1.getAttribute('trindex')) {
              //     console.log(this.checkList[index], index, 'target');
              //     this.checkList.splice(index, 1)
              //   }
              // })
            }
          } else {
            this.checkList = [{
              tr: target.getAttribute('trindex') || target1.getAttribute('trindex'),
              td: target.getAttribute('tdindex') || target1.getAttribute('tdindex'),
              name: !isNameEmpty ? curTdEle.getAttribute("title") || '暂未匹配元素' : '暂未匹配元素',
              isMulti: false
            }]
            document.querySelectorAll('#parent .select-td').forEach(el => el.classList.remove('select-td'));
          }
          // if (!target.classList.contains('select-td')) {

          //   if (ctrlKey || metaKey) {
          //     target.classList.add("select-td");
          //     this.checkList.push({
          //       tr: target.getAttribute('trindex') || target1.getAttribute('trindex'),
          //       td: target.getAttribute('tdindex') || target1.getAttribute('tdindex'),
          //       name: !isNameEmpty ? curTdEle.getAttribute("title") || '暂未匹配元素' : '暂未匹配元素'

          //     })
          //   } else {
          //     this.checkList = [{
          //       tr: target.getAttribute('trindex') || target1.getAttribute('trindex'),
          //       td: target.getAttribute('tdindex') || target1.getAttribute('tdindex'),
          //       name: !isNameEmpty ? curTdEle.getAttribute("title") || '暂未匹配元素' : '暂未匹配元素'
          //     }]
          //   }
          // } else {
          //   target.classList.remove("select-td");
          //   this.checkList.forEach((ele, index) => {
          //     if (ele.tr === target.getAttribute('trindex') || ele.tr === target1.getAttribute('trindex')) {
          //       this.checkList.splice(index, 1)
          //     }
          //   })
          // }
        }

        this.noRepeat(this.checkList)
        console.log(this.checkList, 'this.checkList');
      }
    },

    getParentTD(ele) {
      let targetParent = ele.parentNode;
      while (targetParent.nodeName !== "TD") {
        if (targetParent.id == 'parent') {
          return null;
        }
        targetParent = targetParent.parentNode;
      }
      return targetParent;
    },
    testTips() {
      console.log("test tips start");
      document.querySelectorAll('#parent div[htmlelementerror]').forEach(td => {
        const htmlElementError = td.getAttribute('htmlelementerror')
        if (htmlElementError == '1') {
          td.style.position = 'relative'
          const child = document.createElement('div')
          child.className = 'warnstyle-date'
          td.appendChild(child)
        }
      })
      document.querySelectorAll('#parent input').forEach(input => {
        input.readOnly = true;
      })
      document.querySelectorAll('#parent td[title]').forEach(td => {
        // 鼠标进入时临时清空 title 并显示自定义提示
        td.addEventListener('mouseenter', function (e) {
          const inputElement = td.querySelector('[placeholder]'); // 在td元素中查找具有placeholder属性的子元素
          if (inputElement) {
            const placeholderValue = inputElement.getAttribute('placeholder');
            if (placeholderValue) {
              const title = this.getAttribute('title')
              this.setAttribute('title', placeholderValue);
              this.setAttribute('title_original', title)
            }
          }
        });
        // 鼠标离开时恢复 title 并移除自定义提示
        td.addEventListener('mouseleave', function () {
          const title = this.getAttribute('title_original')
          if (title) {
            // 恢复原始 title 属性
            this.setAttribute('title', title);
            this.removeAttribute('title_original');
          }
        });
      });
    }
  },
  watch: {
    'options'() {
      if (this.options) {
        this.options2 = [{
          value: '编辑元素字段',
          label: '编辑元素字段',
          children: [{
            value: '替换元素',
            label: '替换元素'
          }, {
            value: '新增元素',
            label: '新增元素'
          }, {
            value: '删除文本信息',
            label: '删除文本信息'
          }]
        }, {
          value: '公式配置',
          label: '公式配置',
        }]
      } else {
        this.options2 = [{
          value: '编辑元素字段',
          label: '编辑元素字段',
          children: [{
            value: '新增元素',
            label: '新增元素'
          }, {
            value: '删除文本信息',
            label: '删除文本信息'
          }]
        }, {
          value: '公式配置',
          label: '公式配置',
        }]
      }
    },
    'value'(values) {
      if (values) {
        this.options.forEach(val => {
          if (val.id == values) {
            this.names = val.eName
          }
        })
      }
    },
    initTableId(val) {


      this.initTableId = val
      this.getUnMatchFieldData()
    },
    // 'cascaderPanel'(val){
    //   this.AddNewElementField = '替换元素'
    // }
  }
}
</script>

<style lang="scss" scoped>
.editElement {
  padding-bottom: 40px !important;

  .header {
    color: rgb(240, 114, 10);
  }

  .tihuan {
    margin-top: 15px;
    margin-bottom: 10px;
    font-family: SourceHanSansSC;
    font-weight: 400;
    font-size: 14px;
    color: rgb(16, 16, 16);
    font-style: normal;
    letter-spacing: 0px;
    line-height: 20px;
    text-decoration: none;
  }
}

.parent {
  ::v-deep .select-td {
    background-color: #DDEAFE !important;
    border-color: #2550A2 1px solid;
  }

  ::v-deep .oldlace-bg {
    border-width: 4px;
    border-color: #2550A2;
    border-style: solid;

  }

  ::v-deep .el-popper {
    display: none !important;
  }
}

::v-deep .warnstyle-date {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #FE6F21;
  background-image: url('/img/login/warn-1.png') !important;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

::v-deep .warnstyle-date.select-td {
  background-color: #DDEAFE;
}

::v-deep .warnstyle .el-input__inner {
  background-color: #FE6F21;
  background-image: url('/img/login/warn-1.png') !important;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center
}

::v-deep .warnstyle .el-textarea__inner {
  background-color: #FE6F21;
  background-image: url('/img/login/warn-1.png') !important;
  background-repeat: no-repeat;
  // background-size:cover;
  background-position-x: 45%;
  background-position-y: 46%;
}

.full-dialog {
  ::v-deep .el-dialog__body {
    padding-bottom: 0;
    padding-top: 0;
  }

  ::v-deep .basic-container {
    height: calc(100vh - 60px);
  }
}

.replace_box {
  margin-top: 20px;
  border: 1px gray dashed;
  width: 95%;
  height: calc(100vh - 780px);
  position: relative;
  padding-top: 20px;
  padding-left: 20px;
}


.check_box {
  margin-top: 10px;
  //line-height: 50px;
  height: 50px;
  padding: 10px;
  background-color: #E8E8E8;
  overflow-y: auto;
}

.save-btn {
  width: 100%;

  .el-button--primary {
    width: 100%;
    background: #2550A2;
    border-color: #2550A2;
  }
}

.message-box {
  margin-top: 20px;
  width: 95%;
  border: 1px rgb(254, 240, 13) solid;
  background: rgb(254, 252, 233);
  padding: 10px;
}
</style>
