import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { buildTree, flattenTree, getChildCount, getProjection, removeChildrenOf, removeItem, setProperty } from "./utilities.js";
import SortableTreeItem_default from "./components/TreeItem/SortableTreeItem.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useMemoizedFn } from "ahooks";
import { createPortal } from "react-dom";
import { DndContext, DragOverlay, MeasuringStrategy, PointerSensor, closestCenter, defaultDropAnimation, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, arrayMove, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
//#region src/components/pisellDraggable/index.tsx
/**
* 可拖拽树形组件
* 基于@dnd-kit库实现，支持拖拽排序、展开折叠、删除等功能
*/
/**
* 初始化树形数据结构
* 包含了基本的导航菜单结构：首页、商品集合、关于我们、我的账户等
*/
const initialItems = [
	{
		id: "Home",
		children: []
	},
	{
		id: "Collections",
		children: [
			{
				id: "Spring",
				children: []
			},
			{
				id: "Summer",
				children: []
			},
			{
				id: "Fall",
				children: []
			},
			{
				id: "Winter",
				children: [],
				disabledDrop: true
			}
		]
	},
	{
		id: "About Us",
		children: []
	},
	{
		id: "My Account",
		children: [{
			id: "Addresses",
			children: []
		}, {
			id: "Order History",
			children: []
		}]
	}
];
/**
* 测量策略配置
* strategy: MeasuringStrategy.Always - 始终测量可放置区域的尺寸
*/
const measuring = { droppable: { strategy: MeasuringStrategy.Always } };
/**
* 拖拽动画配置
* 定义了拖拽时的动画效果，包括透明度变化和位置移动
*/
const dropAnimationConfig = {
	keyframes({ transform }) {
		return [{
			opacity: 1,
			transform: CSS.Transform.toString(transform.initial)
		}, {
			opacity: 0,
			transform: CSS.Transform.toString(_objectSpread2(_objectSpread2({}, transform.final), {}, {
				x: transform.final.x + 5,
				y: transform.final.y + 5
			}))
		}];
	},
	easing: "ease-out",
	sideEffects({ active }) {
		active.node.animate([{ opacity: 0 }, { opacity: 1 }], {
			duration: defaultDropAnimation.duration,
			easing: defaultDropAnimation.easing
		});
	}
};
function SortableTree({ collapsible = true, value = initialItems, indicator = false, indentationWidth = 50, removable = true, renderItem, onChange, onRemoveBefore, __designMode, maxLevel = 3, canDrop }) {
	/** 当前树形数据 */
	const [items, setItems] = useState([]);
	/** 当前正在拖拽的节点ID */
	const [activeId, setActiveId] = useState(null);
	/** 当前拖拽悬停的节点ID */
	const [overId, setOverId] = useState(null);
	/** 水平偏移量，用于确定拖拽时的层级变化 */
	const [offsetLeft, setOffsetLeft] = useState(0);
	useEffect(() => {
		console.log("初始化", value);
		setItems(value);
	}, [value]);
	const flattenTreeData = useMemo(() => {
		return flattenTree(items);
	}, [items]);
	/**
	* 扁平化处理树形数据
	* 1. 将树形结构转换为扁平数组
	* 2. 处理折叠状态
	* 3. 移除被折叠节点的子节点
	*/
	const flattenedItems = useMemo(() => {
		const collapsedItems = flattenTreeData.reduce((acc, { children = [], collapsed, id }) => collapsed && children.length ? [...acc, id] : acc, []);
		return removeChildrenOf(flattenTreeData, activeId != null ? [activeId, ...collapsedItems] : collapsedItems);
	}, [activeId, flattenTreeData]);
	console.log("flattenedItems", flattenedItems);
	/**
	* 计算拖拽投影
	* 根据当前拖拽状态计算目标位置和深度
	*/
	const projected = activeId && overId ? getProjection(flattenedItems, activeId, overId, offsetLeft, indentationWidth) : null;
	/**
	* 传感器上下文
	* 存储扁平化的节点数据和偏移量信息
	*/
	const sensorContext = useRef({
		items: flattenedItems,
		offset: offsetLeft
	});
	const sensors = useSensors(useSensor(PointerSensor));
	const sortedIds = useMemo(() => flattenedItems.map(({ id }) => id), [flattenedItems]);
	const activeItem = useMemo(() => {
		return activeId ? flattenedItems.find(({ id }) => id === activeId) : null;
	}, [activeId, flattenedItems]);
	useEffect(() => {
		sensorContext.current = {
			items: flattenedItems,
			offset: offsetLeft
		};
	}, [flattenedItems, offsetLeft]);
	useEffect(() => {
		document.body.id = "body";
	}, []);
	/**
	* 检查子树是否超过最大深度限制
	* @param items 当前项目列表
	* @param itemId 要检查的项目ID
	* @param baseDepth 基础深度
	* @returns 是否超过限制
	*/
	function checkSubtreeDepth(items, itemId, baseDepth) {
		if (!items.find((i) => i.id === itemId)) return false;
		if (baseDepth >= maxLevel) return true;
		const children = items.filter((i) => i.parentId === itemId);
		if (baseDepth >= maxLevel - 1 && children.length > 0) return true;
		return children.some((child) => {
			const childNewDepth = baseDepth + 1;
			return childNewDepth >= maxLevel || checkSubtreeDepth(items, child.id, childNewDepth);
		});
	}
	/**
	* 处理节点删除
	* 从树形结构中移除指定节点
	*/
	const handleRemove = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (item) {
			if (onRemoveBefore) {
				if (!(yield onRemoveBefore === null || onRemoveBefore === void 0 ? void 0 : onRemoveBefore(item))) return;
			}
			setItems((items) => removeItem(items, item.id));
			onChange === null || onChange === void 0 || onChange(items);
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	/**
	* 处理拖拽开始事件
	* 设置当前拖拽项和初始状态
	*/
	const handleDragStart = useMemoizedFn(({ active: { id: activeId } }) => {
		setActiveId(activeId);
		setOverId(activeId);
		document.body.style.setProperty("cursor", "grabbing");
	});
	/**
	* 处理拖拽移动事件
	* 更新水平偏移量
	*/
	const handleDragMove = useMemoizedFn(({ delta }) => {
		setOffsetLeft(delta.x);
	});
	const handleDragOver = useMemoizedFn(({ over }) => {
		if (!projected || !over) {
			var _over$id;
			setOverId((_over$id = over === null || over === void 0 ? void 0 : over.id) !== null && _over$id !== void 0 ? _over$id : null);
			return;
		}
		const targetParent = projected.parentId ? flattenedItems.find((item) => item.id === projected.parentId) : null;
		if (targetParent === null || targetParent === void 0 ? void 0 : targetParent.disabledDrop) return;
		if (projected.depth >= maxLevel) return;
		if (checkSubtreeDepth(flattenTreeData, activeId, projected.depth)) return;
		setOverId(over.id);
	});
	const parentNode = useMemo(() => {
		return (projected === null || projected === void 0 ? void 0 : projected.parentId) ? flattenedItems.find((item) => item.id === projected.parentId) : null;
	}, [flattenedItems, projected === null || projected === void 0 ? void 0 : projected.parentId]);
	/**
	* 处理拖拽结束事件
	* 1. 重置状态
	* 2. 更新节点位置和层级
	* 3. 重建树形结构
	*/
	const handleDragEnd = useMemoizedFn(({ active, over }) => {
		resetState();
		if (projected && over) {
			const { depth, parentId } = projected;
			const targetParent = parentId ? flattenedItems.find((item) => item.id === parentId) : null;
			if (targetParent === null || targetParent === void 0 ? void 0 : targetParent.disabledDrop) return;
			const dragItem = flattenedItems.find((item) => item.id === active.id);
			const dropTarget = flattenedItems.find((item) => item.id === over.id);
			if (canDrop && dragItem && dropTarget) {
				if (!canDrop(dragItem, dropTarget, parentId, targetParent)) return;
			}
			if (depth >= maxLevel) return;
			if (checkSubtreeDepth(flattenTreeData, active.id, depth)) return;
			const clonedItems = JSON.parse(JSON.stringify(flattenTree(items)));
			const overIndex = clonedItems.findIndex(({ id }) => id === over.id);
			const activeIndex = clonedItems.findIndex(({ id }) => id === active.id);
			const activeTreeItem = clonedItems[activeIndex];
			clonedItems[activeIndex] = _objectSpread2(_objectSpread2({}, activeTreeItem), {}, {
				depth,
				parentId
			});
			const newItems = buildTree(arrayMove(clonedItems, activeIndex, overIndex));
			setItems(newItems);
			onChange === null || onChange === void 0 || onChange(newItems);
		}
	});
	/**
	* 处理节点折叠/展开
	* 切换指定节点的折叠状态
	*/
	const handleCollapse = useMemoizedFn((id) => {
		setItems((items) => {
			const newVal = setProperty(items, id, "collapsed", (value) => {
				return !value;
			});
			onChange === null || onChange === void 0 || onChange(items);
			return newVal;
		});
	});
	const isError = useMemo(() => {
		return !(canDrop === null || canDrop === void 0 ? void 0 : canDrop(activeItem || {}, {}, projected === null || projected === void 0 ? void 0 : projected.parentId, parentNode));
	}, [
		projected,
		activeItem,
		canDrop,
		parentNode
	]);
	const renderTreeItems = useMemo(() => {
		return flattenedItems.map((item) => {
			const { id, children, collapsed, depth } = item;
			return /* @__PURE__ */ React.createElement(SortableTreeItem_default, {
				key: id,
				id,
				item,
				depth: id === activeId && projected ? projected.depth : depth,
				indentationWidth,
				indicator,
				collapsed: Boolean(collapsed && (children === null || children === void 0 ? void 0 : children.length)),
				onCollapse: collapsible && (children === null || children === void 0 ? void 0 : children.length) ? () => handleCollapse(id) : void 0,
				onRemove: removable ? () => handleRemove(item) : void 0,
				renderItem,
				__designMode
			});
		});
	}, [
		flattenedItems,
		activeId,
		projected === null || projected === void 0 ? void 0 : projected.depth,
		indentationWidth,
		indicator,
		collapsible,
		handleCollapse,
		handleRemove,
		renderItem,
		__designMode
	]);
	return /* @__PURE__ */ React.createElement(DndContext, {
		sensors,
		collisionDetection: closestCenter,
		measuring,
		onDragStart: handleDragStart,
		onDragMove: handleDragMove,
		onDragOver: handleDragOver,
		onDragEnd: handleDragEnd,
		onDragCancel: handleDragCancel
	}, /* @__PURE__ */ React.createElement(SortableContext, {
		items: sortedIds,
		strategy: verticalListSortingStrategy
	}, renderTreeItems, createPortal(/* @__PURE__ */ React.createElement(DragOverlay, {
		dropAnimation: dropAnimationConfig,
		modifiers: indicator ? [adjustTranslate] : void 0
	}, activeId && activeItem ? /* @__PURE__ */ React.createElement(SortableTreeItem_default, {
		id: activeId,
		depth: activeItem.depth,
		clone: true,
		childCount: getChildCount(items, activeId) + 1,
		item: activeItem,
		indentationWidth,
		renderItem: (props, ref) => renderItem === null || renderItem === void 0 ? void 0 : renderItem(_objectSpread2(_objectSpread2({}, props), {}, { isError }), ref)
	}) : null), document.body)));
	function handleDragCancel() {
		resetState();
	}
	function resetState() {
		setOverId(null);
		setActiveId(null);
		setOffsetLeft(0);
		document.body.style.setProperty("cursor", "");
	}
}
/**
* 调整拖拽项的位置
* 对拖拽时的位置进行微调，提升视觉效果
*/
const adjustTranslate = ({ transform }) => {
	return _objectSpread2(_objectSpread2({}, transform), {}, { y: transform.y - 25 });
};
const Demo = (props) => {
	return /* @__PURE__ */ React.createElement(SortableTree, props);
};
//#endregion
export { SortableTree, Demo as default };
