const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_index = require("../../../utils/index.js");
const require_SectionList = require("./components/SectionList.js");
const require_SettingsTable = require("./components/SettingsTable.js");
const require_locales = require("./locales.js");
const require_GroupModal = require("./components/GroupModal.js");
const require_typeValidation = require("./utils/typeValidation.js");
const require_ItemModal = require("./components/ItemModal.js");
const require_services = require("./services.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let _ant_design_icons = require("@ant-design/icons");
require("./index.less");
//#region src/components/systemSettings/registry/index.tsx
const Registry = ({ className, style, sections = [], selectedSectionId, onSectionSelect, onDataChange, scene }) => {
	var _context$engine2;
	const context = require_useEngineContext.default();
	const { request: request$1 } = context.appHelper.utils;
	const [localSections, setLocalSections] = (0, react.useState)(sections);
	const [currentSectionId, setCurrentSectionId] = (0, react.useState)(selectedSectionId || (sections.length > 0 ? sections[0].id : 0));
	require_index.request.setRequest(request$1);
	const [loading, setLoading] = (0, react.useState)(false);
	const [hasMore, setHasMore] = (0, react.useState)(true);
	const [currentPage, setCurrentPage] = (0, react.useState)(1);
	const [pageSize] = (0, react.useState)(20);
	const [isInitialLoad, setIsInitialLoad] = (0, react.useState)(true);
	const [groupList, setGroupList] = (0, react.useState)([]);
	const [groupLoading, setGroupLoading] = (0, react.useState)(false);
	const onDataChangeRef = (0, react.useRef)(onDataChange);
	const lastLoadedSectionCodeRef = (0, react.useRef)("");
	onDataChangeRef.current = onDataChange;
	const [groupModalOpen, setGroupModalOpen] = (0, react.useState)(false);
	const [itemModalOpen, setItemModalOpen] = (0, react.useState)(false);
	const [modalType, setModalType] = (0, react.useState)("add");
	const [editingGroup, setEditingGroup] = (0, react.useState)();
	const [editingItem, setEditingItem] = (0, react.useState)();
	const [targetGroupId, setTargetGroupId] = (0, react.useState)(0);
	const handleCreateGroup = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.createGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.locales.getText("registry.message.save.success"));
				return response;
			} catch (error) {
				antd.message.error(_pisell_utils.locales.getText("registry.message.create.group.error"));
				throw error;
			}
		});
		return function handleCreateGroup(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const handleUpdateGroup = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.updateGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.deleteGroup(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.createItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.updateItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			try {
				const response = yield require_services.deleteItem(request$1, params, scene);
				if (currentSectionId) {
					const currentSection = localSections.find((s) => s.id === currentSectionId);
					if (currentSection) yield loadGroupData(currentSection.code, true);
				}
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._asyncToGenerator(function* (groupIds) {
			try {
				const currentSection = localSections.find((s) => s.id === currentSectionId);
				if (!currentSection) throw new Error("Current section not found");
				yield require_services.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 ? require_objectSpread2._objectSpread2({}, group) : null;
				}).filter(Boolean));
				antd.message.success(_pisell_utils.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 = require_asyncToGenerator._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 require_services.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);
				antd.message.success(_pisell_utils.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 = (0, react.useCallback)(function() {
		var _ref9 = require_asyncToGenerator._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 require_services.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 = (0, react.useCallback)(function() {
		var _ref10 = require_asyncToGenerator._asyncToGenerator(function* (page, isLoadMore = false) {
			if (loading) return;
			setLoading(true);
			try {
				const response = yield require_services.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 = (0, react.useCallback)(() => {
		if (!hasMore || loading) return;
		const nextPage = currentPage + 1;
		setCurrentPage(nextPage);
		loadSectionData(nextPage, true);
	}, [
		hasMore,
		loading,
		currentPage
	]);
	(0, react.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";
		_pisell_utils.locales.init(require_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]);
	(0, react.useEffect)(() => {
		if (isInitialLoad) {
			setIsInitialLoad(false);
			loadSectionData(1, false);
		}
	}, [isInitialLoad]);
	(0, react.useEffect)(() => {
		if (!isInitialLoad && sections && sections.length > 0) setLocalSections(sections);
	}, [sections, isInitialLoad]);
	(0, react.useEffect)(() => {
		if (selectedSectionId) setCurrentSectionId(selectedSectionId);
	}, [selectedSectionId]);
	(0, react.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 = require_asyncToGenerator._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 = require_asyncToGenerator._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 = require_typeValidation.validateDefaultValue(formData.fieldType, formData.default);
				if (!validation.isValid) {
					antd.message.error(`默认值验证失败: ${validation.error}`);
					return;
				}
				processedDefaultValue = require_typeValidation.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.default.createElement("div", {
		className: `pisell-settings-registry ${className || ""}`,
		style
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-sidebar" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-sidebar-header" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-sidebar-title" }, _pisell_utils.locales.getText("registry.sections.title"))), /* @__PURE__ */ react.default.createElement(require_SectionList.default, {
		sections: localSections,
		selectedSectionId: currentSectionId,
		onSectionSelect: handleSectionSelect,
		loading,
		hasMore,
		onLoadMore: handleLoadMore
	})), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-content" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-content-header" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-content-title" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-settings-registry-content-main-title" }, _pisell_utils.locales.getText("registry.title"))), /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		type: "primary",
		icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.PlusOutlined, null),
		onClick: handleAddGroup,
		disabled: !currentSection
	}, _pisell_utils.locales.getText("registry.action.add.group"))), /* @__PURE__ */ react.default.createElement(require_SettingsTable.default, {
		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.default.createElement(require_GroupModal.default, {
		open: groupModalOpen,
		type: modalType,
		data: editingGroup,
		onOk: handleGroupSubmit,
		onCancel: () => setGroupModalOpen(false)
	}), /* @__PURE__ */ react.default.createElement(require_ItemModal.default, {
		open: itemModalOpen,
		type: modalType,
		data: editingItem,
		section: currentSection,
		onOk: handleItemSubmit,
		onCancel: () => setItemModalOpen(false),
		scene
	}));
};
//#endregion
exports.default = Registry;
