/**
 * tdesign v0.46.4
 * (c) 2022 tdesign
 * @license MIT
 */

import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { toRefs, ref, computed, watch, h } from '@vue/composition-api';
import Sortable from 'sortablejs';
import get from 'lodash/get';
import isFunction from 'lodash/isFunction';
import { hasClass } from '../../utils/dom.js';
import useClassName from './useClassName.js';
import '../../_common/js/log/index.js';
import swapDragArrayElement from '../../_common/js/utils/swapDragArrayElement.js';
import { getColumnDataByKey, getColumnIndexByKey } from '../utils.js';
import log from '../../_common/js/log/log.js';
import 'vue';
import 'raf';
import 'lodash/isString';
import '../../utils/easing.js';
import '../../config-provider/useConfig.js';
import '../../config-provider/context.js';
import 'lodash/merge';
import 'lodash/mergeWith';
import '../../_common/js/global-config/default-config.js';
import '../../_common/js/global-config/locale/zh_CN.js';
import '../../config-provider/type.js';
import '@babel/runtime/helpers/typeof';
import 'lodash/isObject';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function useDragSort(props, context) {
  var _toRefs = toRefs(props),
      sortOnRowDraggable = _toRefs.sortOnRowDraggable,
      dragSort = _toRefs.dragSort,
      data = _toRefs.data;

  var _useClassName = useClassName(),
      tableDraggableClasses = _useClassName.tableDraggableClasses,
      tableBaseClass = _useClassName.tableBaseClass,
      tableFullRowClasses = _useClassName.tableFullRowClasses;

  var columns = ref(props.columns || []);
  var primaryTableRef = ref(null);
  var dragCol = computed(function () {
    var _columns$value;

    return (_columns$value = columns.value) === null || _columns$value === void 0 ? void 0 : _columns$value.find(function (item) {
      return item.colKey === "drag";
    });
  });
  var isRowDraggable = computed(function () {
    return sortOnRowDraggable.value || dragSort.value === "row";
  });
  var isRowHandlerDraggable = computed(function () {
    return ["drag-col", "row-handler", "row-handler-col"].includes(dragSort.value) && !!dragCol.value;
  });
  var isColDraggable = computed(function () {
    return ["col", "row-handler-col"].includes(dragSort.value);
  });
  var lastRowList = ref([]);
  var lastColList = ref([]);

  if (dragSort.value === "drag-col") {
    log.error("Table", "dragSort='drag-col' is going to be deprecated, please use dragSort='col' instead.");
  }

  if (props.sortOnRowDraggable) {
    log.error("Table", "`sortOnRowDraggable` is going to be deprecated, please use dragSort='row' instead.");
  }

  watch(data, function (data2) {
    lastRowList.value = data2 === null || data2 === void 0 ? void 0 : data2.map(function (item) {
      return get(item, props.rowKey);
    });
  }, {
    immediate: true
  });
  watch(columns, function (columns2) {
    lastColList.value = columns2 ? columns2.map(function (t) {
      return t.colKey;
    }) : [];
  }, {
    immediate: true
  });

  var registerRowDragEvent = function registerRowDragEvent(element) {
    if (!isRowHandlerDraggable.value && !isRowDraggable.value) return;
    var dragContainer = element === null || element === void 0 ? void 0 : element.querySelector("tbody");

    if (!dragContainer) {
      console.error("tbody does not exist.");
      return null;
    }

    var dragInstanceTmp = null;

    var baseOptions = _objectSpread(_objectSpread({
      animation: 150
    }, props.dragSortOptions), {}, {
      ghostClass: tableDraggableClasses.ghost,
      chosenClass: tableDraggableClasses.chosen,
      dragClass: tableDraggableClasses.dragging,
      filter: ".".concat(tableFullRowClasses.base),
      onMove: function onMove(evt) {
        return !hasClass(evt.related, tableFullRowClasses.base);
      },
      onEnd: function onEnd(evt) {
        var _dragInstanceTmp, _props$onDragSort;

        (_dragInstanceTmp = dragInstanceTmp) === null || _dragInstanceTmp === void 0 ? void 0 : _dragInstanceTmp.sort(lastRowList.value);
        var currentIndex = evt.oldIndex,
            targetIndex = evt.newIndex;

        if (isFunction(props.firstFullRow) && props.firstFullRow(h) || context.slots.firstFullRow) {
          currentIndex -= 1;
          targetIndex -= 1;
        }

        var params = {
          data: data.value,
          currentIndex: currentIndex,
          current: data.value[currentIndex],
          targetIndex: targetIndex,
          target: data.value[targetIndex],
          newData: swapDragArrayElement(_toConsumableArray(props.data), currentIndex, targetIndex),
          e: evt,
          sort: "row"
        };
        params.currentData = params.newData;
        (_props$onDragSort = props.onDragSort) === null || _props$onDragSort === void 0 ? void 0 : _props$onDragSort.call(props, params);
        context.emit("drag-sort", params);
      }
    });

    if (isRowDraggable.value) {
      dragInstanceTmp = new Sortable(dragContainer, _objectSpread({}, baseOptions));
    } else {
      dragInstanceTmp = new Sortable(dragContainer, _objectSpread(_objectSpread({}, baseOptions), {}, {
        handle: ".".concat(tableDraggableClasses.handle)
      }));
    }

    lastRowList.value = dragInstanceTmp.toArray();
  };

  var registerOneLevelColDragEvent = function registerOneLevelColDragEvent(container, recover) {
    var dragInstanceTmp = null;

    var options = _objectSpread(_objectSpread({
      animation: 150
    }, props.dragSortOptions), {}, {
      dataIdAttr: "data-colkey",
      direction: "vertical",
      ghostClass: tableDraggableClasses.ghost,
      chosenClass: tableDraggableClasses.chosen,
      dragClass: tableDraggableClasses.dragging,
      handle: ".".concat(tableBaseClass.thCellInner),
      onEnd: function onEnd(evt) {
        var _props$onDragSort2;

        if (recover) {
          var _dragInstanceTmp2;

          (_dragInstanceTmp2 = dragInstanceTmp) === null || _dragInstanceTmp2 === void 0 ? void 0 : _dragInstanceTmp2.sort(_toConsumableArray(lastColList.value));
        }

        var oldIndex = evt.oldIndex,
            newIndex = evt.newIndex,
            targetElement = evt.target;
        var currentIndex = recover ? oldIndex : newIndex;
        var targetIndex = recover ? newIndex : oldIndex;
        var oldElement = targetElement.children[currentIndex];
        var newElement = targetElement.children[targetIndex];
        var current = getColumnDataByKey(columns.value, oldElement.dataset.colkey);
        var target = getColumnDataByKey(columns.value, newElement.dataset.colkey);

        if (!current || !current.colKey) {
          log.error("Table", "colKey is missing in ".concat(JSON.stringify(current)));
        }

        if (!target || !target.colKey) {
          log.error("Table", "colKey is missing in ".concat(JSON.stringify(target)));
        }

        currentIndex = getColumnIndexByKey(props.columns, current.colKey);
        targetIndex = getColumnIndexByKey(props.columns, target.colKey);
        var params = {
          data: columns.value,
          currentIndex: currentIndex,
          current: current,
          targetIndex: targetIndex,
          target: target,
          newData: swapDragArrayElement(_toConsumableArray(props.columns), currentIndex, targetIndex),
          e: evt,
          sort: "col"
        };
        params.currentData = params.newData;
        (_props$onDragSort2 = props.onDragSort) === null || _props$onDragSort2 === void 0 ? void 0 : _props$onDragSort2.call(props, params);
        context.emit("drag-sort", params);
      }
    });

    dragInstanceTmp = new Sortable(container, options);
    return dragInstanceTmp;
  };

  var registerColDragEvent = function registerColDragEvent(tableElement) {
    if (!isColDraggable.value || !tableElement) return;
    var trList = tableElement.querySelectorAll("thead > tr");

    if (trList.length <= 1) {
      var _trList = _slicedToArray(trList, 1),
          container = _trList[0];

      var dragInstanceTmp = registerOneLevelColDragEvent(container, true);
      lastColList.value = dragInstanceTmp === null || dragInstanceTmp === void 0 ? void 0 : dragInstanceTmp.toArray();
    } else {
      trList.forEach(function (container) {
        registerOneLevelColDragEvent(container, false);
      });
    }
  };

  function setDragSortPrimaryTableRef(primaryTableElement) {
    primaryTableRef.value = primaryTableElement;
  }

  function setDragSortColumns(val) {
    columns.value = val;
  }

  watch([primaryTableRef], function (_ref) {
    var _ref2 = _slicedToArray(_ref, 1),
        val = _ref2[0];

    if (!val || !val.$el) return;
    registerRowDragEvent(val.$el);
    registerColDragEvent(val.$el);
    var timer = setTimeout(function () {
      if (val.$refs.affixHeaderRef) {
        registerColDragEvent(val.$refs.affixHeaderRef);
      }

      clearTimeout(timer);
    });
  });
  return {
    isRowDraggable: isRowDraggable,
    isRowHandlerDraggable: isRowHandlerDraggable,
    isColDraggable: isColDraggable,
    setDragSortPrimaryTableRef: setDragSortPrimaryTableRef,
    setDragSortColumns: setDragSortColumns
  };
}

export { useDragSort as default };
//# sourceMappingURL=useDragSort.js.map
