function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["record", "children", "className", "style"];
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
import React, { useState, useMemo } from 'react';
import { Table, Tag, Space, Empty, Modal, Spin } from 'antd';

// 临时类型修复
var AntdTag = Tag;
var AntdSpace = Space;
import { Button } from '@pisell/materials';
import { PlusOutlined, EditOutlined, DeleteOutlined, CaretRightOutlined, CaretDownOutlined, HolderOutlined } from '@ant-design/icons';
import { locales } from '@pisell/utils';
import { DndContext, PointerSensor, useSensor, useSensors, DragOverlay, closestCenter, rectIntersection } from '@dnd-kit/core';
import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import useEngineContext from "../../../../hooks/useEngineContext";
// 作用域值到 locales key 的映射（与 ItemModal 保持一致）
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',
  'profile': 'registry.scope.profile',
  'instance': 'registry.scope.instance'
};

// 工具函数：获取多语言文本的显示值
var getMultiLanguageText = function getMultiLanguageText(text, currentLocale) {
  if (typeof text === 'string') {
    return text;
  }

  // 获取当前语言，优先使用传入的 currentLocale
  var currentLang = currentLocale || localStorage.getItem('umi_locale') || 'zh-CN';

  // 根据当前语言返回对应的文本，如果没有则使用 original
  if (text[currentLang]) {
    return text[currentLang];
  }
  return text.original || '';
};

// 虚拟拖动容器类型

// 可拖拽行组件

// 创建一个 Context 来传递拖拽属性
var DragContext = /*#__PURE__*/React.createContext({});

// 拖拽句柄组件
var DragHandle = function DragHandle(_ref) {
  var record = _ref.record,
    isGroup = _ref.isGroup,
    isExpanded = _ref.isExpanded,
    onExpand = _ref.onExpand,
    currentLocale = _ref.currentLocale;
  var _React$useContext = React.useContext(DragContext),
    attributes = _React$useContext.attributes,
    listeners = _React$useContext.listeners;
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-settings-registry-table-title",
    style: {
      paddingLeft: record.level * 24,
      display: 'flex',
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement("div", _extends({
    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, {
    type: "text",
    size: "small",
    icon: isExpanded ? /*#__PURE__*/React.createElement(CaretDownOutlined, null) : /*#__PURE__*/React.createElement(CaretRightOutlined, null),
    onClick: function onClick() {
      return 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)));
};

// 移除了 DroppableVirtualContainer 组件，拖放逻辑已集成到行级别

var DraggableRow = function DraggableRow(_ref2) {
  var record = _ref2.record,
    children = _ref2.children,
    className = _ref2.className,
    style = _ref2.style,
    props = _objectWithoutProperties(_ref2, _excluded);
  // 如果没有有效的 record，返回普通的 tr
  if (!record || !record.key) {
    return /*#__PURE__*/React.createElement("tr", _extends({
      className: className,
      style: style
    }, props), children);
  }

  // 普通的可拖拽行
  var _useSortable = useSortable({
      id: record.key,
      data: {
        type: record.type,
        record: record,
        groupId: record.type === 'item' ? record.data.groupId || record.data.group_id : record.data.id
      }
    }),
    attributes = _useSortable.attributes,
    listeners = _useSortable.listeners,
    setNodeRef = _useSortable.setNodeRef,
    transform = _useSortable.transform,
    transition = _useSortable.transition,
    isDragging = _useSortable.isDragging;

  // 为组行添加拖放区域（用于接受设置项）
  var dropResult = useDroppable({
    id: record.type === 'group' ? "item-container-".concat(record.data.id) : "drop-".concat(record.key),
    data: {
      type: record.type === 'group' ? 'item-container' : 'item',
      groupId: record.type === 'group' ? record.data.id : undefined,
      acceptTypes: record.type === 'group' ? ['item'] : []
    },
    disabled: record.type !== 'group' // 只有组行才能接受拖放
  });
  var dragStyle = _objectSpread(_objectSpread({
    transform: CSS.Transform.toString(transform),
    transition: transition,
    opacity: isDragging ? 0.5 : 1
  }, record.type === 'group' && dropResult.isOver ? {
    backgroundColor: 'rgba(24, 144, 255, 0.05)',
    borderLeft: '3px solid #1890ff'
  } : {}), style);

  // 合并拖拽和拖放的 ref
  var combinedRef = function combinedRef(node) {
    setNodeRef(node);
    dropResult.setNodeRef(node);
  };
  return /*#__PURE__*/React.createElement(DragContext.Provider, {
    value: {
      attributes: attributes,
      listeners: listeners
    }
  }, /*#__PURE__*/React.createElement("tr", _extends({
    ref: combinedRef,
    style: dragStyle,
    className: "".concat(className, " ").concat(isDragging ? 'dragging' : '', " ").concat(record.type === 'group' ? 'group-row' : '', " ").concat(dropResult.isOver && record.type === 'group' ? 'drop-over' : '')
  }, props), children));
};
var SettingsTable = function SettingsTable(_ref3) {
  var _context$engine;
  var section = _ref3.section,
    _ref3$groupList = _ref3.groupList,
    groupList = _ref3$groupList === void 0 ? [] : _ref3$groupList,
    _ref3$groupLoading = _ref3.groupLoading,
    groupLoading = _ref3$groupLoading === void 0 ? false : _ref3$groupLoading,
    onDataChange = _ref3.onDataChange,
    onEditGroup = _ref3.onEditGroup,
    onDeleteGroup = _ref3.onDeleteGroup,
    onAddItem = _ref3.onAddItem,
    onEditItem = _ref3.onEditItem,
    onDeleteItem = _ref3.onDeleteItem,
    onGroupReorder = _ref3.onGroupReorder,
    onItemMove = _ref3.onItemMove;
  var context = useEngineContext();
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    expandedKeys = _useState2[0],
    setExpandedKeys = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    activeId = _useState4[0],
    setActiveId = _useState4[1];
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    dragOverZone = _useState6[0],
    setDragOverZone = _useState6[1];

  // 配置拖拽传感器
  var sensors = useSensors(useSensor(PointerSensor, {
    activationConstraint: {
      distance: 8
    }
  }));

  // 创建虚拟拖动区域
  var virtualDropZones = useMemo(function () {
    var zones = [];

    // 为每个组创建一个组级别的拖动区域（用于组之间的排序）
    groupList.forEach(function (group) {
      zones.push({
        id: "group-zone-".concat(group.id),
        type: 'group',
        groupId: group.id,
        acceptTypes: ['group'],
        key: "group-".concat(group.id)
      });

      // 为每个组创建一个项目容器区域（用于项目的跨组移动）
      zones.push({
        id: "item-container-".concat(group.id),
        type: 'item-container',
        groupId: group.id,
        acceptTypes: ['item'],
        key: "item-".concat(group.id)
      });
    });
    return zones;
  }, [groupList]);

  // 自定义碰撞检测，基于虚拟区域
  var customCollisionDetection = function customCollisionDetection(args) {
    var _standardCollisions$;
    var active = args.active,
      droppableContainers = args.droppableContainers;

    // 首先尝试检测虚拟容器
    var virtualContainers = Array.from(droppableContainers.values()).filter(function (container) {
      var id = container.id;
      return id.startsWith('item-container-') || id.startsWith('group-zone-');
    });
    if (virtualContainers.length > 0) {
      // 对虚拟容器使用矩形相交检测
      var virtualCollisions = rectIntersection(_objectSpread(_objectSpread({}, args), {}, {
        droppableContainers: virtualContainers
      }));
      if (virtualCollisions && virtualCollisions.length > 0) {
        console.log('虚拟容器碰撞检测:', virtualCollisions[0].id);
        return virtualCollisions;
      }
    }

    // 如果没有虚拟容器碰撞，则使用标准的最近中心点检测
    var standardCollisions = closestCenter(args);
    console.log('标准碰撞检测:', standardCollisions === null || standardCollisions === void 0 || (_standardCollisions$ = standardCollisions[0]) === null || _standardCollisions$ === void 0 ? void 0 : _standardCollisions$.id);
    return standardCollisions;
  };

  // 获取当前语言
  var 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';

  // 将组数据转换为树形结构
  var treeData = useMemo(function () {
    if (!groupList || groupList.length === 0) return [];
    var nodes = [];
    groupList.forEach(function (group) {
      var groupNode = {
        key: "group-".concat(group.id),
        type: 'group',
        data: group,
        children: []
      };
      group === null || group === void 0 || group.items.sort(function (a, b) {
        return a.sort - b.sort || a.id - b.id;
      }).forEach(function (item) {
        var itemNode = {
          key: "item-".concat(item.id),
          type: 'item',
          data: item,
          parentKey: groupNode.key
        };
        groupNode.children.push(itemNode);
      });
      nodes.push(groupNode);
    });
    return nodes;
  }, [groupList]);

  // 初始化展开状态
  React.useEffect(function () {
    if (groupList && groupList.length > 0) {
      var defaultExpanded = groupList.filter(function (group) {
        return group.expanded !== false;
      }).map(function (group) {
        return "group-".concat(group.id);
      });
      setExpandedKeys(defaultExpanded);
    }
  }, [groupList]);

  // 扁平化数据用于表格显示，包含虚拟容器
  var flattenData = useMemo(function () {
    var result = [];
    treeData.forEach(function (groupNode, groupIndex) {
      // 添加组行，包装在组级虚拟容器中
      var groupZone = virtualDropZones.find(function (z) {
        return z.id === "group-zone-".concat(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(function (itemNode) {
            result.push({
              key: itemNode.key,
              type: 'item',
              data: itemNode.data,
              level: 1
            });
          });
        }
      }
    });
    return result;
  }, [treeData, expandedKeys, virtualDropZones]);

  // 处理展开/收起
  var handleExpand = function handleExpand(key) {
    setExpandedKeys(function (prev) {
      return prev.includes(key) ? prev.filter(function (k) {
        return k !== key;
      }) : [].concat(_toConsumableArray(prev), [key]);
    });
  };

  // 拖拽开始
  var handleDragStart = function handleDragStart(event) {
    setActiveId(event.active.id);
  };

  // 拖拽悬停
  var handleDragOver = function handleDragOver(event) {
    var active = event.active,
      over = event.over;
    if (!over) {
      setDragOverZone(null);
      return;
    }
    var overId = over.id;

    // 检查是否悬停在虚拟区域上
    var zone = virtualDropZones.find(function (z) {
      return z.id === overId;
    });
    if (zone) {
      setDragOverZone(overId);
    } else {
      setDragOverZone(null);
    }
  };

  // 拖拽结束 - 基于虚拟拖动容器
  var handleDragEnd = function handleDragEnd(event) {
    var active = event.active,
      over = event.over;
    setActiveId(null);
    setDragOverZone(null);
    if (!over || active.id === over.id) return;
    var activeData = active.data.current;
    var overData = over.data.current;
    if (!activeData) return;
    var activeRecord = activeData.record;
    var overId = over.id;

    // 基于虚拟容器的拖拽处理
    console.log('拖拽结束:', {
      activeId: active.id,
      overId: overId,
      activeRecord: activeRecord.type
    });

    // 处理组与组之间的排序（拖拽到组的虚拟容器）
    if (activeRecord.type === 'group') {
      // 查找目标组的虚拟容器
      var targetZone = virtualDropZones.find(function (z) {
        return z.key === overId && z.type === 'group';
      });
      if (targetZone) {
        var activeGroupId = activeRecord.data.id;
        var targetGroupId = targetZone.groupId;
        if (activeGroupId === targetGroupId) return; // 同一个组，不需要移动

        var newGroupOrder = _toConsumableArray(groupList);
        var activeIndex = newGroupOrder.findIndex(function (g) {
          return g.id === activeGroupId;
        });
        var targetIndex = newGroupOrder.findIndex(function (g) {
          return g.id === targetGroupId;
        });
        if (activeIndex !== -1 && targetIndex !== -1) {
          var _newGroupOrder$splice = newGroupOrder.splice(activeIndex, 1),
            _newGroupOrder$splice2 = _slicedToArray(_newGroupOrder$splice, 1),
            movedGroup = _newGroupOrder$splice2[0];
          newGroupOrder.splice(targetIndex, 0, movedGroup);
          var groupIds = newGroupOrder.map(function (g) {
            return g.id;
          });
          console.log('调用组重排序接口 (虚拟容器):', groupIds);
          onGroupReorder === null || onGroupReorder === void 0 || onGroupReorder(groupIds);
        }
        return;
      }
    }

    // 处理设置项拖放到虚拟容器（跨组移动）
    if (activeRecord.type === 'item') {
      // 查找目标虚拟容器
      var _targetZone = virtualDropZones.find(function (z) {
        return z.id === overId;
      });
      if (_targetZone && _targetZone.type === 'item-container') {
        var _targetGroup$items;
        var activeItemId = activeRecord.data.id;
        var _targetGroupId = _targetZone.groupId;

        // 获取当前设置项的原始位置信息
        var currentGroup = groupList.find(function (g) {
          return g.items && g.items.some(function (item) {
            return item.id === activeItemId;
          });
        });
        if (!currentGroup) return;
        var currentGroupId = currentGroup.id;

        // 如果是同一个组，不需要移动
        if (currentGroupId === _targetGroupId) return;

        // 移动到目标组的末尾
        var targetGroup = groupList.find(function (g) {
          return g.id === _targetGroupId;
        });
        var newOrder = (targetGroup === null || targetGroup === void 0 || (_targetGroup$items = targetGroup.items) === null || _targetGroup$items === void 0 ? void 0 : _targetGroup$items.length) || 0;
        console.log('调用设置项移动接口 (虚拟容器):', {
          activeItemId: activeItemId,
          targetGroupId: _targetGroupId,
          newOrder: newOrder
        });
        onItemMove === null || onItemMove === void 0 || onItemMove(activeItemId, _targetGroupId, newOrder);
        return;
      }
    }

    // 如果没有匹配到虚拟容器，则可能是直接拖拽到行上的情况
    if (overData && overData.record) {
      var overRecord = overData.record;

      // 设置项拖放到组行上
      if (activeRecord.type === 'item' && overRecord.type === 'group') {
        var _targetGroup$items2;
        var _activeItemId = activeRecord.data.id;
        var _targetGroupId2 = overRecord.data.id;
        var _currentGroup = groupList.find(function (g) {
          return g.items && g.items.some(function (item) {
            return item.id === _activeItemId;
          });
        });
        if (!_currentGroup) return;
        var _currentGroupId = _currentGroup.id;
        if (_currentGroupId === _targetGroupId2) return;
        var _targetGroup = groupList.find(function (g) {
          return g.id === _targetGroupId2;
        });
        var _newOrder = (_targetGroup === null || _targetGroup === void 0 || (_targetGroup$items2 = _targetGroup.items) === null || _targetGroup$items2 === void 0 ? void 0 : _targetGroup$items2.length) || 0;
        console.log('调用设置项移动接口 (直接拖放到组):', {
          activeItemId: _activeItemId,
          targetGroupId: _targetGroupId2,
          newOrder: _newOrder
        });
        onItemMove === null || onItemMove === void 0 || onItemMove(_activeItemId, _targetGroupId2, _newOrder);
        return;
      }

      // 设置项与设置项之间的排序
      if (activeRecord.type === 'item' && overRecord.type === 'item') {
        var _activeItemId2 = activeRecord.data.id;
        var overItemId = overRecord.data.id;
        var activeGroup = groupList.find(function (g) {
          return g.items && g.items.some(function (item) {
            return item.id === _activeItemId2;
          });
        });
        var overGroup = groupList.find(function (g) {
          return g.items && g.items.some(function (item) {
            return item.id === overItemId;
          });
        });
        if (!activeGroup || !overGroup) return;
        if (activeGroup.id === overGroup.id) {
          // 同组内排序
          var _activeIndex = activeGroup.items.findIndex(function (item) {
            return item.id === _activeItemId2;
          });
          var overIndex = activeGroup.items.findIndex(function (item) {
            return item.id === overItemId;
          });
          if (_activeIndex !== -1 && overIndex !== -1 && _activeIndex !== overIndex) {
            console.log('调用同组内设置项排序接口:', {
              activeItemId: _activeItemId2,
              targetGroupId: activeGroup.id,
              newOrder: overIndex
            });
            onItemMove === null || onItemMove === void 0 || onItemMove(_activeItemId2, activeGroup.id, overIndex);
          }
        } else {
          // 跨组移动
          var _overIndex = overGroup.items.findIndex(function (item) {
            return item.id === overItemId;
          });
          var _newOrder2 = _overIndex >= 0 ? _overIndex : 0;
          console.log('调用跨组设置项移动接口:', {
            activeItemId: _activeItemId2,
            targetGroupId: overGroup.id,
            newOrder: _newOrder2
          });
          onItemMove === null || onItemMove === void 0 || onItemMove(_activeItemId2, overGroup.id, _newOrder2);
        }
      }
    }
  };

  // 处理删除
  var handleDelete = function handleDelete(record) {
    if (record.type === 'group') {
      // 检查组下是否有设置项
      var hasItems = record.data.items && record.data.items.length > 0;
      if (hasItems) {
        // 如果组下有设置项，显示无法删除的提示
        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: function onOk() {
        if (record.type === 'group') {
          // 调用删除组的回调函数
          onDeleteGroup === null || onDeleteGroup === void 0 || onDeleteGroup(record.data.id);
        } else {
          // 调用删除设置项的回调函数
          onDeleteItem === null || onDeleteItem === void 0 || onDeleteItem(record.data.id);
        }
      }
    });
  };

  // 获取当前拖拽的类型
  var activeType = useMemo(function () {
    if (!activeId) return undefined;
    var activeItem = flattenData.find(function (item) {
      return item.key === activeId;
    });
    return activeItem === null || activeItem === void 0 ? void 0 : activeItem.type;
  }, [activeId, flattenData]);

  // 表格列定义
  var columns = [{
    title: locales.getText('registry.table.title'),
    dataIndex: 'name',
    key: 'name',
    width: '30%',
    render: function render(_, record) {
      var isGroup = record.type === 'group';
      var isExpanded = expandedKeys.includes(record.key);
      return /*#__PURE__*/React.createElement(DragHandle, {
        record: record,
        isGroup: isGroup,
        isExpanded: isExpanded,
        onExpand: handleExpand,
        currentLocale: currentLocale
      });
    }
  }, {
    title: locales.getText('registry.table.key'),
    dataIndex: 'key',
    key: 'key',
    width: '25%',
    render: function 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: function render(_, record) {
      if (record.type === 'item' && record.data.scopes) {
        return /*#__PURE__*/React.createElement(AntdSpace, {
          wrap: true
        }, record.data.scopes.map(function (scope) {
          return /*#__PURE__*/React.createElement(AntdTag, {
            key: scope,
            size: "small"
          }, locales.getText(scopeKeyMapping[scope] || "registry.scope.".concat(scope)));
        }));
      }
      return '-';
    }
  }, {
    title: locales.getText('registry.table.actions'),
    key: 'actions',
    width: '20%',
    render: function render(_, record) {
      var isGroup = record.type === 'group';
      return /*#__PURE__*/React.createElement(AntdSpace, {
        size: "small"
      }, isGroup && /*#__PURE__*/React.createElement(Button, {
        type: "text",
        size: "small",
        icon: /*#__PURE__*/React.createElement(PlusOutlined, null),
        onClick: function onClick() {
          return onAddItem === null || onAddItem === void 0 ? void 0 : onAddItem(record.data.id);
        },
        title: locales.getText('registry.action.add.item')
      }), /*#__PURE__*/React.createElement(Button, {
        type: "text",
        size: "small",
        icon: /*#__PURE__*/React.createElement(EditOutlined, null),
        onClick: function 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, {
        type: "text",
        size: "small",
        icon: /*#__PURE__*/React.createElement(DeleteOutlined, null),
        danger: true,
        onClick: function onClick() {
          return 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
    }));
  }

  // 获取所有可拖拽的项目ID
  var sortableIds = flattenData.map(function (item) {
    return item.key;
  });
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-settings-registry-table"
  }, /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: customCollisionDetection,
    onDragStart: handleDragStart,
    onDragOver: handleDragOver,
    onDragEnd: handleDragEnd
  }, /*#__PURE__*/React.createElement(SortableContext, {
    items: sortableIds,
    strategy: verticalListSortingStrategy
  }, /*#__PURE__*/React.createElement(Table, {
    columns: columns,
    dataSource: flattenData,
    pagination: false,
    rowKey: "key",
    className: "pisell-settings-registry-table-content",
    components: {
      body: {
        row: function row(props) {
          // Antd Table 会通过 data-row-key 传递行的 key
          var rowKey = props['data-row-key'];
          // 从 dataSource 中找到对应的 record
          var record = flattenData.find(function (item) {
            return item.key === rowKey;
          });

          // 如果找不到 record，返回普通的 tr
          if (!record) {
            return /*#__PURE__*/React.createElement("tr", props);
          }
          return /*#__PURE__*/React.createElement(DraggableRow, _extends({}, props, {
            record: record
          }));
        }
      }
    }
  })), /*#__PURE__*/React.createElement(DragOverlay, null, activeId ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-settings-registry-drag-overlay"
  }, function () {
    var activeItem = flattenData.find(function (item) {
      return 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)));
};
export default SettingsTable;