var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/systemSettings/registry/index.tsx
var registry_exports = {};
__export(registry_exports, {
  default: () => registry_default
});
module.exports = __toCommonJS(registry_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_icons = require("@ant-design/icons");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_components = require("./components");
var import_services = require("./services");
var import_typeValidation = require("./utils/typeValidation");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var import_utils2 = require("../../../utils");
var Registry = ({
  className,
  style,
  sections = [],
  selectedSectionId,
  onSectionSelect,
  onDataChange
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const { request } = context.appHelper.utils;
  const [localSections, setLocalSections] = (0, import_react.useState)(sections);
  const [currentSectionId, setCurrentSectionId] = (0, import_react.useState)(
    selectedSectionId || (sections.length > 0 ? sections[0].id : 0)
  );
  import_utils2.request.setRequest(request);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [hasMore, setHasMore] = (0, import_react.useState)(true);
  const [currentPage, setCurrentPage] = (0, import_react.useState)(1);
  const [pageSize] = (0, import_react.useState)(20);
  const [isInitialLoad, setIsInitialLoad] = (0, import_react.useState)(true);
  const [groupList, setGroupList] = (0, import_react.useState)([]);
  const [groupLoading, setGroupLoading] = (0, import_react.useState)(false);
  const onDataChangeRef = (0, import_react.useRef)(onDataChange);
  const lastLoadedSectionCodeRef = (0, import_react.useRef)("");
  onDataChangeRef.current = onDataChange;
  const [groupModalOpen, setGroupModalOpen] = (0, import_react.useState)(false);
  const [itemModalOpen, setItemModalOpen] = (0, import_react.useState)(false);
  const [modalType, setModalType] = (0, import_react.useState)("add");
  const [editingGroup, setEditingGroup] = (0, import_react.useState)();
  const [editingItem, setEditingItem] = (0, import_react.useState)();
  const [targetGroupId, setTargetGroupId] = (0, import_react.useState)(0);
  const handleCreateGroup = async (params) => {
    try {
      const response = await (0, import_services.createGroup)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.save.success"));
      return response;
    } catch (error) {
      import_antd.message.error(import_utils.locales.getText("registry.message.create.group.error"));
      throw error;
    }
  };
  const handleUpdateGroup = async (params) => {
    try {
      const response = await (0, import_services.updateGroup)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.save.success"));
      return response;
    } catch (error) {
      throw error;
    }
  };
  const handleDeleteGroup = async (params) => {
    try {
      const response = await (0, import_services.deleteGroup)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.delete.success"));
      return response;
    } catch (error) {
      throw error;
    }
  };
  const handleCreateItem = async (params) => {
    try {
      const response = await (0, import_services.createItem)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.save.success"));
      return response;
    } catch (error) {
      throw error;
    }
  };
  const handleUpdateItem = async (params) => {
    try {
      const response = await (0, import_services.updateItem)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.save.success"));
      return response;
    } catch (error) {
      throw error;
    }
  };
  const handleDeleteItem = async (params) => {
    try {
      const response = await (0, import_services.deleteItem)(request, params);
      if (currentSectionId) {
        const currentSection2 = localSections.find((s) => s.id === currentSectionId);
        if (currentSection2) {
          await loadGroupData(currentSection2.code, true);
        }
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.delete.success"));
      return response;
    } catch (error) {
      console.error("Failed to delete item:", error);
      throw error;
    }
  };
  const handleGroupReorder = async (groupIds) => {
    try {
      const currentSection2 = localSections.find((s) => s.id === currentSectionId);
      if (!currentSection2) {
        throw new Error("Current section not found");
      }
      await (0, import_services.sortGroups)(request, {
        section_code: currentSection2.code,
        group_ids: groupIds
      });
      const reorderedGroups = groupIds.map((id) => {
        const group = groupList.find((g) => g.id === id);
        return group ? { ...group } : null;
      }).filter(Boolean);
      setGroupList(reorderedGroups);
      import_antd.message.success(import_utils.locales.getText("registry.message.reorder.success"));
    } catch (error) {
      console.error("Failed to reorder groups:", error);
      const currentSection2 = localSections.find((s) => s.id === currentSectionId);
      if (currentSection2) {
        await loadGroupData(currentSection2.code, true);
      }
    }
  };
  const handleItemMove = async (itemId, targetGroupId2, newOrder) => {
    try {
      const targetGroup = groupList.find((g) => g.id === targetGroupId2);
      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 allItems = groupList.reduce((acc, g) => [...acc, ...g.items], []);
        const movedItem = allItems.find((item) => item.id === itemId);
        if (movedItem) {
          targetGroupItems.splice(newOrder, 0, movedItem);
        }
      }
      const sortedItemIds = targetGroupItems.map((item) => item.id);
      await (0, import_services.sortItems)(request, {
        id: itemId,
        group_id: targetGroupId2.toString(),
        item_ids: sortedItemIds
      });
      const currentSection2 = localSections.find((s) => s.id === currentSectionId);
      if (currentSection2) {
        await loadGroupData(currentSection2.code, true);
      }
      import_antd.message.success(import_utils.locales.getText("registry.message.move.success"));
    } catch (error) {
      console.error("Failed to move item:", error);
      const currentSection2 = localSections.find((s) => s.id === currentSectionId);
      if (currentSection2) {
        await loadGroupData(currentSection2.code, true);
      }
    }
  };
  const loadGroupData = (0, import_react.useCallback)(async (sectionCode, forceRefresh = false) => {
    if (groupLoading || !forceRefresh && lastLoadedSectionCodeRef.current === sectionCode) {
      return;
    }
    lastLoadedSectionCodeRef.current = sectionCode;
    setGroupLoading(true);
    try {
      const response = await (0, import_services.getGroupList)(request, {
        page: 1,
        pageSize: 100,
        // 获取所有组数据
        filter: { section_code: sectionCode }
      });
      const newGroups = response.data || [];
      setGroupList(newGroups);
    } catch (error) {
      console.error("Failed to load group data:", error);
      setGroupList([]);
    } finally {
      setGroupLoading(false);
    }
  }, []);
  const loadSectionData = (0, import_react.useCallback)(async (page, isLoadMore = false) => {
    var _a2;
    if (loading) return;
    setLoading(true);
    try {
      const response = await (0, import_services.getSectionList)(request, {
        page,
        pageSize,
        filter: {}
      });
      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 _a3;
          const updatedSections = [...prev, ...newSections];
          (_a3 = onDataChangeRef.current) == null ? void 0 : _a3.call(onDataChangeRef, updatedSections);
          return updatedSections;
        });
      } else {
        (_a2 = onDataChangeRef.current) == null ? void 0 : _a2.call(onDataChangeRef, newSections);
      }
    } catch (error) {
      console.error("Failed to load section data:", error);
    } finally {
      setLoading(false);
    }
  }, [loading, pageSize, currentSectionId]);
  const handleLoadMore = (0, import_react.useCallback)(() => {
    if (!hasMore || loading) return;
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    loadSectionData(nextPage, true);
  }, [hasMore, loading, currentPage]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    const currentLocale = ((_b2 = (_a2 = context == null ? void 0 : context.engine) == null ? void 0 : _a2.props) == null ? void 0 : _b2.locale) || localStorage.getItem("umi_locale") || "zh-CN";
    import_utils.locales.init(import_locales.default, currentLocale);
  }, [(_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale]);
  (0, import_react.useEffect)(() => {
    if (isInitialLoad) {
      setIsInitialLoad(false);
      loadSectionData(1, false);
    }
  }, [isInitialLoad]);
  (0, import_react.useEffect)(() => {
    if (!isInitialLoad && sections && sections.length > 0) {
      setLocalSections(sections);
    }
  }, [sections, isInitialLoad]);
  (0, import_react.useEffect)(() => {
    if (selectedSectionId) {
      setCurrentSectionId(selectedSectionId);
    }
  }, [selectedSectionId]);
  (0, import_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 ? void 0 : onSectionSelect(sectionId);
  };
  const handleDataChange = (updatedSection) => {
    const newSections = localSections.map(
      (section) => section.id === updatedSection.id ? updatedSection : section
    );
    setLocalSections(newSections);
    onDataChange == null ? 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 = async (formData) => {
    if (!currentSection) return;
    if (isCodeExists(formData.code, editingGroup == null ? void 0 : editingGroup.id)) {
      return;
    }
    try {
      if (modalType === "add") {
        const maxSort = groupList.length > 0 ? Math.max(...groupList.map((group) => group.sort || 0)) : 0;
        const newSort = maxSort + 1;
        await handleCreateGroup({
          section_code: currentSection.code,
          code: formData.code,
          title: formData.title,
          description: formData == null ? void 0 : formData.description,
          sort: newSort
        });
      } else {
        if (!(editingGroup == null ? void 0 : editingGroup.id)) {
          console.error("No editing group ID found");
          return;
        }
        await handleUpdateGroup({
          id: editingGroup.id,
          code: formData.code,
          title: formData.title,
          description: formData == null ? void 0 : formData.description
        });
      }
      setGroupModalOpen(false);
    } catch (error) {
      console.error("Failed to submit group form:", error);
    }
  };
  const handleItemSubmit = async (formData) => {
    if (!currentSection) return;
    if (isKeyExists(formData.key, editingItem == null ? void 0 : editingItem.id)) {
      return;
    }
    let processedDefaultValue = formData.default;
    if (formData.default !== void 0 && formData.default !== null && formData.default !== "") {
      const validation = (0, import_typeValidation.validateDefaultValue)(formData.fieldType, formData.default);
      if (!validation.isValid) {
        import_antd.message.error(`默认值验证失败: ${validation.error}`);
        return;
      }
      processedDefaultValue = (0, import_typeValidation.parseDefaultValue)(formData.fieldType, formData.default);
    } else {
      processedDefaultValue = null;
    }
    try {
      if (modalType === "add") {
        const targetGroup = groupList.find((group) => group.id === targetGroupId);
        const maxSort = targetGroup && targetGroup.items && targetGroup.items.length > 0 ? Math.max(...targetGroup.items.map((item) => item.sort || 0)) : 0;
        const newSort = maxSort + 1;
        await 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.uiSchema ? (() => {
          //     try {
          //         return JSON.parse(formData.uiSchema);
          //     } catch (e) {
          //         console.warn('Invalid JSON in uiSchema:', e);
          //         return formData.uiSchema;
          //     }
          // })() : undefined,
          schema: (formData == null ? void 0 : formData.schema) || void 0,
          sort: newSort
        });
      } else {
        if (!(editingItem == null ? void 0 : editingItem.id)) {
          console.error("No editing item ID found");
          return;
        }
        await 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.uiSchema ? (() => {
          //     try {
          //         return JSON.parse(formData.uiSchema);
          //     } catch (e) {
          //         console.warn('Invalid JSON in uiSchema:', e);
          //         return formData.uiSchema;
          //     }
          // })() : undefined,
          schema: (formData == null ? void 0 : formData.schema) || void 0,
          sort: editingItem.sort
        });
      }
      setItemModalOpen(false);
    } catch (error) {
      console.error("Failed to submit item form:", error);
    }
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: `pisell-settings-registry ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-sidebar" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-sidebar-header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-sidebar-title" }, import_utils.locales.getText("registry.sections.title"))), /* @__PURE__ */ import_react.default.createElement(
    import_components.SectionList,
    {
      sections: localSections,
      selectedSectionId: currentSectionId,
      onSectionSelect: handleSectionSelect,
      loading,
      hasMore,
      onLoadMore: handleLoadMore
    }
  )), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-content-header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-content-title" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-content-main-title" }, import_utils.locales.getText("registry.title"))), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      type: "primary",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
      onClick: handleAddGroup,
      disabled: !currentSection
    },
    import_utils.locales.getText("registry.action.add.group")
  )), /* @__PURE__ */ import_react.default.createElement(
    import_components.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__ */ import_react.default.createElement(
    import_components.GroupModal,
    {
      open: groupModalOpen,
      type: modalType,
      data: editingGroup,
      onOk: handleGroupSubmit,
      onCancel: () => setGroupModalOpen(false)
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_components.ItemModal,
    {
      open: itemModalOpen,
      type: modalType,
      data: editingItem,
      section: currentSection,
      onOk: handleItemSubmit,
      onCancel: () => setItemModalOpen(false)
    }
  ));
};
var registry_default = Registry;
