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

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var vue = require('vue');
var Sortable = require('sortablejs');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var _common_js_log_log = require('../../_common/js/log/log.js');
var utils_dom = require('../../utils/dom.js');
var _common_js_utils_swapDragArrayElement = require('../../_common/js/utils/swapDragArrayElement.js');
var table_utils = require('../utils.js');
var table_hooks_useClassName = require('./useClassName.js');
require('../../_chunks/dep-7f0559c3.js');
require('lodash/isString');
require('lodash/isArray');
require('../../utils/easing.js');
require('@babel/runtime/helpers/typeof');
require('lodash/isObject');
require('../../hooks/useConfig.js');
require('../../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('../../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('dayjs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var Sortable__default = /*#__PURE__*/_interopDefaultLegacy(Sortable);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

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__default["default"](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 = vue.toRefs(props),
    sortOnRowDraggable = _toRefs.sortOnRowDraggable,
    dragSort = _toRefs.dragSort,
    data = _toRefs.data,
    rowKey = _toRefs.rowKey;
  var _useClassName = table_hooks_useClassName["default"](),
    tableDraggableClasses = _useClassName.tableDraggableClasses,
    tableBaseClass = _useClassName.tableBaseClass,
    tableFullRowClasses = _useClassName.tableFullRowClasses;
  var primaryTableRef = vue.ref(null);
  var columns = vue.ref(props.columns || []);
  var dragCol = vue.computed(function () {
    return columns.value.find(function (item) {
      return item.colKey === "drag";
    });
  });
  var isRowDraggable = vue.computed(function () {
    return sortOnRowDraggable.value || dragSort.value === "row";
  });
  var isRowHandlerDraggable = vue.computed(function () {
    return ["row-handler", "row-handler-col"].includes(dragSort.value) && !!dragCol.value;
  });
  var isColDraggable = vue.computed(function () {
    return ["col", "row-handler-col"].includes(dragSort.value);
  });
  var lastRowList = vue.ref([]);
  var lastColList = vue.ref([]);
  var dragRowInstanceTmp = null;
  var dragColInstanceTmp = null;
  if (props.sortOnRowDraggable) _common_js_log_log["default"].error("Table", "`sortOnRowDraggable` is going to be deprecated, use dragSort='row' instead.");
  vue.watch([data], function (_ref) {
    var _ref2 = _slicedToArray__default["default"](_ref, 1),
      data2 = _ref2[0];
    lastRowList.value = (data2 === null || data2 === void 0 ? void 0 : data2.map(function (item) {
      return get__default["default"](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
  });
  vue.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 !utils_dom.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__default["default"](props.firstFullRow) && props.firstFullRow(vue.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: _common_js_utils_swapDragArrayElement["default"](_toConsumableArray__default["default"](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__default["default"](dragContainer, _objectSpread({}, baseOptions));
    } else {
      dragRowInstanceTmp = new Sortable__default["default"](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__default["default"](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 = table_utils.getColumnDataByKey(columns.value, oldElement.dataset.colkey);
        var target = table_utils.getColumnDataByKey(columns.value, newElement.dataset.colkey);
        if (!current || !current.colKey) _common_js_log_log["default"].error("Table", "colKey is missing in ".concat(JSON.stringify(current)));
        if (!target || !target.colKey) _common_js_log_log["default"].error("Table", "colKey is missing in ".concat(JSON.stringify(target)));
        currentIndex = table_utils.getColumnIndexByKey(props.columns, current.colKey);
        targetIndex = table_utils.getColumnIndexByKey(props.columns, target.colKey);
        var params = {
          data: columns.value,
          currentIndex: currentIndex,
          current: current,
          targetIndex: targetIndex,
          target: target,
          newData: _common_js_utils_swapDragArrayElement["default"](_toConsumableArray__default["default"](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__default["default"](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__default["default"](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;
  }
  vue.watch([primaryTableRef], function (_ref3) {
    var _ref4 = _slicedToArray__default["default"](_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
  };
}

exports["default"] = useDragSort;
//# sourceMappingURL=useDragSort.js.map
