<template>
  <th v-bind="$attrs" :class="$style.headerCell" v-on="$listeners">
    <slot></slot>
    <!-- 避免拖拽时触发整个单元格的click -->
    <div @click.stop>
      <VueDraggableResizable
        :w="10"
        :z="1"
        :x="x"
        h="auto"
        axis="x"
        :draggable="true"
        :resizable="false"
        :class-name="$style.handle"
        :on-drag-start="onDragStart"
        :on-drag="onDrag"
        @dragstop="onDragstop"
      />
    </div>
  </th>
</template>

<script>
import VueDraggableResizable from 'vue-draggable-resizable'

export default {
  name: 'SdResizableTh',
  components: {
    VueDraggableResizable,
  },
  props: {
    width: {
      type: Number,
      default: 0,
    },
    last: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      x: 0,
    }
  },
  watch: {
    // 传入的width变化时，更新当前x轴坐标
    width: function(width) {
      this.x = width
      if (width === 0) this.updateByDomWidth()
    },
  },

  mounted() {
    // 传入的width可能是百分比格式，按实际宽度触发更新
    this.updateByDomWidth()
  },

  methods: {
    // 按实际DOM渲染的宽度，触发更新
    updateByDomWidth() {
      // 需要等待数据反映到DOM结构上
      this.$nextTick(function() {
        this.x = this.$el.clientWidth - 1 // clientWidth是取整和实际的不一样，这里减一个像素防止表格多出滚动条
        this.$emit('resize', this.x)
      })
    },
    onDragStart() {
      this.$emit('resizeStart')
    },
    onDrag(x) {
      this.x = x
    },
    onDragstop() {
      // 先提交当前拖拽的宽度
      this.$emit('resize', this.x)
      // 再按实际宽度触发更新，因为上一步提交的宽度可能与实际渲染出来的不一样
      this.updateByDomWidth()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$icon-width: 28px;
.header-cell {
  position: relative;
  overflow: visible;
  .handle {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    // 向左移动 自身的一半
    margin-left: -5px;
    cursor: col-resize;
    background-clip: content-box;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
    &:global(.dragging),
    &:hover {
      background-color: $text-color-secondary;
    }
  }
  // 复选框列和最后一列 不显示拖拽条
  &:global(.ant-table-selection-column),
  &:global(.ant-table-row-cell-last) {
    .handle {
      display: none;
    }
  }
}
// 最后一列的过滤图标，向左移动让开选择列的图标
:global .ant-table-thead > tr > th.ant-table-row-cell-last {
  &:local(.header-cell) {
    .anticon-filter,
    .ant-table-filter-icon {
      right: $icon-width;
    }
  }
}
</style>
