<template>
  <div class="n-th-resize inherit" v-mouse="onMouseEvent">
    <div class="n-th-resize-bar inherit"></div>
  </div>
</template>

<script>
import mouse from '@uif/next/lib/directives/mouse'
import {addBodyClass, removeBodyClass, isNumber} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-table-th-resize',
  directives: {
    mouse
  },
  props: {
    column: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
    }
  },
  methods: {
    // 排序事件
    onMouseEvent (time, event) {
      switch (time) {
        case 'start':
          addBodyClass('e-resize')
          this.$emit('on-resize-start')
          this.initWidth()
          this.event = event
          break
        case 'move':
          this.changeWidth(event)
          break
        case 'end':
          this.event = null
          removeBodyClass('e-resize')
          this.$emit('on-resize-end')
          break
      }
    },
    // 获取宽度
    initWidth () {
      this.width = isNumber(this.column.width) ? this.column.width : this.$el.parentElement.getBoundingClientRect().width
    },
    // 设置宽度
    changeWidth (event) {
      const width = this.width + event.clientX - this.event.clientX
      this.$set(this.column, 'width', Math.max(40, width))
    }
  }
}
</script>
