//mixins/tableDragResize.js
import Vue from 'vue'
import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)
/**
 * @param { 表格columns } tbCols
 */
function initDrag(tbCols) {
  const draggingMap = {}
  tbCols.forEach((col) => {
    const key = col.dataIndex || col.key//这儿要求表格数据中要有这两个属性
    draggingMap[key] = col.width || 0
  })
  const draggingState = Vue.observable(draggingMap)
  return (h, props, children) => {
    let thDom = null
    const { key, ...restProps } = props
    let col
    if (key === 'selection-column') {
      //表格加了复选框，不加这个判断col会是undefided
      col = {}
    } else {
      col = tbCols.find((item) => {
        const k = item.dataIndex || item.key
        return k === key
      })
    }
    if (!col.width) {//这儿要求表格数据中要有宽width属性，若是没有是不会执行下面的拖拽的
      return <th {...restProps}>{children}</th>
    }

    const onDrag = (x) => {
      draggingState[key] = 0
      col.width = Math.max(x, 1)
    }
    const onDragstop = () => {
      draggingState[key] = thDom.getBoundingClientRect().width
    }

    return (
      <th
        {...restProps}
        v-ant-ref={(r) => {
          thDom = r
        }}
        width={draggingState[key]}
        class="resize-table-th"
      >
        {children}
        <vue-draggable-resizable
          key={col.dataIndex || col.key}
          class="table-draggable-handle"
          w={10}
          x={col.width || draggingState[key]}
          z={1}
          axis="x"
          draggable={true}
          resizable={false}
          onDragging={onDrag}
          onDragstop={onDragstop}
        ></vue-draggable-resizable>
      </th>
    )
  }
}
export default {
  methods: {
    /**
     * https://github.com/mauricius/vue-draggable-resizable
     * 表格列可拖拽
     * 表格上使用：:components="drag(columns)"
     * tips:columns中需包含dataIndex或者key和width(Number)
     */
    drag(columns) {
      return {
        header: {
          cell: initDrag(columns),
        },
      }
    },
  },
}
