/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var VueCompositionAPI = require('@vue/composition-api');
var Sortable = require('sortablejs');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var log = require('../../../chunks/log.js');
var utils_dom = require('../../../utils/dom.js');
var components_table_utils = require('../utils.js');
var components_table_hooks_useClassName = require('./useClassName.js');
require('../../../chunks/_commonjsHelpers-2e6815bd.js');
require('vue');
require('raf');
require('lodash/isString');
require('../../../utils/easing.js');
require('lodash/isObject');
require('../../config-provider/useConfig.js');
require('../../config-provider/context.js');
require('lodash');
require('../../../chunks/zh_CN.js');

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

var Sortable__default = /*#__PURE__*/_interopDefaultLegacy(Sortable);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

function swapDragArrayElement(data, currentIndex, targetIndex) {
  var newData = [...data];
  if (targetIndex - currentIndex > 0) {
    newData.splice(targetIndex + 1, 0, newData[currentIndex]);
    newData.splice(currentIndex, 1);
  } else {
    newData.splice(targetIndex, 0, newData[currentIndex]);
    newData.splice(currentIndex + 1, 1);
  }
  return newData;
}

function useDragSort(props, context) {
  const {
    sortOnRowDraggable,
    dragSort,
    data
  } = VueCompositionAPI.toRefs(props);
  const {
    tableDraggableClasses,
    tableBaseClass,
    tableFullRowClasses
  } = components_table_hooks_useClassName["default"]();
  const columns = VueCompositionAPI.ref(props.columns || []);
  const primaryTableRef = VueCompositionAPI.ref(null);
  const dragCol = VueCompositionAPI.computed(() => {
    var _columns$value;
    return (_columns$value = columns.value) === null || _columns$value === void 0 ? void 0 : _columns$value.find(item => item.colKey === "drag");
  });
  const isRowDraggable = VueCompositionAPI.computed(() => sortOnRowDraggable.value || dragSort.value === "row");
  const isRowHandlerDraggable = VueCompositionAPI.computed(() => ["drag-col", "row-handler", "row-handler-col"].includes(dragSort.value) && !!dragCol.value);
  const isColDraggable = VueCompositionAPI.computed(() => ["col", "row-handler-col"].includes(dragSort.value));
  const lastRowList = VueCompositionAPI.ref([]);
  const lastColList = VueCompositionAPI.ref([]);
  if (dragSort.value === "drag-col") log.log.error("Table", "dragSort='drag-col' is going to be deprecated, please use dragSort='col' instead.");
  if (props.sortOnRowDraggable) log.log.error("Table", "`sortOnRowDraggable` is going to be deprecated, please use dragSort='row' instead.");
  VueCompositionAPI.watch(data, data2 => {
    lastRowList.value = data2 === null || data2 === void 0 ? void 0 : data2.map(item => get__default["default"](item, props.rowKey));
  }, {
    immediate: true
  });
  VueCompositionAPI.watch(columns, columns2 => {
    lastColList.value = columns2 ? columns2.map(t => t.colKey) : [];
  }, {
    immediate: true
  });
  function getDataPageIndex(index) {
    const {
      pagination
    } = props;
    if (!props.disableDataPage && pagination && data.value.length > pagination.pageSize) return pagination.pageSize * (pagination.current - 1) + index;
    return index;
  }
  const registerRowDragEvent = element => {
    if (!isRowHandlerDraggable.value && !isRowDraggable.value) return;
    const dragContainer = element === null || element === void 0 ? void 0 : element.querySelector("tbody");
    if (!dragContainer) {
      console.error("tbody does not exist.");
      return null;
    }
    let dragInstanceTmp = null;
    const baseOptions = {
      animation: 150,
      ghostClass: tableDraggableClasses.ghost,
      chosenClass: tableDraggableClasses.chosen,
      dragClass: tableDraggableClasses.dragging,
      filter: `.${tableFullRowClasses.base}`,
      onMove: evt => !utils_dom.hasClass(evt.related, tableFullRowClasses.base),
      onEnd(evt) {
        var _dragInstanceTmp, _props$onDragSort;
        (_dragInstanceTmp = dragInstanceTmp) === null || _dragInstanceTmp === void 0 ? void 0 : _dragInstanceTmp.sort(lastRowList.value);
        let {
          oldIndex: currentIndex,
          newIndex: targetIndex
        } = evt;
        if (isFunction__default["default"](props.firstFullRow) && props.firstFullRow(VueCompositionAPI.h) || context.slots.firstFullRow) {
          currentIndex -= 1;
          targetIndex -= 1;
        }
        const params = {
          data: data.value,
          currentIndex,
          current: data.value[currentIndex],
          targetIndex,
          target: data.value[targetIndex],
          newData: swapDragArrayElement([...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);
        context.emit("drag-sort", params);
      },
      ...props.dragSortOptions
    };
    if (!dragContainer) return;
    if (isRowDraggable.value) {
      dragInstanceTmp = new Sortable__default["default"](dragContainer, {
        ...baseOptions
      });
    } else {
      dragInstanceTmp = new Sortable__default["default"](dragContainer, {
        ...baseOptions,
        handle: `.${tableDraggableClasses.handle}`
      });
    }
    lastRowList.value = dragInstanceTmp.toArray();
  };
  const registerOneLevelColDragEvent = (container, recover) => {
    let dragInstanceTmp = null;
    const options = {
      animation: 150,
      ...props.dragSortOptions,
      dataIdAttr: "data-colkey",
      direction: "vertical",
      ghostClass: tableDraggableClasses.ghost,
      chosenClass: tableDraggableClasses.chosen,
      dragClass: tableDraggableClasses.dragging,
      handle: `.${tableBaseClass.thCellInner}`,
      onEnd: evt => {
        var _props$onDragSort2;
        if (recover) {
          var _dragInstanceTmp2;
          (_dragInstanceTmp2 = dragInstanceTmp) === null || _dragInstanceTmp2 === void 0 ? void 0 : _dragInstanceTmp2.sort([...lastColList.value]);
        }
        const {
          oldIndex,
          newIndex,
          target: targetElement
        } = evt;
        let currentIndex = recover ? oldIndex : newIndex;
        let targetIndex = recover ? newIndex : oldIndex;
        const oldElement = targetElement.children[currentIndex];
        const newElement = targetElement.children[targetIndex];
        const current = components_table_utils.getColumnDataByKey(columns.value, oldElement.dataset.colkey);
        const target = components_table_utils.getColumnDataByKey(columns.value, newElement.dataset.colkey);
        if (!current || !current.colKey) log.log.error("Table", `colKey is missing in ${JSON.stringify(current)}`);
        if (!target || !target.colKey) log.log.error("Table", `colKey is missing in ${JSON.stringify(target)}`);
        currentIndex = components_table_utils.getColumnIndexByKey(props.columns, current.colKey);
        targetIndex = components_table_utils.getColumnIndexByKey(props.columns, target.colKey);
        const params = {
          data: columns.value,
          currentIndex,
          current,
          targetIndex,
          target,
          newData: swapDragArrayElement([...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);
      }
    };
    if (!container) return;
    dragInstanceTmp = new Sortable__default["default"](container, options);
    return dragInstanceTmp;
  };
  const registerColDragEvent = tableElement => {
    if (!isColDraggable.value || !tableElement) return;
    const trList = tableElement.querySelectorAll("thead > tr");
    if (trList.length <= 1) {
      const [container] = trList;
      const dragInstanceTmp = registerOneLevelColDragEvent(container, true);
      lastColList.value = dragInstanceTmp === null || dragInstanceTmp === void 0 ? void 0 : dragInstanceTmp.toArray();
    } else {
      trList.forEach(container => {
        registerOneLevelColDragEvent(container, false);
      });
    }
  };
  function setDragSortPrimaryTableRef(primaryTableElement) {
    primaryTableRef.value = primaryTableElement;
  }
  function setDragSortColumns(val) {
    columns.value = val;
  }
  VueCompositionAPI.watch([primaryTableRef], _ref => {
    let [val] = _ref;
    if (!val || !val.$el) return;
    registerRowDragEvent(val.$el);
    registerColDragEvent(val.$el);
    const timer = setTimeout(() => {
      if (val.$refs.affixHeaderRef) registerColDragEvent(val.$refs.affixHeaderRef);
      clearTimeout(timer);
    });
  });
  return {
    isRowDraggable,
    isRowHandlerDraggable,
    isColDraggable,
    setDragSortPrimaryTableRef,
    setDragSortColumns
  };
}

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