/**
 * ldesign v0.2.22
 * (c) 2022/12/7 16:21 built by swimly
 * @license MIT
 */

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 { l as log } from '../../../_chunks/dep-eaa95999.js';
import { hasClass } from '../../../utils/dom.js';
import { getColumnDataByKey, getColumnIndexByKey } from '../utils.js';
import useClassName from './useClassName.js';
import '../../../_chunks/dep-102361be.js';
import 'vue';
import 'raf';
import 'lodash/isString';
import '../../../utils/easing.js';
import 'lodash/isObject';
import '../../config-provider/useConfig.js';
import '../../config-provider/context.js';
import 'lodash/merge';
import 'lodash/mergeWith';
import '../../../_chunks/dep-b4fd1955.js';

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
  } = toRefs(props);
  const {
    tableDraggableClasses,
    tableBaseClass,
    tableFullRowClasses
  } = useClassName();
  const columns = ref(props.columns || []);
  const primaryTableRef = ref(null);
  const dragCol = computed(() => columns.value?.find(item => item.colKey === "drag"));
  const isRowDraggable = computed(() => sortOnRowDraggable.value || dragSort.value === "row");
  const isRowHandlerDraggable = computed(() => ["drag-col", "row-handler", "row-handler-col"].includes(dragSort.value) && !!dragCol.value);
  const isColDraggable = computed(() => ["col", "row-handler-col"].includes(dragSort.value));
  const lastRowList = ref([]);
  const 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, data2 => {
    lastRowList.value = data2?.map(item => get(item, props.rowKey));
  }, {
    immediate: true
  });
  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?.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 => !hasClass(evt.related, tableFullRowClasses.base),
      onEnd(evt) {
        dragInstanceTmp?.sort(lastRowList.value);
        let {
          oldIndex: currentIndex,
          newIndex: targetIndex
        } = evt;
        if (isFunction(props.firstFullRow) && props.firstFullRow(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?.(params);
        context.emit("drag-sort", params);
      },
      ...props.dragSortOptions
    };
    if (!dragContainer) return;
    if (isRowDraggable.value) {
      dragInstanceTmp = new Sortable(dragContainer, {
        ...baseOptions
      });
    } else {
      dragInstanceTmp = new Sortable(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 => {
        if (recover) {
          dragInstanceTmp?.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 = getColumnDataByKey(columns.value, oldElement.dataset.colkey);
        const target = getColumnDataByKey(columns.value, newElement.dataset.colkey);
        if (!current || !current.colKey) log.error("Table", `colKey is missing in ${JSON.stringify(current)}`);
        if (!target || !target.colKey) log.error("Table", `colKey is missing in ${JSON.stringify(target)}`);
        currentIndex = getColumnIndexByKey(props.columns, current.colKey);
        targetIndex = 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.onDragSort?.(params);
        context.emit("drag-sort", params);
      }
    };
    if (!container) return;
    dragInstanceTmp = new Sortable(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?.toArray();
    } else {
      trList.forEach(container => {
        registerOneLevelColDragEvent(container, false);
      });
    }
  };
  function setDragSortPrimaryTableRef(primaryTableElement) {
    primaryTableRef.value = primaryTableElement;
  }
  function setDragSortColumns(val) {
    columns.value = val;
  }
  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
  };
}

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