import sortable from "sortablejs";
import clonedeep from "lodash.clonedeep";

const tableDrag = {
  bind(el, binding) {
    // 这里是定义了一个对象只接收value和arg
    const { value, arg } = binding;
    // 如果没有获取到元素节点
    if (!el) {
      return;
    }
    // 定义对象,如果没有的话为空
    const { elementSeletor, onEnd, ...config } = arg || {};
    // 三元表达式判断元素节点是否为空,不为空则选择到el中指定的节点
    const bindEls = elementSeletor ? el.querySelector(elementSeletor) : el;
    // 创建
    el.sortable = sortable.create(bindEls, {
      animation: 150,//动画时长设置  ms
      ghostClass: "blue-background-class",
      ...config,
      handle: ".handle",
      onEnd: (evt) => {
        let cloneValue = null;
        if (Array.isArray(value)) {
          const { oldIndex, newIndex } = evt;
          cloneValue = clonedeep(value);
          value.splice(newIndex, 0, ...value.splice(oldIndex, 1));
        }

        onEnd && onEnd(evt, cloneValue, value);
      },
      onMove(e) {
        return e.related.className.indexOf("filtered") === -1;
      }
    });
    el.tableData = value;
  },

  update(el, { value }) {
    el.tableData = value;
  },

  unbind: function (el) {
    el.sortable.destroy();
    el.sortable = null;
  }
};

export default tableDrag;
