<template>
  <div class="edit-wbs-container">
    <div class="header">
      <div class="title">编辑WBS库</div>
      <div class="go-back" @click="GoBack()">
        返回上一级
      </div>
    </div>
    <div class="edit-content">
      <div class="excel-box hc-excel-table-form" @click="parentClick($event)">
        <div class='parent' id='parent'></div>
      </div>
      <div class="right">
        <div class="tabs">
          <avue-tabs :option="option" @change="handleChange"></avue-tabs>
        </div>
        <div class="tabs-content">
          <span v-if="type.prop === 'tab1'">
            <setInputTPT v-if="type.prop === 'tab1'" :pkeyId='pkeyId' @cop='domss' :htmlData="htmlData"
              :checkList="checkList" :checkNameList="checkNameList" @change="change" />
          </span>
          <span v-else-if="type.prop === 'tab2'">
            <electronicSignature :pkeyId1='pkeyId' :htmlData1="htmlData" :excelId="excelId" :times="timesTimeElement"
              @edit="signatureEdit" @timeFocus="timeElementFocus" />
          </span>
          <span v-else-if="type.prop === 'tab3'">
            <setFormula :pkeyId1='pkeyId' :htmlData="htmlData" />
          </span>
          <span v-else-if="type.prop === 'tab4'">
            <editDefault :pkeyId1='pkeyId' :htmlData1="htmlData" />
          </span>
          <span v-else-if="type.prop === 'tab5'">
            <promptSettings :pkeyId1='pkeyId' :htmlData1="htmlData" />
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import setInputTPT from './template/setInputTPT.vue'
import electronicSignature from './template/electronicSignature.vue'
import setFormula from './template/setFormula.vue'
import editDefault from './template/editDefault.vue'
import promptSettings from './template/promptSettings.vue'
import HtmlSelect from '../components/HtmlSelect.vue'
import Vue from 'vue'
// import {getExcelHtml} from '@/api/exctab/excelmodel'
import { getSignDetail } from "@/api/manager/AdjustForm";

export default {
  props: ['pkeyId', 'excelId'],
  data() {
    return {
      setUptype: 0,//右侧显示的类型1
      htmlData: {
        name: '',
        tr: '',
        td: ''
      },
      type: {},
      option: {
        column: [{
          label: '设置输入框',
          prop: 'tab1',
          width: 10,
        }, {

          label: '电签位置配置',
          prop: 'tab2',
        },
        {
          label: '参数设置',
          prop: 'tab3',
        }
          ,
        {

          label: '编辑默认信息',
          prop: 'tab4',
        }, {

          label: '提示设置',
          prop: 'tab5',
        }
        ]
      },
      checkList: [],
      checkNameList: [],
      isSignatureEdit: false,
      isTimeElement: false,
      timesTimeElement: {}
    }
  },
  mounted() {
    this.cop()
    this.type = this.option.column[0];
  },


  methods: {
    change() {
      this.checkList = []
      this.checkNameList = []
    },
    GoBack() {//返回上一级
      this.$emit('remove')
    },
    handleChange(column) {
      this.type = column;
      this.isSignatureEdit = false
    },
    // async getExcelHtml(pkeyId) {
    //   const {data: res} = await getExcelHtml({pkeyId})
    //   console.log(res);
    //   if (res.code === 200) {
    //     localStorage.setItem('excelHtml', res.data)
    //     this.copss();
    //   }
    // },
    async cop() {
      let _that = this
      var MyComponent = await Vue.extend({
        template: localStorage.getItem('excelHtml'),
        components: { HtmlSelect },
        data() {
          return {
            formData: {},
            getTokenHeader: {},
            dap_site_data: {}
          }
        },
        methods: {
          contextmenuClick(tr, td, x1, x2, y1, y2, event) {
          },
          getInformation(name, tr, td) {//鼠标右键事件
            _that.getInformation(name, tr, td)
          },
          formUploadSuccess() {
          },
          formUploadExceed() {
          },
          formUploadLoading() {
          },
          delTableFormFile() {
          },
          formUploadError() {
          },
          uploadprogress() {
          },
          formRemoteMethod() {
          },
          getRegularExpression() {
          },
          checkboxGroupChange() {
          },
          formRemoteChange() {
          },
          dateKeydown() {
          },
          keyupShiftUp() {
          },
          keyupShiftDown() {
          },
          keyupShiftLeft() {
          },
          keyupShiftRight() {
          },
          inputLeftClick({ e, params }) {
            _that.parentClick(e, params)
          },
        }
      })
      var component = new MyComponent().$mount()
      document.getElementById('parent').appendChild(component.$el);
    },

    async copss() {
      let _that = this
      var MyComponent = await Vue.extend({
        template: localStorage.getItem('excelHtml'),
        components: { HtmlSelect },
        data() {
          return {
            formData: {},
            getTokenHeader: {},
            dap_site_data: {}
          }
        },
        methods: {
          contextmenuClick(tr, td, x1, x2, y1, y2, event) {
          },
          getInformation(name, tr, td) {//鼠标右键事件
            _that.getInformation(name, tr, td)
          },
          formUploadSuccess() {
          },
          formUploadExceed() {
          },
          formUploadLoading() {
          },
          delTableFormFile() {
          },
          formUploadError() {
          },
          uploadprogress() {
          },
          getRegularExpression() {
          },
          formRemoteMethod() {
          },
          checkboxGroupChange() {
          },
          formRemoteChange() {
          },
          dateKeydown() {
          },
          keyupShiftUp() {
          },
          keyupShiftDown() {
          },
          keyupShiftLeft() {
          },
          keyupShiftRight() {
          },
          inputLeftClick({ e, params }) {
            _that.parentClick(e, params)
          },
        }
      })
      var component = new MyComponent().$mount()
      let na = document.getElementById('parent')
      na.innerHTML = `<div
        class='parent'
        id='parent'
      ></div>`
      document.getElementById('parent').appendChild(component.$el);
    },
    domss() {
      this.copss()
    },

    getInformation(name, tr, td) {//鼠标点击事件
      console.log('getInformation', name, tr, td);
      if (!this.isTimeElement) {
        let tdEle = null;
        //获取TD元素
        if (event.target.nodeName === "TD") {
          tdEle = event.target
        } else {
          tdEle = this.getParentTD(event.target);
        }
        let moreObj = {};
        if (tdEle) {
          moreObj = this.getWidget(tdEle);
        }
        this.htmlData = Object.assign({
          name,
          tr,
          td
        }, moreObj)
      } else {
        this.$set(this.timesTimeElement, 'colName', name)
      }
    },
    signatureEdit(data) {
      this.isSignatureEdit = data
    },
    //excel父节点点击检测
    async parentClick(e, params = null) {
      console.log('parentClick', e.target);
      if (params) {
        this.getInformation(params.name, params.trIndex, params.tdIndex)
      }
      if (!this.isTimeElement) {
        let target = e.target;
        const { metaKey, ctrlKey } = e
        let bgs = document.querySelectorAll("#parent .oldlace-bg")
        //console.log(bgs)
        for (let i = 0; i < bgs.length; i++) {
          bgs[i].classList.remove("oldlace-bg");
        }
        //console.log(target.getAttribute('trindex'))
        let tdEle = this.getParentTD(target);
        this.htmlData.dqid = tdEle ? tdEle.getAttribute('dqid') : ''
        // const {data: res} = await getSignDetail({id: this.htmlData.dqid})
        //   console.log(res,'res');
        if (this.htmlData.dqid) {
          if (this.type.prop === 'tab2' && this.isSignatureEdit) {
            this.htmlData.obj = null
          } else {
            const { data: res } = await getSignDetail({ id: this.htmlData.dqid, tabId: this.pkeyId })
            if (res.code === 200) {
              this.htmlData.obj = res.data
            }
          }
        } else {
          this.htmlData.obj = null
        }
        let target1
        if (tdEle) {
          let mydiv = tdEle.getElementsByTagName('div')
          target1 = mydiv[0]
        } else {
          tdEle = target
          let mydiv = tdEle.getElementsByTagName('div')
          target = mydiv[0]
        }
        let keyname = ''
        try {
          keyname = target.getAttribute('keyname') || target1.getAttribute('keyname')
        } catch {
        }
        console.log('keyname1111111111111', keyname, params, target)
        this.htmlData.keyname = params ? params.keyName : keyname
        if (target && target.getAttribute('trindex') && target.getAttribute('tdindex') || target1 && target1.getAttribute('trindex') && target1.getAttribute('tdindex') || params && params.trIndex && params.tdIndex) {
          let tdEle = this.getParentTD(target);
          if (tdEle) {
            //橙色背景
            target.classList.add("oldlace-bg");
            if (metaKey || ctrlKey) {
              target.classList.add("select-td");
              this.checkNameList.push(this.htmlData)
              this.checkList.push({
                tr: target.getAttribute('trindex') || target1.getAttribute('trindex'),
                td: target.getAttribute('tdindex') || target1.getAttribute('tdindex'),
              })
            } 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.checkNameList.forEach((ele, index) => {
                if (this.htmlData.tr === ele.tr) {
                  this.checkNameList.splice(index, 1)
                }
              })
            }
          }
        }
      } else {
        let target = e.target;
        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]
        }
        let keyname = ''
        try {
          keyname = target.getAttribute('keyname') || target1.getAttribute('keyname')
        } catch { }
        this.$set(this.timesTimeElement, 'keyname', keyname)
        console.log(this.timesTimeElement)
      }
    },
    getParentTD(ele) {
      let targetParent = ele.parentNode;
      while (targetParent && targetParent.nodeName !== "TD") {
        if (targetParent.id == 'parent') {
          return null;
        }
        targetParent = targetParent.parentNode;
      }
      return targetParent;
    },


    //获取控件信息
    getWidget(tdEle) {
      let selectElement = tdEle.querySelectorAll('.el-select');
      let isMultiple = false
      if (selectElement.length) {

        // 遍历每个元素，检查是否包含 is-multiple 类名
        selectElement.forEach(element => {
          if (element.classList.contains('is-multiple')) {
            isMultiple = true;
          }
        });
        if (isMultiple) {
          let options = selectElement[0].__vue__.options;
          let selectDatas = [];
          for (let i = 0; i < options.length; i++) {
            selectDatas.push({
              dictValue: options[i].label
            });
          }
          return {
            type: 'selectBox',
            selectDatas
          }
        }
      }
      let checkLabels = tdEle.querySelectorAll('.el-checkbox-group span.el-checkbox__label');
      //console.log(checkLabels)
      if (checkLabels.length > 0) {
        let checkLabelDatas = [];
        for (let i = 0; i < checkLabels.length; i++) {
          //console.dir(checkLabels[i])
          checkLabelDatas.push({
            dictValue: checkLabels[i].innerText
          });
        }
        return {
          type: 'checkbox',
          checkLabelDatas
        }
      }

      let radioLabels = tdEle.querySelectorAll('.el-radio .el-radio__label');
      if (radioLabels.length > 0) {
        let radioDatas = [];
        for (let i = 0; i < radioLabels.length; i++) {
          radioDatas.push({
            dictValue: radioLabels[i].innerText
          });
        }
        return {
          type: 'radio',
          radioDatas
        }
      }

      let elSelect = tdEle.querySelectorAll('.el-select');
      //console.dir(elSelect[0])
      if (elSelect.length) {
        let options = elSelect[0].__vue__.options;
        let selectDatas = [];
        for (let i = 0; i < options.length; i++) {
          selectDatas.push({
            dictValue: options[i].label
          });
        }
        return {
          type: 'select',
          selectDatas
        }

      }


      return {};
    },
    //是否为时间元素选择模式
    timeElementFocus(val) {
      this.isTimeElement = val
    },
  },
  components: {
    setInputTPT,
    electronicSignature,
    setFormula,
    editDefault,
    promptSettings
  }
}
</script>

<style lang="scss" scoped>
.edit-wbs-container {
  background-color: #fff;
  padding: 0 20px 68px 20px;
  box-sizing: border-box;
  height: 100%;
  overflow-y: hidden;

  .header {
    width: 100%;
    display: flex;
    margin: 10px 0;

    .title {
      font-size: 24px;
      font-weight: 700;
    }    
  }

  .go-back {
    color: rgba(0, 82, 216, 1);
    text-decoration: underline;
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-left: 20px;
  }

  .edit-content {
    margin-top: -20px;
    height: 100%;
    display: grid;
    grid-template-columns: 1.7fr 1fr;
    gap: 40px;


    .excel-box {
      flex-shrink: 0;
      overflow-y: auto;

      .parent {
        overflow-y: auto;
      }

      ::v-deep table {
        width: 100% !important;
      }

    }

    .right {
      width: 100%;
      margin-top: -44px;

      .tabs-content {
        margin-left: 40px;
      }
    }
  }
}



// 设置图片样式
.hc-upload-table-form {
  position: relative;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hc-upload-table-form .el-upload {
  position: relative;
  flex: 1;
  height: 100%;
  color: #ccc;
}

.hc-upload-table-form .el-upload .hc-table-form-icon {
  font-size: 24px;
  font-weight: 100;
}

.hc-upload-table-form .el-upload .hc-table-form-img {
  width: 100%;
  height: 100%;
}

.excel-box {
  ::v-deep .oldlace-bg {
    background-color: oldlace;
  }

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

#parent {
  ::v-deep .el-popper {
    display: none !important;
  }
}
</style>
