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

'use strict';

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

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var VueCompositionAPI = require('@vue/composition-api');
var Sortable = require('sortablejs');
var get = require('lodash/get');
var table_hooks_useClassName = require('./useClassName.js');
var _common_js_log_log = require('../../_common/js/log/log.js');
var _common_js_utils_swapDragArrayElement = require('../../_common/js/utils/swapDragArrayElement.js');
require('../../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('lodash/mergeWith');
require('../../config-provider/context.js');
require('lodash/merge');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');

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

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

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 = VueCompositionAPI.toRefs(props),
      sortOnRowDraggable = _toRefs.sortOnRowDraggable,
      dragSort = _toRefs.dragSort,
      columns = _toRefs.columns,
      data = _toRefs.data;

  var _useClassName = table_hooks_useClassName["default"](),
      tableDraggableClasses = _useClassName.tableDraggableClasses,
      tableBaseClass = _useClassName.tableBaseClass;

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

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

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

  VueCompositionAPI.watch(data, function (data2) {
    lastRowList.value = data2 === null || data2 === void 0 ? void 0 : data2.map(function (item) {
      return get__default["default"](item, props.rowKey);
    });
  }, {
    immediate: true
  });
  VueCompositionAPI.watch(columns, function (columns2) {
    lastColList.value = columns2 || [];
  }, {
    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,
      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;
        var params = {
          currentIndex: currentIndex,
          current: data.value[currentIndex],
          targetIndex: targetIndex,
          target: data.value[targetIndex],
          currentData: _common_js_utils_swapDragArrayElement["default"](props.data, currentIndex, targetIndex),
          e: evt,
          sort: "row"
        };
        (_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__default["default"](dragContainer, _objectSpread({}, baseOptions));
    } else {
      dragInstanceTmp = new Sortable__default["default"](dragContainer, _objectSpread(_objectSpread({}, baseOptions), {}, {
        handle: ".".concat(tableDraggableClasses.handle)
      }));
    }

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

  var registerColDragEvent = function registerColDragEvent(tableElement) {
    var _dragInstanceTmp3;

    if (!isColDraggable.value || !tableElement) return;
    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 _dragInstanceTmp2, _props$onDragSort2;

        (_dragInstanceTmp2 = dragInstanceTmp) === null || _dragInstanceTmp2 === void 0 ? void 0 : _dragInstanceTmp2.sort(_toConsumableArray__default["default"](lastColList.value));
        var currentIndex = evt.oldIndex,
            targetIndex = evt.newIndex;
        var params = {
          currentIndex: currentIndex,
          current: columns.value[currentIndex],
          targetIndex: targetIndex,
          target: columns.value[targetIndex],
          currentData: _common_js_utils_swapDragArrayElement["default"](columns.value, currentIndex, targetIndex),
          e: evt,
          sort: "col"
        };
        (_props$onDragSort2 = props.onDragSort) === null || _props$onDragSort2 === void 0 ? void 0 : _props$onDragSort2.call(props, params);
        context.emit("drag-sort", params);
      }
    });

    var container = tableElement.querySelector("thead > tr");
    dragInstanceTmp = new Sortable__default["default"](container, options);
    lastColList.value = (_dragInstanceTmp3 = dragInstanceTmp) === null || _dragInstanceTmp3 === void 0 ? void 0 : _dragInstanceTmp3.toArray();
  };

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

  VueCompositionAPI.watch([primaryTableRef], function (_ref) {
    var _ref2 = _slicedToArray__default["default"](_ref, 1),
        val = _ref2[0];

    (val === null || val === void 0 ? void 0 : val.$el) && registerRowDragEvent(val === null || val === void 0 ? void 0 : val.$el);
    (val === null || val === void 0 ? void 0 : val.$el) && registerColDragEvent(val === null || val === void 0 ? void 0 : val.$el);
  });
  return {
    isRowDraggable: isRowDraggable,
    isRowHandlerDraggable: isRowHandlerDraggable,
    isColDraggable: isColDraggable,
    setDragSortPrimaryTableRef: setDragSortPrimaryTableRef
  };
}

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