<template>
  <div
    ref="target"
    v-drag:target="dragConfig"
    :class="dragBarClasses"
    class="mm-thead-dragbar"></div>
</template>
<script>
import defaultTo from "lodash/defaultTo"
import drag from "../../directives/drag"
import { setCacheWidthData } from "./utils"

export default {
  directives: { drag },
  props: {
    column: {
      type: Object,
    },
  },
  inject: {
    rootTable: {
      from: "mm-table",
      default: null,
    },
  },
  computed: {
    dragConfig() {
      return {
        draggable: this.rootTable.columnDraggable,
        dragstart: this.dragstartHandler,
        drag: this.dragHandler,
        dragend: this.dragendHandler,
      }
    },

    dragBarClasses() {
      return {
        "mm-thead-dragbar--disabled": !this.draggable,
        "mm-thead-dragbar__next": true,
      }
    },

    draggable() {
      return (
        this.rootTable.columnDraggable !== false &&
        this.column.draggable !== false
      )
    },
  },
  methods: {
    dragstartHandler() {
      this.width = this.column.width
    },
    dragHandler({ distanceX }) {
      if (!this.draggable) {
        return
      }
      const MIN_DRAG_WIDTH = this.rootTable.minDragWidth

      const minDragWidth = defaultTo(this.column.minDragWidth, MIN_DRAG_WIDTH)
      const width = this.width + distanceX
      const canDrag = width > minDragWidth

      if (canDrag) {
        this.setColumnWidth(this.column, width)
      }
    },
    dragendHandler() {
      const data = {
        width: this.column.width,
        column: this.column,
        oldWidth: this.width,
      }
      setCacheWidthData(this.rootTable.cacheWidthKey, this.column.key, this.column.width)
      this.rootTable.$emit("column-width-dragend", data, this.rootTable.store.state.columns)
    },

    setColumnWidth(column, width) {
      column.width = width
      column.flex = false
    },
  },
}
</script>
