<!--
 * @Author: 曹捷
 * @Date: 2021-11-03 10:33:03
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-11-03 11:48:19
 * @Description: 设置 编辑器表格宽度
-->
<template>
  <a-modal @cancel="closeDialog" @ok="saveInfo" v-if="showModal" :maskClosable="false" style="top: 20px" :keyboard="false" title="表格宽度设置" v-model:visible="showModal" width="40%">
    <div v-for="(item,index) in tableList" :key="index">
      <a-divider><b>表格1</b></a-divider>
      <div class="flex-l-r">
        <div v-for="(ele,idx) in item.widthList" :key="idx">
          <div class="title">列{{idx+1}}</div>
          <div>
            <a-input v-model:value="ele.width" suffix="%" placeholder="请输入列宽度百分比"></a-input>
          </div>
        </div>
      </div>
    </div>

  </a-modal>
</template>

<script>
import { onMounted, inject, reactive, ref, toRefs, watch, getCurrentInstance } from 'vue'
export default {
  props: {
    open: {
      type: Boolean,
    },
    dom: {
      type: Object
    }
  },
  setup (props, context) {
    let _data = reactive({
      tableList: [],
      showModal: props.open,
    })
    let _methods = {
      initTable () {
        let dom = props.dom
        let table = dom.querySelectorAll('table')
        if (table && table.length > 0) {
          table.forEach((element, index) => {
            let info = { name: '表格' + (index + 1), widthList: [] }
            let thList = element.querySelector('tr').querySelectorAll('th')
            thList.forEach(ele => {
              if (!ele.style.width) {
                ele.style.width = `${100 / thList.length}%`
              }
              info.widthList.push({ width: ele.style.width.replace('%', '') })
            })
            _data.tableList.push(info)
          })
        }
      },
      closeDialog () {
        context.emit('update:open', false)
        _data.tableList = []
      },
      saveInfo () {
        let table = props.dom.querySelectorAll('table')
        if (table && table.length > 0) {
          _data.tableList.forEach((element, index) => {
            let tableDom = table[index]
            let thDomList = tableDom.querySelector('tr').querySelectorAll('th')
            element.widthList.forEach((ele, idx) => {
              thDomList[idx].style.width = `${ele.width}%`
            });
          });
        }
        _methods.closeDialog()
      }
    }
    watch(() => props.open, (value) => {
      if (value) {
        _methods.initTable()
      }
    })
    return {
      ...toRefs(_data),
      ..._methods
    }
  }
}
</script>

<style>
</style>