import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import React, { useMemo, useState } from "react";
import { Empty, Modal, Space, Spin, Table, Tag } from "antd";
import { locales } from "@pisell/utils";
import { Button as Button$1 } from "@pisell/materials";
import { CaretDownOutlined, CaretRightOutlined, DeleteOutlined, EditOutlined, HolderOutlined, PlusOutlined } from "@ant-design/icons";
import { DndContext, DragOverlay, PointerSensor, closestCenter, rectIntersection, useDroppable, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
//#region src/components/systemSettings/registry/components/SettingsTable.tsx
const _excluded = [
	"record",
	"children",
	"className",
	"style"
];
const AntdTag = Tag;
const AntdSpace = Space;
const scopeKeyMapping = {
	"system": "registry.scope.systemDefault",
	"saas": "registry.scope.saasDefault",
	"organization": "registry.scope.organization",
	"business": "registry.scope.business",
	"channel": "registry.scope.channel",
	"board": "registry.scope.board",
	"profile": "registry.scope.profile",
	"instance": "registry.scope.instance"
};
const getMultiLanguageText = (text, currentLocale) => {
	if (typeof text === "string") return text;
	const currentLang = currentLocale || localStorage.getItem("umi_locale") || "zh-CN";
	if (text[currentLang]) return text[currentLang];
	return text.original || "";
};
const DragContext = React.createContext({});
const DragHandle = ({ record, isGroup, isExpanded, onExpand, currentLocale }) => {
	const { attributes, listeners } = React.useContext(DragContext);
	return /* @__PURE__ */ React.createElement("div", {
		className: "pisell-settings-registry-table-title",
		style: {
			paddingLeft: record.level * 24,
			display: "flex",
			alignItems: "center"
		}
	}, /* @__PURE__ */ React.createElement("div", _objectSpread2(_objectSpread2(_objectSpread2({ className: "drag-handle" }, attributes || {}), listeners || {}), {}, { style: {
		cursor: "grab",
		marginRight: 8,
		color: "#999",
		fontSize: "12px",
		display: "flex",
		alignItems: "center"
	} }), /* @__PURE__ */ React.createElement(HolderOutlined, null)), isGroup && /* @__PURE__ */ React.createElement(Button$1, {
		type: "text",
		size: "small",
		icon: isExpanded ? /* @__PURE__ */ React.createElement(CaretDownOutlined, null) : /* @__PURE__ */ React.createElement(CaretRightOutlined, null),
		onClick: () => onExpand(record.key),
		style: { marginRight: 8 }
	}), /* @__PURE__ */ React.createElement(AntdTag, { color: isGroup ? "blue" : "green" }, locales.getText(isGroup ? "registry.level.group" : "registry.level.item")), /* @__PURE__ */ React.createElement("span", { style: { marginLeft: 8 } }, getMultiLanguageText(record.data.title || record.data.name, currentLocale)));
};
const DraggableRow = (_ref) => {
	let { record, children, className, style } = _ref, props = _objectWithoutProperties(_ref, _excluded);
	if (!record || !record.key) return /* @__PURE__ */ React.createElement("tr", _objectSpread2({
		className,
		style
	}, props), children);
	const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
		id: record.key,
		data: {
			type: record.type,
			record,
			groupId: record.type === "item" ? record.data.groupId || record.data.group_id : record.data.id
		}
	});
	const dropResult = useDroppable({
		id: record.type === "group" ? `item-container-${record.data.id}` : `drop-${record.key}`,
		data: {
			type: record.type === "group" ? "item-container" : "item",
			groupId: record.type === "group" ? record.data.id : void 0,
			acceptTypes: record.type === "group" ? ["item"] : []
		},
		disabled: record.type !== "group"
	});
	const dragStyle = _objectSpread2(_objectSpread2({
		transform: CSS.Transform.toString(transform),
		transition,
		opacity: isDragging ? .5 : 1
	}, record.type === "group" && dropResult.isOver ? {
		backgroundColor: "rgba(24, 144, 255, 0.05)",
		borderLeft: "3px solid #1890ff"
	} : {}), style);
	const combinedRef = (node) => {
		setNodeRef(node);
		dropResult.setNodeRef(node);
	};
	return /* @__PURE__ */ React.createElement(DragContext.Provider, { value: {
		attributes,
		listeners
	} }, /* @__PURE__ */ React.createElement("tr", _objectSpread2({
		ref: combinedRef,
		style: dragStyle,
		className: `${className} ${isDragging ? "dragging" : ""} ${record.type === "group" ? "group-row" : ""} ${dropResult.isOver && record.type === "group" ? "drop-over" : ""}`
	}, props), children));
};
const SettingsTable = ({ section, groupList = [], groupLoading = false, onDataChange, onEditGroup, onDeleteGroup, onAddItem, onEditItem, onDeleteItem, onGroupReorder, onItemMove }) => {
	var _context$engine;
	const context = useEngineContext();
	const [expandedKeys, setExpandedKeys] = useState([]);
	const [activeId, setActiveId] = useState(null);
	const [dragOverZone, setDragOverZone] = useState(null);
	const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
	const virtualDropZones = useMemo(() => {
		const zones = [];
		groupList.forEach((group) => {
			zones.push({
				id: `group-zone-${group.id}`,
				type: "group",
				groupId: group.id,
				acceptTypes: ["group"],
				key: `group-${group.id}`
			});
			zones.push({
				id: `item-container-${group.id}`,
				type: "item-container",
				groupId: group.id,
				acceptTypes: ["item"],
				key: `item-${group.id}`
			});
		});
		return zones;
	}, [groupList]);
	const customCollisionDetection = (args) => {
		var _standardCollisions$;
		const { active, droppableContainers } = args;
		const virtualContainers = Array.from(droppableContainers.values()).filter((container) => {
			const id = container.id;
			return id.startsWith("item-container-") || id.startsWith("group-zone-");
		});
		if (virtualContainers.length > 0) {
			const virtualCollisions = rectIntersection(_objectSpread2(_objectSpread2({}, args), {}, { droppableContainers: virtualContainers }));
			if (virtualCollisions && virtualCollisions.length > 0) {
				console.log("虚拟容器碰撞检测:", virtualCollisions[0].id);
				return virtualCollisions;
			}
		}
		const standardCollisions = closestCenter(args);
		console.log("标准碰撞检测:", standardCollisions === null || standardCollisions === void 0 || (_standardCollisions$ = standardCollisions[0]) === null || _standardCollisions$ === void 0 ? void 0 : _standardCollisions$.id);
		return standardCollisions;
	};
	const currentLocale = (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || localStorage.getItem("umi_locale") || "zh-CN";
	const treeData = useMemo(() => {
		if (!groupList || groupList.length === 0) return [];
		const nodes = [];
		groupList.forEach((group) => {
			const groupNode = {
				key: `group-${group.id}`,
				type: "group",
				data: group,
				children: []
			};
			group === null || group === void 0 || group.items.sort((a, b) => a.sort - b.sort || a.id - b.id).forEach((item) => {
				const itemNode = {
					key: `item-${item.id}`,
					type: "item",
					data: item,
					parentKey: groupNode.key
				};
				groupNode.children.push(itemNode);
			});
			nodes.push(groupNode);
		});
		return nodes;
	}, [groupList]);
	React.useEffect(() => {
		if (groupList && groupList.length > 0) setExpandedKeys(groupList.filter((group) => group.expanded !== false).map((group) => `group-${group.id}`));
	}, [groupList]);
	const flattenData = useMemo(() => {
		const result = [];
		treeData.forEach((groupNode, groupIndex) => {
			const groupZone = virtualDropZones.find((z) => z.id === `group-zone-${groupNode.data.id}`);
			result.push({
				key: groupNode.key,
				type: "group",
				data: groupNode.data,
				level: 0,
				virtualZone: groupZone
			});
			if (expandedKeys.includes(groupNode.key)) {
				if (groupNode.children && groupNode.children.length > 0) groupNode.children.forEach((itemNode) => {
					result.push({
						key: itemNode.key,
						type: "item",
						data: itemNode.data,
						level: 1
					});
				});
			}
		});
		return result;
	}, [
		treeData,
		expandedKeys,
		virtualDropZones
	]);
	const handleExpand = (key) => {
		setExpandedKeys((prev) => prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]);
	};
	const handleDragStart = (event) => {
		setActiveId(event.active.id);
	};
	const handleDragOver = (event) => {
		const { active, over } = event;
		if (!over) {
			setDragOverZone(null);
			return;
		}
		const overId = over.id;
		if (virtualDropZones.find((z) => z.id === overId)) setDragOverZone(overId);
		else setDragOverZone(null);
	};
	const handleDragEnd = (event) => {
		const { active, over } = event;
		setActiveId(null);
		setDragOverZone(null);
		if (!over || active.id === over.id) return;
		const activeData = active.data.current;
		const overData = over.data.current;
		if (!activeData) return;
		const activeRecord = activeData.record;
		const overId = over.id;
		console.log("拖拽结束:", {
			activeId: active.id,
			overId,
			activeRecord: activeRecord.type
		});
		if (activeRecord.type === "group") {
			const targetZone = virtualDropZones.find((z) => z.key === overId && z.type === "group");
			if (targetZone) {
				const activeGroupId = activeRecord.data.id;
				const targetGroupId = targetZone.groupId;
				if (activeGroupId === targetGroupId) return;
				const newGroupOrder = [...groupList];
				const activeIndex = newGroupOrder.findIndex((g) => g.id === activeGroupId);
				const targetIndex = newGroupOrder.findIndex((g) => g.id === targetGroupId);
				if (activeIndex !== -1 && targetIndex !== -1) {
					const [movedGroup] = newGroupOrder.splice(activeIndex, 1);
					newGroupOrder.splice(targetIndex, 0, movedGroup);
					const groupIds = newGroupOrder.map((g) => g.id);
					console.log("调用组重排序接口 (虚拟容器):", groupIds);
					onGroupReorder === null || onGroupReorder === void 0 || onGroupReorder(groupIds);
				}
				return;
			}
		}
		if (activeRecord.type === "item") {
			const targetZone = virtualDropZones.find((z) => z.id === overId);
			if (targetZone && targetZone.type === "item-container") {
				var _targetGroup$items;
				const activeItemId = activeRecord.data.id;
				const targetGroupId = targetZone.groupId;
				const currentGroup = groupList.find((g) => g.items && g.items.some((item) => item.id === activeItemId));
				if (!currentGroup) return;
				if (currentGroup.id === targetGroupId) return;
				const targetGroup = groupList.find((g) => g.id === targetGroupId);
				const newOrder = (targetGroup === null || targetGroup === void 0 || (_targetGroup$items = targetGroup.items) === null || _targetGroup$items === void 0 ? void 0 : _targetGroup$items.length) || 0;
				console.log("调用设置项移动接口 (虚拟容器):", {
					activeItemId,
					targetGroupId,
					newOrder
				});
				onItemMove === null || onItemMove === void 0 || onItemMove(activeItemId, targetGroupId, newOrder);
				return;
			}
		}
		if (overData && overData.record) {
			const overRecord = overData.record;
			if (activeRecord.type === "item" && overRecord.type === "group") {
				var _targetGroup$items2;
				const activeItemId = activeRecord.data.id;
				const targetGroupId = overRecord.data.id;
				const currentGroup = groupList.find((g) => g.items && g.items.some((item) => item.id === activeItemId));
				if (!currentGroup) return;
				if (currentGroup.id === targetGroupId) return;
				const targetGroup = groupList.find((g) => g.id === targetGroupId);
				const newOrder = (targetGroup === null || targetGroup === void 0 || (_targetGroup$items2 = targetGroup.items) === null || _targetGroup$items2 === void 0 ? void 0 : _targetGroup$items2.length) || 0;
				console.log("调用设置项移动接口 (直接拖放到组):", {
					activeItemId,
					targetGroupId,
					newOrder
				});
				onItemMove === null || onItemMove === void 0 || onItemMove(activeItemId, targetGroupId, newOrder);
				return;
			}
			if (activeRecord.type === "item" && overRecord.type === "item") {
				const activeItemId = activeRecord.data.id;
				const overItemId = overRecord.data.id;
				const activeGroup = groupList.find((g) => g.items && g.items.some((item) => item.id === activeItemId));
				const overGroup = groupList.find((g) => g.items && g.items.some((item) => item.id === overItemId));
				if (!activeGroup || !overGroup) return;
				if (activeGroup.id === overGroup.id) {
					const activeIndex = activeGroup.items.findIndex((item) => item.id === activeItemId);
					const overIndex = activeGroup.items.findIndex((item) => item.id === overItemId);
					if (activeIndex !== -1 && overIndex !== -1 && activeIndex !== overIndex) {
						console.log("调用同组内设置项排序接口:", {
							activeItemId,
							targetGroupId: activeGroup.id,
							newOrder: overIndex
						});
						onItemMove === null || onItemMove === void 0 || onItemMove(activeItemId, activeGroup.id, overIndex);
					}
				} else {
					const overIndex = overGroup.items.findIndex((item) => item.id === overItemId);
					const newOrder = overIndex >= 0 ? overIndex : 0;
					console.log("调用跨组设置项移动接口:", {
						activeItemId,
						targetGroupId: overGroup.id,
						newOrder
					});
					onItemMove === null || onItemMove === void 0 || onItemMove(activeItemId, overGroup.id, newOrder);
				}
			}
		}
	};
	const handleDelete = (record) => {
		if (record.type === "group") {
			if (record.data.items && record.data.items.length > 0) {
				Modal.warning({
					title: locales.getText("registry.modal.delete.group.hasItems.title"),
					content: locales.getText("registry.modal.delete.group.hasItems.content")
				});
				return;
			}
		}
		Modal.confirm({
			title: locales.getText("registry.modal.delete.title"),
			content: locales.getText(record.type === "group" ? "registry.modal.delete.group.content" : "registry.modal.delete.item.content"),
			onOk: () => {
				if (record.type === "group") onDeleteGroup === null || onDeleteGroup === void 0 || onDeleteGroup(record.data.id);
				else onDeleteItem === null || onDeleteItem === void 0 || onDeleteItem(record.data.id);
			}
		});
	};
	useMemo(() => {
		if (!activeId) return void 0;
		const activeItem = flattenData.find((item) => item.key === activeId);
		return activeItem === null || activeItem === void 0 ? void 0 : activeItem.type;
	}, [activeId, flattenData]);
	const columns = [
		{
			title: locales.getText("registry.table.title"),
			dataIndex: "name",
			key: "name",
			width: "30%",
			render: (_, record) => {
				const isGroup = record.type === "group";
				const isExpanded = expandedKeys.includes(record.key);
				return /* @__PURE__ */ React.createElement(DragHandle, {
					record,
					isGroup,
					isExpanded,
					onExpand: handleExpand,
					currentLocale
				});
			}
		},
		{
			title: locales.getText("registry.table.key"),
			dataIndex: "key",
			key: "key",
			width: "25%",
			render: (_, record) => {
				if (record.type === "group") return /* @__PURE__ */ React.createElement("span", { className: "pisell-settings-registry-code" }, record.data.code);
				return /* @__PURE__ */ React.createElement("span", { className: "pisell-settings-registry-key" }, record.data.key || record.data.code);
			}
		},
		{
			title: locales.getText("registry.table.scopes"),
			dataIndex: "scopes",
			key: "scopes",
			width: "25%",
			render: (_, record) => {
				if (record.type === "item" && record.data.scopes) return /* @__PURE__ */ React.createElement(AntdSpace, { wrap: true }, record.data.scopes.map((scope) => /* @__PURE__ */ React.createElement(AntdTag, {
					key: scope,
					size: "small"
				}, locales.getText(scopeKeyMapping[scope] || `registry.scope.${scope}`))));
				return "-";
			}
		},
		{
			title: locales.getText("registry.table.actions"),
			key: "actions",
			width: "20%",
			render: (_, record) => {
				const isGroup = record.type === "group";
				return /* @__PURE__ */ React.createElement(AntdSpace, { size: "small" }, isGroup && /* @__PURE__ */ React.createElement(Button$1, {
					type: "text",
					size: "small",
					icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
					onClick: () => onAddItem === null || onAddItem === void 0 ? void 0 : onAddItem(record.data.id),
					title: locales.getText("registry.action.add.item")
				}), /* @__PURE__ */ React.createElement(Button$1, {
					type: "text",
					size: "small",
					icon: /* @__PURE__ */ React.createElement(EditOutlined, null),
					onClick: () => {
						if (isGroup) onEditGroup === null || onEditGroup === void 0 || onEditGroup(record.data);
						else onEditItem === null || onEditItem === void 0 || onEditItem(record.data);
					},
					title: locales.getText("registry.action.edit")
				}), /* @__PURE__ */ React.createElement(Button$1, {
					type: "text",
					size: "small",
					icon: /* @__PURE__ */ React.createElement(DeleteOutlined, null),
					danger: true,
					onClick: () => handleDelete(record),
					title: locales.getText("registry.action.delete")
				}));
			}
		}
	];
	if (!section) return /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-table-empty" }, /* @__PURE__ */ React.createElement(Empty, {
		description: locales.getText("registry.message.select.section"),
		image: Empty.PRESENTED_IMAGE_SIMPLE
	}));
	if (groupLoading) return /* @__PURE__ */ React.createElement("div", {
		className: "pisell-settings-registry-table-loading",
		style: {
			textAlign: "center",
			padding: "50px"
		}
	}, /* @__PURE__ */ React.createElement(Spin, { size: "large" }), /* @__PURE__ */ React.createElement("div", { style: { marginTop: "16px" } }, locales.getText("registry.message.loading.groups")));
	if (flattenData.length === 0) return /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-table-empty" }, /* @__PURE__ */ React.createElement(Empty, {
		description: locales.getText("registry.message.no.settings"),
		image: Empty.PRESENTED_IMAGE_SIMPLE
	}));
	const sortableIds = flattenData.map((item) => item.key);
	return /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-table" }, /* @__PURE__ */ React.createElement(DndContext, {
		sensors,
		collisionDetection: customCollisionDetection,
		onDragStart: handleDragStart,
		onDragOver: handleDragOver,
		onDragEnd: handleDragEnd
	}, /* @__PURE__ */ React.createElement(SortableContext, {
		items: sortableIds,
		strategy: verticalListSortingStrategy
	}, /* @__PURE__ */ React.createElement(Table, {
		columns,
		dataSource: flattenData,
		pagination: false,
		rowKey: "key",
		className: "pisell-settings-registry-table-content",
		components: { body: { row: (props) => {
			const rowKey = props["data-row-key"];
			const record = flattenData.find((item) => item.key === rowKey);
			if (!record) return /* @__PURE__ */ React.createElement("tr", props);
			return /* @__PURE__ */ React.createElement(DraggableRow, _objectSpread2(_objectSpread2({}, props), {}, { record }));
		} } }
	})), /* @__PURE__ */ React.createElement(DragOverlay, null, activeId ? /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-drag-overlay" }, (() => {
		const activeItem = flattenData.find((item) => item.key === activeId);
		if (!activeItem) return null;
		return /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-drag-item" }, /* @__PURE__ */ React.createElement(AntdTag, { color: activeItem.type === "group" ? "blue" : "green" }, locales.getText(activeItem.type === "group" ? "registry.level.group" : "registry.level.item")), /* @__PURE__ */ React.createElement("span", null, getMultiLanguageText(activeItem.data.title || activeItem.data.name, currentLocale)));
	})()) : null)));
};
//#endregion
export { SettingsTable as default };
