/**
* v-fitColumn el-table 中设置 el-table-column 宽度
* 使用： el-table 添加v-fitColumn,在操作列上添加 class-name="fit-width"
*
* 注意：此自定义指令有bug,在列较少的时候，会出现一个横向混动条~ 暂时废弃。使用hooks useFitColumn 替代
*/
function adjustColumnWidth(table, padding = 0) {
  const colgroup = table.querySelector("colgroup");
  const colDefs = [...colgroup.querySelectorAll("col")];

  colDefs.forEach((col) => {
    const clsName = col.getAttribute("name");
    const cells = [
      ...table.querySelectorAll(`th.${clsName}`),
      ...table.querySelectorAll(`td.${clsName}`),
    ];

    if (!cells[0]?.classList?.contains?.("fit-width")) return

    const widthList = cells.map((el) => {
      return el.querySelector(".cell")?.scrollWidth || 0;
    });

    const max = Math.max(...widthList);

    table.querySelectorAll(`col[name=${clsName}]`).forEach((el) => {
      el.setAttribute("width", max + padding);
    });
  });
}

export default {
  mounted(el, binding, vnode) {
    setTimeout(() => {
      adjustColumnWidth(el, binding.value)
    }, 100);
  },
  updated(el, binding, vnode) {
    el.classList.add("fit-table");
    setTimeout(() => {
      adjustColumnWidth(el, binding.value)
    }, 100);
  }
}
