import Sortable from "sortablejs";

let VelTableSort = {
  bind(el, binding, vnode, oldnode) {
    const tbody = el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];

    const orderKey = binding.arg;

    Sortable.create(tbody, {
      ghostClass: "sortable-ghost",
      chosenClass: "sortable-chosen",
      animation: 150,
      setData: function(dataTransfer) {
        dataTransfer.setData("Text", "");
      },
      onEnd({ newIndex, oldIndex }) {
        const data = vnode.componentInstance.data;
        const targetRow = data.splice(oldIndex, 1)[0];
        data.splice(newIndex, 0, targetRow);
        data.forEach((item, idx) => (item[orderKey] = idx + 1));
      }
    });
  }
};

export default VelTableSort;
