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 useEngineContext from "../../../hooks/useEngineContext.js";
import { request } from "../../../utils/index.js";
import SectionList from "./components/SectionList.js";
import SettingsTable from "./components/SettingsTable.js";
import locales_default from "./locales.js";
import GroupModal from "./components/GroupModal.js";
import { parseDefaultValue, validateDefaultValue } from "./utils/typeValidation.js";
import ItemModal from "./components/ItemModal.js";
import { createGroup, createItem, deleteGroup, deleteItem, getGroupList, getSectionList, sortGroups, sortItems, updateGroup, updateItem } from "./services.js";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { message } from "antd";
import { locales } from "@pisell/utils";
import { Button as Button$1 } from "@pisell/materials";
import { PlusOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/components/systemSettings/registry/index.tsx
const Registry = ({ className, style, sections = [], selectedSectionId, onSectionSelect, onDataChange, scene }) => {
	var _context$engine2;
	const context = useEngineContext();
	const { request: request$1 } = context.appHelper.utils;
	const [localSections, setLocalSections] = useState(sections);
	const [currentSectionId, setCurrentSectionId] = useState(selectedSectionId || (sections.length > 0 ? sections[0].id : 0));
	request.setRequest(request$1);
	const [loading, setLoading] = useState(false);
	const [hasMore, setHasMore] = useState(true);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize] = useState(20);
	const [isInitialLoad, setIsInitialLoad] = useState(true);
	const [groupList, setGroupList] = useState([]);
	const [groupLoading, setGroupLoading] = useState(false);
	const onDataChangeRef = useRef(onDataChange);
	const lastLoadedSectionCodeRef = useRef("");
	onDataChangeRef.current = onDataChange;
	const [groupModalOpen, setGroupModalOpen] = useState(false);
	const [itemModalOpen, setItemModalOpen] = useState(false);
	const [modalType, setModalType] = useState("add");
	const [editingGroup, setEditingGroup] = useState();
	const [editingItem, setEditingItem] = useState();
	const [targetGroupId, setTargetGroupId] = useState(0);
	const handleCreateGroup = function() {
		var _ref = _asyncToGenerator(function* (params) {
			try {
				const response = yield createGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.save.success"));
				return response;
			} catch (error) {
				message.error(locales.getText("registry.message.create.group.error"));
				throw error;
			}
		});
		return function handleCreateGroup(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const handleUpdateGroup = function() {
		var _ref2 = _asyncToGenerator(function* (params) {
			try {
				const response = yield updateGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.save.success"));
				return response;
			} catch (error) {
				throw error;
			}
		});
		return function handleUpdateGroup(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleDeleteGroup = function() {
		var _ref3 = _asyncToGenerator(function* (params) {
			try {
				const response = yield deleteGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.delete.success"));
				return response;
			} catch (error) {
				throw error;
			}
		});
		return function handleDeleteGroup(_x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	const handleCreateItem = function() {
		var _ref4 = _asyncToGenerator(function* (params) {
			try {
				const response = yield createItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.save.success"));
				return response;
			} catch (error) {
				throw error;
			}
		});
		return function handleCreateItem(_x4) {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleUpdateItem = function() {
		var _ref5 = _asyncToGenerator(function* (params) {
			try {
				const response = yield updateItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.save.success"));
				return response;
			} catch (error) {
				throw error;
			}
		});
		return function handleUpdateItem(_x5) {
			return _ref5.apply(this, arguments);
		};
	}();
	const handleDeleteItem = function() {
		var _ref6 = _asyncToGenerator(function* (params) {
			try {
				const response = yield deleteItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				message.success(locales.getText("registry.message.delete.success"));
				return response;
			} catch (error) {
				console.error("Failed to delete item:", error);
				throw error;
			}
		});
		return function handleDeleteItem(_x6) {
			return _ref6.apply(this, arguments);
		};
	}();
	const handleGroupReorder = function() {
		var _ref7 = _asyncToGenerator(function* (groupIds) {
			try {
				const currentSection = localSections.find((s) => s.id === currentSectionId);
				if (!currentSection) throw new Error("Current section not found");
				yield sortGroups(request$1, {
					section_code: currentSection.code,
					group_ids: groupIds
				}, scene);
				setGroupList(groupIds.map((id) => {
					const group = groupList.find((g) => g.id === id);
					return group ? _objectSpread2({}, group) : null;
				}).filter(Boolean));
				message.success(locales.getText("registry.message.reorder.success"));
			} catch (error) {
				console.error("Failed to reorder groups:", error);
				const currentSection = localSections.find((s) => s.id === currentSectionId);
				if (currentSection) yield loadGroupData(currentSection.code, true);
			}
		});
		return function handleGroupReorder(_x7) {
			return _ref7.apply(this, arguments);
		};
	}();
	const handleItemMove = function() {
		var _ref8 = _asyncToGenerator(function* (itemId, targetGroupId, newOrder) {
			try {
				const targetGroup = groupList.find((g) => g.id === targetGroupId);
				if (!targetGroup) throw new Error("Target group not found");
				const targetGroupItems = [...targetGroup.items];
				const existingIndex = targetGroupItems.findIndex((item) => item.id === itemId);
				if (existingIndex !== -1) {
					const [movedItem] = targetGroupItems.splice(existingIndex, 1);
					targetGroupItems.splice(newOrder, 0, movedItem);
				} else {
					const movedItem = groupList.reduce((acc, g) => [...acc, ...g.items], []).find((item) => item.id === itemId);
					if (movedItem) targetGroupItems.splice(newOrder, 0, movedItem);
				}
				const sortedItemIds = targetGroupItems.map((item) => item.id);
				yield sortItems(request$1, {
					id: itemId,
					group_id: targetGroupId.toString(),
					item_ids: sortedItemIds
				}, scene);
				const currentSection = localSections.find((s) => s.id === currentSectionId);
				if (currentSection) yield loadGroupData(currentSection.code, true);
				message.success(locales.getText("registry.message.move.success"));
			} catch (error) {
				console.error("Failed to move item:", error);
				const currentSection = localSections.find((s) => s.id === currentSectionId);
				if (currentSection) yield loadGroupData(currentSection.code, true);
			}
		});
		return function handleItemMove(_x8, _x9, _x10) {
			return _ref8.apply(this, arguments);
		};
	}();
	const loadGroupData = useCallback(function() {
		var _ref9 = _asyncToGenerator(function* (sectionCode, forceRefresh = false) {
			const dedupKey = `${scene !== null && scene !== void 0 ? scene : ""}::${sectionCode}`;
			if (groupLoading || !forceRefresh && lastLoadedSectionCodeRef.current === dedupKey) return;
			lastLoadedSectionCodeRef.current = dedupKey;
			setGroupLoading(true);
			try {
				setGroupList((yield getGroupList(request$1, {
					page: 1,
					pageSize: 100,
					filter: { section_code: sectionCode }
				}, scene)).data || []);
			} catch (error) {
				console.error("Failed to load group data:", error);
				setGroupList([]);
			} finally {
				setGroupLoading(false);
			}
		});
		return function(_x11) {
			return _ref9.apply(this, arguments);
		};
	}(), [scene]);
	const loadSectionData = useCallback(function() {
		var _ref10 = _asyncToGenerator(function* (page, isLoadMore = false) {
			if (loading) return;
			setLoading(true);
			try {
				const response = yield getSectionList(request$1, {
					page,
					pageSize,
					filter: {}
				}, scene);
				const newSections = response.data || [];
				if (isLoadMore) setLocalSections((prev) => [...prev, ...newSections]);
				else {
					setLocalSections(newSections);
					if (newSections.length > 0 && (!currentSectionId || currentSectionId === 0)) setCurrentSectionId(newSections[0].id);
				}
				const { totalPage } = response.meta;
				setHasMore(page < totalPage);
				if (isLoadMore) setLocalSections((prev) => {
					var _onDataChangeRef$curr;
					const updatedSections = [...prev, ...newSections];
					(_onDataChangeRef$curr = onDataChangeRef.current) === null || _onDataChangeRef$curr === void 0 || _onDataChangeRef$curr.call(onDataChangeRef, updatedSections);
					return updatedSections;
				});
				else {
					var _onDataChangeRef$curr2;
					(_onDataChangeRef$curr2 = onDataChangeRef.current) === null || _onDataChangeRef$curr2 === void 0 || _onDataChangeRef$curr2.call(onDataChangeRef, newSections);
				}
			} catch (error) {
				console.error("Failed to load section data:", error);
			} finally {
				setLoading(false);
			}
		});
		return function(_x12) {
			return _ref10.apply(this, arguments);
		};
	}(), [
		loading,
		pageSize,
		currentSectionId,
		scene
	]);
	const handleLoadMore = useCallback(() => {
		if (!hasMore || loading) return;
		const nextPage = currentPage + 1;
		setCurrentPage(nextPage);
		loadSectionData(nextPage, true);
	}, [
		hasMore,
		loading,
		currentPage
	]);
	useEffect(() => {
		var _context$engine;
		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";
		locales.init(locales_default, currentLocale);
	}, [context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale]);
	useEffect(() => {
		if (isInitialLoad) {
			setIsInitialLoad(false);
			loadSectionData(1, false);
		}
	}, [isInitialLoad]);
	useEffect(() => {
		if (!isInitialLoad && sections && sections.length > 0) setLocalSections(sections);
	}, [sections, isInitialLoad]);
	useEffect(() => {
		if (selectedSectionId) setCurrentSectionId(selectedSectionId);
	}, [selectedSectionId]);
	useEffect(() => {
		if (currentSectionId && localSections.length > 0) {
			const selectedSection = localSections.find((section) => section.id === currentSectionId);
			if (selectedSection) {
				lastLoadedSectionCodeRef.current = "";
				loadGroupData(selectedSection.code);
			}
		}
	}, [currentSectionId, localSections]);
	const handleSectionSelect = (sectionId) => {
		setCurrentSectionId(sectionId);
		onSectionSelect === null || onSectionSelect === void 0 || onSectionSelect(sectionId);
	};
	const handleDataChange = (updatedSection) => {
		const newSections = localSections.map((section) => section.id === updatedSection.id ? updatedSection : section);
		setLocalSections(newSections);
		onDataChange === null || onDataChange === void 0 || onDataChange(newSections);
	};
	const currentSection = localSections.find((section) => section.id === currentSectionId);
	const isCodeExists = (code, excludeId) => {
		if (!currentSection || !currentSection.groups) return false;
		return currentSection.groups.some((group) => group.code === code && group.id !== excludeId);
	};
	const isKeyExists = (key, excludeId) => {
		if (!currentSection || !currentSection.groups) return false;
		return currentSection.groups.some((group) => group.items && group.items.some((item) => item.key === key && item.id !== excludeId));
	};
	const handleAddGroup = () => {
		setModalType("add");
		setEditingGroup(void 0);
		setGroupModalOpen(true);
	};
	const handleEditGroup = (group) => {
		setModalType("edit");
		setEditingGroup(group);
		console.log("group", group);
		setGroupModalOpen(true);
	};
	const handleAddItem = (groupId) => {
		setModalType("add");
		setEditingItem(void 0);
		setTargetGroupId(groupId);
		setItemModalOpen(true);
	};
	const handleEditItem = (item) => {
		setModalType("edit");
		setEditingItem(item);
		setTargetGroupId(item.groupId || item.group_id || 0);
		setItemModalOpen(true);
	};
	const handleGroupSubmit = function() {
		var _ref11 = _asyncToGenerator(function* (formData) {
			if (!currentSection) return;
			if (isCodeExists(formData.code, editingGroup === null || editingGroup === void 0 ? void 0 : editingGroup.id)) return;
			try {
				if (modalType === "add") {
					const newSort = (groupList.length > 0 ? Math.max(...groupList.map((group) => group.sort || 0)) : 0) + 1;
					yield handleCreateGroup({
						section_code: currentSection.code,
						code: formData.code,
						title: formData.title,
						description: formData === null || formData === void 0 ? void 0 : formData.description,
						sort: newSort
					});
				} else {
					if (!(editingGroup === null || editingGroup === void 0 ? void 0 : editingGroup.id)) {
						console.error("No editing group ID found");
						return;
					}
					yield handleUpdateGroup({
						id: editingGroup.id,
						code: formData.code,
						title: formData.title,
						description: formData === null || formData === void 0 ? void 0 : formData.description
					});
				}
				setGroupModalOpen(false);
			} catch (error) {
				console.error("Failed to submit group form:", error);
			}
		});
		return function handleGroupSubmit(_x13) {
			return _ref11.apply(this, arguments);
		};
	}();
	const handleItemSubmit = function() {
		var _ref12 = _asyncToGenerator(function* (formData) {
			if (!currentSection) return;
			if (isKeyExists(formData.key, editingItem === null || editingItem === void 0 ? void 0 : editingItem.id)) return;
			let processedDefaultValue = formData.default;
			if (formData.default !== void 0 && formData.default !== null && formData.default !== "") {
				const validation = validateDefaultValue(formData.fieldType, formData.default);
				if (!validation.isValid) {
					message.error(`默认值验证失败: ${validation.error}`);
					return;
				}
				processedDefaultValue = parseDefaultValue(formData.fieldType, formData.default);
			} else processedDefaultValue = null;
			try {
				if (modalType === "add") {
					const targetGroup = groupList.find((group) => group.id === targetGroupId);
					const newSort = (targetGroup && targetGroup.items && targetGroup.items.length > 0 ? Math.max(...targetGroup.items.map((item) => item.sort || 0)) : 0) + 1;
					yield handleCreateItem({
						section_code: currentSection.code,
						group_id: targetGroupId,
						code: formData.key,
						title: formData.name,
						description: formData.description,
						type: formData.fieldType,
						interface: formData.interfaceType,
						default: processedDefaultValue,
						scopes: formData.scopes,
						schema: (formData === null || formData === void 0 ? void 0 : formData.schema) || void 0,
						sort: newSort
					});
				} else {
					if (!(editingItem === null || editingItem === void 0 ? void 0 : editingItem.id)) {
						console.error("No editing item ID found");
						return;
					}
					yield handleUpdateItem({
						id: editingItem.id,
						section_code: currentSection.code,
						group_id: targetGroupId,
						code: formData.key,
						title: formData.name,
						description: formData.description,
						type: formData.fieldType,
						interface: formData.interfaceType,
						default: processedDefaultValue,
						scopes: formData.scopes,
						schema: (formData === null || formData === void 0 ? void 0 : formData.schema) || void 0,
						sort: editingItem.sort
					});
				}
				setItemModalOpen(false);
			} catch (error) {
				console.error("Failed to submit item form:", error);
			}
		});
		return function handleItemSubmit(_x14) {
			return _ref12.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ React.createElement("div", {
		className: `pisell-settings-registry ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-sidebar" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-sidebar-header" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-sidebar-title" }, locales.getText("registry.sections.title"))), /* @__PURE__ */ React.createElement(SectionList, {
		sections: localSections,
		selectedSectionId: currentSectionId,
		onSectionSelect: handleSectionSelect,
		loading,
		hasMore,
		onLoadMore: handleLoadMore
	})), /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-content" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-content-header" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-content-title" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-settings-registry-content-main-title" }, locales.getText("registry.title"))), /* @__PURE__ */ React.createElement(Button$1, {
		type: "primary",
		icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
		onClick: handleAddGroup,
		disabled: !currentSection
	}, locales.getText("registry.action.add.group"))), /* @__PURE__ */ React.createElement(SettingsTable, {
		section: currentSection,
		groupList,
		groupLoading,
		onDataChange: handleDataChange,
		onEditGroup: handleEditGroup,
		onDeleteGroup: (groupId) => handleDeleteGroup({ id: groupId }),
		onAddItem: handleAddItem,
		onEditItem: handleEditItem,
		onDeleteItem: (itemId) => handleDeleteItem({ id: itemId }),
		onGroupReorder: handleGroupReorder,
		onItemMove: handleItemMove
	})), /* @__PURE__ */ React.createElement(GroupModal, {
		open: groupModalOpen,
		type: modalType,
		data: editingGroup,
		onOk: handleGroupSubmit,
		onCancel: () => setGroupModalOpen(false)
	}), /* @__PURE__ */ React.createElement(ItemModal, {
		open: itemModalOpen,
		type: modalType,
		data: editingItem,
		section: currentSection,
		onOk: handleItemSubmit,
		onCancel: () => setItemModalOpen(false),
		scene
	}));
};
//#endregion
export { Registry as default };
