/**
 * ldesign v0.4.2
 * (c) 2023 ldesign
 * @license MIT
 */

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

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,
    rowKey = _toRefs.rowKey;
  var _useClassName = useClassName(),
    tableDraggableClasses = _useClassName.tableDraggableClasses,
    tableBaseClass = _useClassName.tableBaseClass,
    tableFullRowClasses = _useClassName.tableFullRowClasses;
  var primaryTableRef = ref(null);
  var columns = ref(props.columns || []);
  var dragCol = computed(function () {
    return columns.value.find(function (item) {
      return item.colKey === "drag";
    });
  });
  var isRowDraggable = computed(function () {
    return sortOnRowDraggable.value || dragSort.value === "row";
  });
  var isRowHandlerDraggable = computed(function () {
    return ["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([]);
  var dragRowInstanceTmp = null;
  var dragColInstanceTmp = null;
  if (props.sortOnRowDraggable) log.error("Table", "`sortOnRowDraggable` is going to be deprecated, use dragSort='row' instead.");
  watch([data], function (_ref) {
    var _ref2 = _slicedToArray(_ref, 1),
      data2 = _ref2[0];
    lastRowList.value = (data2 === null || data2 === void 0 ? void 0 : data2.map(function (item) {
      return get(item, rowKey.value);
    })) || [];
    var timer = setTimeout(function () {
      if (data2.length) {
        var _dragRowInstanceTmp;
        (_dragRowInstanceTmp = dragRowInstanceTmp) === null || _dragRowInstanceTmp === void 0 ? void 0 : _dragRowInstanceTmp.sort(lastRowList.value);
      } else {
        var _primaryTableRef$valu;
        var trList = (_primaryTableRef$valu = primaryTableRef.value) === null || _primaryTableRef$valu === void 0 ? void 0 : _primaryTableRef$valu.$el.querySelectorAll("tr[data-id]");
        trList === null || trList === void 0 ? void 0 : trList.forEach(function (node) {
          return node.remove();
        });
      }
      clearTimeout(timer);
    }, 0);
  }, {
    immediate: true
  });
  watch(columns, function (columns2) {
    lastColList.value = columns2 ? columns2.map(function (t) {
      return t.colKey;
    }) : [];
    var timer = setTimeout(function () {
      var _dragColInstanceTmp;
      if (!dragColInstanceTmp || !dragColInstanceTmp.el) return;
      (_dragColInstanceTmp = dragColInstanceTmp) === null || _dragColInstanceTmp === void 0 ? void 0 : _dragColInstanceTmp.sort(lastColList.value);
      clearTimeout(timer);
    }, 0);
  });
  function getDataPageIndex(index) {
    var pagination = props.pagination;
    if (!props.disableDataPage && pagination && data.value.length > pagination.pageSize) return pagination.pageSize * (pagination.current - 1) + index;
    return index;
  }
  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 baseOptions = _objectSpread({
      animation: 150,
      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 _dragRowInstanceTmp2, _props$onDragSort;
        if (evt.newIndex === evt.oldIndex) return;
        (_dragRowInstanceTmp2 = dragRowInstanceTmp) === null || _dragRowInstanceTmp2 === void 0 ? void 0 : _dragRowInstanceTmp2.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), getDataPageIndex(currentIndex), getDataPageIndex(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);
      }
    }, props.dragSortOptions);
    if (!dragContainer) return;
    if (isRowDraggable.value) {
      dragRowInstanceTmp = new Sortable(dragContainer, _objectSpread({}, baseOptions));
    } else {
      dragRowInstanceTmp = new Sortable(dragContainer, _objectSpread(_objectSpread({}, baseOptions), {}, {
        handle: ".".concat(tableDraggableClasses.handle)
      }));
    }
    lastRowList.value = dragRowInstanceTmp.toArray();
  };
  var registerOneLevelColDragEvent = function registerOneLevelColDragEvent(container, recover) {
    var options = _objectSpread({
      animation: 150,
      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 (evt.newIndex === evt.oldIndex) return;
        if (recover) {
          var _dragColInstanceTmp2;
          (_dragColInstanceTmp2 = dragColInstanceTmp) === null || _dragColInstanceTmp2 === void 0 ? void 0 : _dragColInstanceTmp2.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);
      }
    }, props.dragSortOptions);
    if (!container) return;
    dragColInstanceTmp = new Sortable(container, options);
    return dragColInstanceTmp;
  };
  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 === null || trList === void 0 ? void 0 : trList.forEach(function (container) {
        registerOneLevelColDragEvent(container, false);
      });
    }
  };
  function setDragSortPrimaryTableRef(primaryTableElement) {
    primaryTableRef.value = primaryTableElement;
  }
  function setDragSortColumns(val) {
    columns.value = val;
  }
  watch([primaryTableRef], function (_ref3) {
    var _ref4 = _slicedToArray(_ref3, 1),
      val = _ref4[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
