import useSharedState from "../../../../../hooks/useSharedState.js";
import { _asyncToGenerator } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { Context } from "../../../model.js";
import { getIdByRowKey } from "../../utils.js";
import React, { useRef } from "react";
import { isFunction } from "@pisell/utils";
import { DndContext } from "@dnd-kit/core";
import { SortableContext, arrayMove, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import "./index.less";
//#region src/components/table/Table/tableConfig/SortRow/index.tsx
const SortRow = ({ children, rowKey, onSortChange }) => {
	const { state, dispatch } = useSharedState(Context);
	const { originDataSource } = state;
	const oldOriginDataSource = useRef(null);
	const onDragEnd = function() {
		var _ref = _asyncToGenerator(function* ({ active, over }) {
			if (active.id !== (over === null || over === void 0 ? void 0 : over.id)) {
				const activeIndex = originDataSource.findIndex((i) => getIdByRowKey(i, rowKey) === active.id);
				const overIndex = originDataSource.findIndex((i) => getIdByRowKey(i, rowKey) === (over === null || over === void 0 ? void 0 : over.id));
				const newData = arrayMove(originDataSource, activeIndex, overIndex);
				dispatch({
					type: "setOriginDataSource",
					payload: newData
				});
				if (isFunction(onSortChange)) {
					oldOriginDataSource.current = originDataSource;
					if (yield onSortChange({
						fromIndex: activeIndex,
						toIndex: overIndex,
						dataSource: newData,
						fromId: active.id,
						toId: over === null || over === void 0 ? void 0 : over.id,
						fromItem: originDataSource[activeIndex],
						toItem: originDataSource[overIndex]
					})) dispatch({
						type: "setOriginDataSource",
						payload: oldOriginDataSource.current
					});
					else oldOriginDataSource.current = null;
				}
			}
		});
		return function onDragEnd(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ React.createElement("div", { className: "grid-view-table-wrap" }, /* @__PURE__ */ React.createElement(DndContext, {
		modifiers: [restrictToVerticalAxis],
		onDragEnd
	}, /* @__PURE__ */ React.createElement(SortableContext, {
		items: originDataSource.map((i) => getIdByRowKey(i, rowKey)),
		strategy: verticalListSortingStrategy
	}, children)));
};
//#endregion
export { SortRow as default };
