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/components/SettingsTable.tsx
var SettingsTable_exports = {};
__export(SettingsTable_exports, {
  default: () => SettingsTable_default
});
module.exports = __toCommonJS(SettingsTable_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_core = require("@dnd-kit/core");
var import_sortable = require("@dnd-kit/sortable");
var import_core2 = require("@dnd-kit/core");
var import_utilities = require("@dnd-kit/utilities");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var AntdTag = import_antd.Tag;
var AntdSpace = import_antd.Space;
var 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"
};
var 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 || "";
};
var DragContext = import_react.default.createContext({});
var DragHandle = ({ record, isGroup, isExpanded, onExpand, currentLocale }) => {
  const { attributes, listeners } = import_react.default.useContext(DragContext);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-settings-registry-table-title",
      style: { paddingLeft: record.level * 24, display: "flex", alignItems: "center" }
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "drag-handle",
        ...attributes || {},
        ...listeners || {},
        style: {
          cursor: "grab",
          marginRight: 8,
          color: "#999",
          fontSize: "12px",
          display: "flex",
          alignItems: "center"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_icons.HolderOutlined, null)
    ),
    isGroup && /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "text",
        size: "small",
        icon: isExpanded ? /* @__PURE__ */ import_react.default.createElement(import_icons.CaretDownOutlined, null) : /* @__PURE__ */ import_react.default.createElement(import_icons.CaretRightOutlined, null),
        onClick: () => onExpand(record.key),
        style: { marginRight: 8 }
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(AntdTag, { color: isGroup ? "blue" : "green" }, import_utils.locales.getText(isGroup ? "registry.level.group" : "registry.level.item")),
    /* @__PURE__ */ import_react.default.createElement("span", { style: { marginLeft: 8 } }, getMultiLanguageText(record.data.title || record.data.name, currentLocale))
  );
};
var DraggableRow = ({ record, children, className, style, ...props }) => {
  if (!record || !record.key) {
    return /* @__PURE__ */ import_react.default.createElement("tr", { className, style, ...props }, children);
  }
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = (0, import_sortable.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 = (0, import_core2.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 = {
    transform: import_utilities.CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.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__ */ import_react.default.createElement(DragContext.Provider, { value: { attributes, listeners } }, /* @__PURE__ */ import_react.default.createElement(
    "tr",
    {
      ref: combinedRef,
      style: dragStyle,
      className: `${className} ${isDragging ? "dragging" : ""} ${record.type === "group" ? "group-row" : ""} ${dropResult.isOver && record.type === "group" ? "drop-over" : ""}`,
      ...props
    },
    children
  ));
};
var SettingsTable = ({
  section,
  groupList = [],
  groupLoading = false,
  onDataChange,
  onEditGroup,
  onDeleteGroup,
  onAddItem,
  onEditItem,
  onDeleteItem,
  onGroupReorder,
  onItemMove
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const [expandedKeys, setExpandedKeys] = (0, import_react.useState)([]);
  const [activeId, setActiveId] = (0, import_react.useState)(null);
  const [dragOverZone, setDragOverZone] = (0, import_react.useState)(null);
  const sensors = (0, import_core.useSensors)(
    (0, import_core.useSensor)(import_core.PointerSensor, {
      activationConstraint: {
        distance: 8
      }
    })
  );
  const virtualDropZones = (0, import_react.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 _a2;
    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 = (0, import_core.rectIntersection)({
        ...args,
        droppableContainers: virtualContainers
      });
      if (virtualCollisions && virtualCollisions.length > 0) {
        console.log("虚拟容器碰撞检测:", virtualCollisions[0].id);
        return virtualCollisions;
      }
    }
    const standardCollisions = (0, import_core.closestCenter)(args);
    console.log("标准碰撞检测:", (_a2 = standardCollisions == null ? void 0 : standardCollisions[0]) == null ? void 0 : _a2.id);
    return standardCollisions;
  };
  const currentLocale = ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || localStorage.getItem("umi_locale") || "zh-CN";
  const treeData = (0, import_react.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 ? 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]);
  import_react.default.useEffect(() => {
    if (groupList && groupList.length > 0) {
      const defaultExpanded = groupList.filter((group) => group.expanded !== false).map((group) => `group-${group.id}`);
      setExpandedKeys(defaultExpanded);
    }
  }, [groupList]);
  const flattenData = (0, import_react.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;
    const zone = virtualDropZones.find((z) => z.id === overId);
    if (zone) {
      setDragOverZone(overId);
    } else {
      setDragOverZone(null);
    }
  };
  const handleDragEnd = (event) => {
    var _a2, _b2;
    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 ? void 0 : onGroupReorder(groupIds);
        }
        return;
      }
    }
    if (activeRecord.type === "item") {
      const targetZone = virtualDropZones.find((z) => z.id === overId);
      if (targetZone && targetZone.type === "item-container") {
        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;
        const currentGroupId = currentGroup.id;
        if (currentGroupId === targetGroupId) return;
        const targetGroup = groupList.find((g) => g.id === targetGroupId);
        const newOrder = ((_a2 = targetGroup == null ? void 0 : targetGroup.items) == null ? void 0 : _a2.length) || 0;
        console.log("调用设置项移动接口 (虚拟容器):", { activeItemId, targetGroupId, newOrder });
        onItemMove == null ? void 0 : onItemMove(activeItemId, targetGroupId, newOrder);
        return;
      }
    }
    if (overData && overData.record) {
      const overRecord = overData.record;
      if (activeRecord.type === "item" && overRecord.type === "group") {
        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;
        const currentGroupId = currentGroup.id;
        if (currentGroupId === targetGroupId) return;
        const targetGroup = groupList.find((g) => g.id === targetGroupId);
        const newOrder = ((_b2 = targetGroup == null ? void 0 : targetGroup.items) == null ? void 0 : _b2.length) || 0;
        console.log("调用设置项移动接口 (直接拖放到组):", { activeItemId, targetGroupId, newOrder });
        onItemMove == null ? 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 ? 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 ? void 0 : onItemMove(activeItemId, overGroup.id, newOrder);
        }
      }
    }
  };
  const handleDelete = (record) => {
    if (record.type === "group") {
      const hasItems = record.data.items && record.data.items.length > 0;
      if (hasItems) {
        import_antd.Modal.warning({
          title: import_utils.locales.getText("registry.modal.delete.group.hasItems.title"),
          content: import_utils.locales.getText("registry.modal.delete.group.hasItems.content")
        });
        return;
      }
    }
    import_antd.Modal.confirm({
      title: import_utils.locales.getText("registry.modal.delete.title"),
      content: import_utils.locales.getText(
        record.type === "group" ? "registry.modal.delete.group.content" : "registry.modal.delete.item.content"
      ),
      onOk: () => {
        if (record.type === "group") {
          onDeleteGroup == null ? void 0 : onDeleteGroup(record.data.id);
        } else {
          onDeleteItem == null ? void 0 : onDeleteItem(record.data.id);
        }
      }
    });
  };
  const activeType = (0, import_react.useMemo)(() => {
    if (!activeId) return void 0;
    const activeItem = flattenData.find((item) => item.key === activeId);
    return activeItem == null ? void 0 : activeItem.type;
  }, [activeId, flattenData]);
  const columns = [
    {
      title: import_utils.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__ */ import_react.default.createElement(
          DragHandle,
          {
            record,
            isGroup,
            isExpanded,
            onExpand: handleExpand,
            currentLocale
          }
        );
      }
    },
    {
      title: import_utils.locales.getText("registry.table.key"),
      dataIndex: "key",
      key: "key",
      width: "25%",
      render: (_, record) => {
        if (record.type === "group") {
          return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-settings-registry-code" }, record.data.code);
        }
        return /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-settings-registry-key" }, record.data.key || record.data.code);
      }
    },
    {
      title: import_utils.locales.getText("registry.table.scopes"),
      dataIndex: "scopes",
      key: "scopes",
      width: "25%",
      render: (_, record) => {
        if (record.type === "item" && record.data.scopes) {
          return /* @__PURE__ */ import_react.default.createElement(AntdSpace, { wrap: true }, record.data.scopes.map((scope) => /* @__PURE__ */ import_react.default.createElement(AntdTag, { key: scope, size: "small" }, import_utils.locales.getText(scopeKeyMapping[scope] || `registry.scope.${scope}`))));
        }
        return "-";
      }
    },
    {
      title: import_utils.locales.getText("registry.table.actions"),
      key: "actions",
      width: "20%",
      render: (_, record) => {
        const isGroup = record.type === "group";
        return /* @__PURE__ */ import_react.default.createElement(AntdSpace, { size: "small" }, isGroup && /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            size: "small",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
            onClick: () => onAddItem == null ? void 0 : onAddItem(record.data.id),
            title: import_utils.locales.getText("registry.action.add.item")
          }
        ), /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            size: "small",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.EditOutlined, null),
            onClick: () => {
              if (isGroup) {
                onEditGroup == null ? void 0 : onEditGroup(record.data);
              } else {
                onEditItem == null ? void 0 : onEditItem(record.data);
              }
            },
            title: import_utils.locales.getText("registry.action.edit")
          }
        ), /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "text",
            size: "small",
            icon: /* @__PURE__ */ import_react.default.createElement(import_icons.DeleteOutlined, null),
            danger: true,
            onClick: () => handleDelete(record),
            title: import_utils.locales.getText("registry.action.delete")
          }
        ));
      }
    }
  ];
  if (!section) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-table-empty" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Empty,
      {
        description: import_utils.locales.getText("registry.message.select.section"),
        image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE
      }
    ));
  }
  if (groupLoading) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-table-loading", style: { textAlign: "center", padding: "50px" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "large" }), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: "16px" } }, import_utils.locales.getText("registry.message.loading.groups")));
  }
  if (flattenData.length === 0) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-table-empty" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Empty,
      {
        description: import_utils.locales.getText("registry.message.no.settings"),
        image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE
      }
    ));
  }
  const sortableIds = flattenData.map((item) => item.key);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-table" }, /* @__PURE__ */ import_react.default.createElement(
    import_core.DndContext,
    {
      sensors,
      collisionDetection: customCollisionDetection,
      onDragStart: handleDragStart,
      onDragOver: handleDragOver,
      onDragEnd: handleDragEnd
    },
    /* @__PURE__ */ import_react.default.createElement(import_sortable.SortableContext, { items: sortableIds, strategy: import_sortable.verticalListSortingStrategy }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.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__ */ import_react.default.createElement("tr", { ...props });
              }
              return /* @__PURE__ */ import_react.default.createElement(DraggableRow, { ...props, record });
            }
          }
        }
      }
    )),
    /* @__PURE__ */ import_react.default.createElement(import_core.DragOverlay, null, activeId ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-drag-overlay" }, (() => {
      const activeItem = flattenData.find((item) => item.key === activeId);
      if (!activeItem) return null;
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-settings-registry-drag-item" }, /* @__PURE__ */ import_react.default.createElement(AntdTag, { color: activeItem.type === "group" ? "blue" : "green" }, import_utils.locales.getText(activeItem.type === "group" ? "registry.level.group" : "registry.level.item")), /* @__PURE__ */ import_react.default.createElement("span", null, getMultiLanguageText(activeItem.data.title || activeItem.data.name, currentLocale)));
    })()) : null)
  ));
};
var SettingsTable_default = SettingsTable;
