<template>
  <div class="menu-management-container">
    <!-- 面包屑导航 -->
    <el-card shadow="never" class="breadcrumb-card mb-3">
      <div class="breadcrumb-container">
        <div class="breadcrumb-left">
          <el-breadcrumb separator="/" class="custom-breadcrumb">
            <el-breadcrumb-item @click="handleBreadcrumbClick(null)">
              <el-icon><HomeFilled /></el-icon>
              <span>根目录</span>
            </el-breadcrumb-item>
            <el-breadcrumb-item
              v-for="(item, index) in breadcrumbPath"
              :key="item.menuId"
              @click="handleBreadcrumbClick(item, index)"
              class="breadcrumb-item"
            >
              {{ item.menuName }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="breadcrumb-right">
          <el-tooltip content="操作帮助" placement="top">
            <el-button icon="QuestionFilled" circle size="small" @click="showHelpDialog = true" type="primary" plain />
          </el-tooltip>
          <el-tooltip content="返回上级" placement="top" v-if="currentNode">
            <el-button icon="Back" circle size="small" @click="handleGoBack" type="warning" plain />
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <el-row class="full-height-row" :gutter="10">
      <!-- 左侧树形菜单 -->
      <el-col :span="6" class="full-height-col">
        <el-card shadow="hover" class="full-height-card">
          <template #header>
            <div class="card-header">
              <span>菜单结构</span>
              <div class="header-actions">
                <el-tooltip content="点击节点查看其子菜单" placement="top">
                  <el-button icon="QuestionFilled" circle size="small" type="info" plain></el-button>
                </el-tooltip>
                <el-tooltip content="展开/收缩" placement="top">
                  <el-button icon="Sort" circle size="small" @click="toggleExpandAll"></el-button>
                </el-tooltip>
                <el-tooltip content="刷新" placement="top">
                  <el-button icon="Refresh" circle size="small" @click="refreshTreeData"></el-button>
                </el-tooltip>
              </div>
            </div>
          </template>

          <div class="search-container">
            <el-input v-model="treeSearchText" placeholder="搜索菜单" clearable @keyup.enter="searchTree" @clear="refreshTreeData">
              <template #suffix>
                <el-button :icon="Search" circle @click="searchTree"></el-button>
              </template>
            </el-input>
          </div>

          <!-- 当前选中状态提示 -->
          <div class="tree-status-bar" v-if="currentNode">
            <el-tag type="primary" size="small">
              <el-icon><Location /></el-icon>
              当前选中：{{ currentNode.menuName }}
            </el-tag>
          </div>

          <!-- 修复树容器高度问题 -->
          <div class="tree-scroll-container">
            <el-tree
              ref="menuTreeRef"
              :data="treeData"
              :props="defaultProps"
              :default-expand-all="isExpandAll"
              node-key="menuId"
              highlight-current
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <!-- 自定义树节点内容 -->
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <!-- 树节点标签修改 -->
                  <div class="node-left">
                    <el-icon v-if="data.menuType === 'M'" class="tree-icon"><Folder /></el-icon>
                    <el-icon v-else-if="data.menuType === 'C'" class="tree-icon"><MenuIcon /></el-icon>
                    <el-icon v-else class="tree-icon"><Operation /></el-icon>
                    <span class="node-label">{{ node.label }}</span>
                  </div>

                  <!-- 统计信息 -->
                  <div class="node-statistics">
                    <el-tag v-if="data.menuCount > 0" size="small" type="success" class="stat-tag"> {{ data.menuCount }}菜单 </el-tag>
                    <el-tag v-if="data.buttonCount > 0" size="small" type="warning" class="stat-tag"> {{ data.buttonCount }}按钮 </el-tag>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="18" class="full-height-col">
        <el-card shadow="hover" class="full-height-card">
          <template #header>
            <div class="table-header">
              <div class="header-title">
                <span>{{ currentNodeName || '根目录' }}</span>
                <el-tag size="small" type="info" class="ml-2">共 {{ tableData.length }} 条</el-tag>
                <!-- 当前位置说明 -->
                <el-tooltip
                  :content="`当前显示 '${currentNodeName || '根目录'}' 下的直接子菜单${currentNode ? '（包含当前节点）' : ''}`"
                  placement="top"
                >
                  <el-icon class="ml-2 text-gray-400 cursor-help"><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </div>

            <!-- 按钮操作区域 -->
            <div class="button-actions-area">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button v-hasPermi="['system:menu:add']" type="primary" plain icon="Plus" @click="handleAdd(currentNode)">
                    新增
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    v-hasPermi="['system:menu:edit']"
                    type="success"
                    plain
                    icon="Edit"
                    :disabled="!selectedMenu"
                    @click="handleUpdate(selectedMenu)"
                  >
                    修改
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    v-hasPermi="['system:menu:remove']"
                    type="danger"
                    plain
                    icon="Delete"
                    :disabled="!selectedMenu"
                    @click="handleDelete(selectedMenu)"
                  >
                    删除
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-tooltip content="拖拽调整菜单排序，支持跨层级移动" placement="top">
                    <el-button
                      v-hasPermi="['system:menu:edit']"
                      type="warning"
                      plain
                      icon="Sort"
                      @click="handleMenuSort"
                    >
                      排序
                    </el-button>
                  </el-tooltip>
                </el-col>
                <!-- <el-col :span="1.5">
                  <el-tooltip content="管理菜单之间的互斥关系，避免权限冲突" placement="top">
                    <el-button
                      v-hasPermi="['system:menu:list']"
                      type="info"
                      plain
                      icon="Connection"
                      @click="handleMutexGroupManage"
                    >
                      互斥
                    </el-button>
                  </el-tooltip>
                </el-col> -->
                <!-- <el-col :span="1.5">
                  <el-dropdown class="mt-[1px]" v-if="showSystemActions">
                    <el-button plain type="info">
                      系统管理
                      <el-icon class="el-icon--right">
                        <ArrowDown />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item icon="Refresh" @click="handleResetMenuPath" :disabled="resetLoading">重置路径</el-dropdown-item>
                        <el-dropdown-item icon="Download" @click="handleExport" :disabled="exportLoading">导出全部</el-dropdown-item>
                        <el-dropdown-item icon="Download" @click="importTemplate" :disabled="exportLoading">下载模板</el-dropdown-item>
                        <el-dropdown-item icon="Top" @click="handleImport" :disabled="exportLoading">导入数据</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col> -->
                <el-col :span="1.5">
                  <el-button icon="Search" plain @click="showSearch = !showSearch">
                    {{ showSearch ? '隐藏' : '显示' }}搜索
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button icon="Refresh" @click="refreshTableData">刷新</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-tooltip content="操作帮助" placement="top">
                    <el-button icon="QuestionFilled" type="info" plain @click="showHelpDialog = true">
                      帮助
                    </el-button>
                  </el-tooltip>
                </el-col>
              </el-row>
            </div>
          </template>

          <!-- 当前位置信息条 -->
          <div class="current-location-bar">
            <el-alert :title="getCurrentLocationText()" type="warning" :closable="false" show-icon class="location-alert" />
          </div>

          <!-- 搜索区域 -->
          <el-collapse-transition>
            <div v-show="showSearch" class="search-form-container">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="菜单名称" prop="menuName">
                  <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
                    <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-transition>

          <!-- 改进表格容器以填充满空间 -->
          <div class="full-height-table-container">
            <el-table
              v-loading="tableLoading"
              :data="tableData"
              row-key="menuId"
              stripe
              border
              fit
              highlight-current-row
              @current-change="handleCurrentChange"
              class="fill-height-table"
            >
              <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true" width="160">
                <template #default="scope">
                  <div class="menu-name-cell">
                    <el-icon v-if="scope.row.menuType === 'M'" class="mr-1"><Folder /></el-icon>
                    <el-icon v-else-if="scope.row.menuType === 'C'" class="mr-1"><Document /></el-icon>
                    <el-icon v-else class="mr-1"><Operation /></el-icon>
                    <span>{{ scope.row.menuName }}</span>
                    <!-- 当前节点标识 -->
                    <el-tag v-if="currentNode && scope.row.menuId === currentNode.menuId" size="small" type="primary" class="ml-1">当前</el-tag>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="icon" label="图标" align="center" width="80">
                <template #default="scope">
                  <svg-icon :icon-class="scope.row.icon" />
                </template>
              </el-table-column>

              <el-table-column prop="menuType" label="类型" align="center" width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.menuType === 'M' ? 'primary' : scope.row.menuType === 'C' ? 'success' : 'warning'">
                    {{ scope.row.menuType === 'M' ? '目录' : scope.row.menuType === 'C' ? '菜单' : '按钮' }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="orderNum" label="排序" width="80" align="center" />
              <el-table-column prop="perms" label="权限标识" :show-overflow-tooltip="true" width="150" />
              <el-table-column v-if="!isSmallScreen" prop="component" label="组件路径" :show-overflow-tooltip="true" width="180" />

              <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="scope">
                  <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                </template>
              </el-table-column>

              <el-table-column prop="visible" label="可见" width="80" align="center">
                <template #default="scope">
                  <el-icon v-if="scope.row.visible === '0'" class="text-green-500"><View /></el-icon>
                  <el-icon v-else class="text-red-500"><Hide /></el-icon>
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" width="200" align="center">
                <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="新增子菜单" placement="top">
                    <el-button v-hasPermi="['system:menu:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="查看子菜单" placement="top" v-if="scope.row.menuType !== 'F'">
                    <el-button link type="success" icon="View" @click="handleViewChildren(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button v-hasPermi="['system:menu:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 空数据填充行 -->
              <template #empty>
                <div class="empty-data">
                  <el-empty description="暂无数据">
                    <template #description>
                      <span>{{ currentNode ? '当前节点下暂无子菜单' : '暂无顶级菜单' }}</span>
                    </template>
                    <el-button type="primary" @click="handleAdd(currentNode)">
                      {{ currentNode ? '新增子菜单' : '新增顶级菜单' }}
                    </el-button>
                  </el-empty>
                </div>
              </template>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 引入菜单表单组件 -->
    <menu-form v-model:visible="formVisible" :edit-type="editType" :row-data="currentRow" @save="handleSave"></menu-form>

    <!-- 引入菜单排序组件 -->
    <menu-sort v-model:visible="sortVisible" @save="handleSortSave"></menu-sort>

    <!-- 操作帮助弹窗 -->
    <el-dialog v-model="showHelpDialog" title="📖 菜单管理操作说明" width="600px" :close-on-click-modal="false" append-to-body>
      <!-- 帮助内容保持原有内容 -->
      <div class="help-dialog-content">
        <div class="help-section">
          <h4>🎯 基本操作</h4>
          <ul>
            <li><strong>查看子菜单</strong>：点击左侧树形结构中的节点，右侧表格会显示该节点的直接子菜单</li>
            <li><strong>面包屑导航</strong>：顶部显示当前位置，点击可快速跳转到上级目录</li>
            <li><strong>新增菜单</strong>：点击表格工具栏的"新增"按钮，或点击表格操作列的"+"按钮新增子菜单</li>
            <li><strong>编辑菜单</strong>：点击表格操作列的"编辑"图标，修改菜单信息</li>
            <li><strong>删除菜单</strong>：点击表格操作列的"删除"图标，删除选中菜单</li>
          </ul>
        </div>

        <div class="help-section">
          <h4>🔧 高级功能</h4>
          <ul>
            <li><strong>菜单排序</strong>：点击工具栏的"排序"按钮，通过拖拽调整菜单顺序</li>
            <li><strong>互斥管理</strong>：管理菜单之间的互斥关系，避免权限冲突</li>
            <li><strong>批量导出</strong>：导出所有菜单数据到Excel文件，包含角色关联信息</li>
            <li><strong>路径重置</strong>：重置所有菜单的路径链，用于修复数据不一致问题</li>
          </ul>
        </div>

        <div class="help-section">
          <h4>📋 菜单类型说明</h4>
          <ul>
            <li><strong>目录（M）</strong>：用于组织菜单结构，不对应具体页面</li>
            <li><strong>菜单（C）</strong>：对应具体的页面，需要设置路由地址和组件路径</li>
            <li><strong>按钮（F）</strong>：页面内的操作按钮，用于权限控制</li>
          </ul>
        </div>

        <div class="help-section">
          <h4>⚠️ 注意事项</h4>
          <ul>
            <li>删除菜单前请确认该菜单下没有子菜单</li>
            <li>已分配给角色的菜单不能直接删除</li>
            <li>菜单类型确定后，父子关系有特定限制</li>
            <li>外链菜单的路由地址必须以http(s)://开头</li>
          </ul>
        </div>
      </div>

      <template #footer>
        <div class="help-dialog-footer">
          <el-button @click="showHelpDialog = false">我知道了</el-button>
          <el-button type="primary" @click="showHelpDialog = false">开始使用</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量导入   -->
    <import-data-upload ref="importRef" up-url="/system/menu/importData" @ok="loadTableData"></import-data-upload>
  </div>
</template>

<script setup name="Menu" lang="ts">
// ==================== 导入依赖 ====================
import { delMenu, listMenu, listMenuManage, resetMenuPath } from '@/api/system/menu';
import { MenuQuery, MenuVO } from '@/api/system/menu/types';
import MenuForm from './menuForm.vue';
import MenuSort from './menuSort.vue';
import { useUserStore } from '@/store/modules/user';
import {
  ArrowDown,
  Document,
  Folder,
  Hide,
  HomeFilled,
  InfoFilled,
  Location,
  Menu as MenuIcon,
  Operation,
  Search,
  View
} from '@element-plus/icons-vue';
import ImportDataUpload from '@/views/modules/common/ImportDataUpload.vue'

const importRef = ref<InstanceType<typeof ImportDataUpload>>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_show_hide, sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_show_hide', 'sys_normal_disable'));

// ==================== 新增：路由导航 ====================
const router = useRouter();

// ==================== 权限控制 ====================
const userStore = useUserStore();

// 系统管理员ID常量（请根据实际情况调整）
const SYSTEM_ADMIN_ID = 1;

/**
 * 判断是否为系统管理员
 */
const isSystemAdmin = (): boolean => {
  return Number(userStore.userId) === SYSTEM_ADMIN_ID;
};

/**
 * 判断是否显示系统管理按钮
 */
const showSystemActions = computed(() => {
  return isSystemAdmin();
});

// ==================== 原有状态变量 ====================
// 表单控制状态
const formVisible = ref(false);
const editType = ref('');
const currentRow = ref<MenuVO | null>(null);

// 菜单排序抽屉控制
const sortVisible = ref(false);

// 新增：用户指导相关
const showHelpDialog = ref(false);
const breadcrumbPath = ref<MenuVO[]>([]);

// 左侧树控制
const treeSearchText = ref('');
const treeData = ref<MenuVO[]>([]);
const treeLoading = ref(false);
const currentNode = ref<MenuVO | null>(null);
const currentNodeName = ref('根目录');
const isExpandAll = ref(false);
const defaultProps = {
  children: 'children',
  label: 'menuName'
};

// 右侧表格控制
const tableData = ref<MenuVO[]>([]);
const tableLoading = ref(false);
const showSearch = ref(true);

// 查询表单ref
const queryFormRef = ref<ElFormInstance>();
const menuTreeRef = ref<ElTreeInstance>();

// 是否小屏幕
const isSmallScreen = ref(false);

// 查询参数
const queryParams = reactive<MenuQuery>({
  menuName: undefined,
  status: undefined
});

// ==================== 新增状态变量 ====================
// 重置和导出功能状态
const resetLoading = ref(false);
const exportLoading = ref(false);

// 表格选中行（用于控制修改/删除按钮的启用状态）
const selectedMenu = ref<MenuVO | null>(null);

// ==================== 新增功能方法 ====================

/**
 * 表格行选择改变事件
 */
const handleCurrentChange = (currentRow: MenuVO | null) => {
  selectedMenu.value = currentRow;
};

/**
 * 菜单排序管理按钮处理
 */
const handleMenuSort = () => {
  sortVisible.value = true;
};

/**
 * 排序保存成功后的处理
 */
const handleSortSave = () => {
  // 刷新树形数据和表格数据
  loadTreeData();
  loadTableData();
  proxy?.$modal.msgSuccess('菜单排序保存成功！数据已更新');
};

/**
 * 菜单互斥管理按钮处理
 */
const handleMutexGroupManage = () => {
  router.push('/system/menu-mutex-group/index');
};

/**
 * 重置菜单路径链功能
 */
const handleResetMenuPath = async () => {
  try {
    resetLoading.value = true;
    await proxy?.$modal.confirm('确认要重置所有菜单的路径链和排序号吗？此操作将重新整理菜单数据。');
    const response = await resetMenuPath();
    if (response.code === 200) {
      proxy?.$modal.msgSuccess(response.msg || '重置成功');
      await Promise.all([loadTreeData(), loadTableData()]);
    } else {
      proxy?.$modal.msgError(response.msg || '重置失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('重置失败，请稍后重试');
    }
  } finally {
    resetLoading.value = false;
  }
};

/**
 * 导出所有菜单功能（简化版）
 */
const handleExport = async () => {
  proxy?.downloadByJson(
    '/system/menu/export',
    {
      ...queryParams
    },
    `菜单数据_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  importRef.value?.show();
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/menu/importTemplate', {}, `系统菜单导入模板_${new Date().getTime()}.xlsx`);
};

/**
 * 构建面包屑路径
 */
const buildBreadcrumbPath = (node: MenuVO | null) => {
  if (!node) {
    breadcrumbPath.value = [];
    return;
  }

  const path: MenuVO[] = [];
  const findPath = (nodeData: MenuVO[], targetId: string | number): MenuVO[] | null => {
    for (const item of nodeData) {
      if (item.menuId === targetId) {
        return [item];
      }
      if (item.children && item.children.length > 0) {
        const childPath = findPath(item.children, targetId);
        if (childPath) {
          return [item, ...childPath];
        }
      }
    }
    return null;
  };

  const fullPath = findPath(treeData.value, node.menuId);
  breadcrumbPath.value = fullPath || [];
};

/**
 * 面包屑点击处理
 */
const handleBreadcrumbClick = (node: MenuVO | null, index?: number) => {
  if (node) {
    currentNode.value = node;
    currentNodeName.value = node.menuName;
    if (typeof index === 'number') {
      breadcrumbPath.value = breadcrumbPath.value.slice(0, index + 1);
    }
  } else {
    currentNode.value = null;
    currentNodeName.value = '根目录';
    breadcrumbPath.value = [];
  }

  loadTableData();

  nextTick(() => {
    if (menuTreeRef.value && node) {
      menuTreeRef.value.setCurrentKey(node.menuId);
    } else if (menuTreeRef.value && !node) {
      menuTreeRef.value.setCurrentKey(null);
    }
  });
};

/**
 * 返回上级
 */
const handleGoBack = () => {
  if (breadcrumbPath.value.length > 1) {
    const parentNode = breadcrumbPath.value[breadcrumbPath.value.length - 2];
    handleBreadcrumbClick(parentNode, breadcrumbPath.value.length - 2);
  } else {
    handleBreadcrumbClick(null);
  }
};

/**
 * 获取当前位置说明文本
 */
const getCurrentLocationText = (): string => {
  if (!currentNode.value) {
    return '正在查看：根目录 → 显示所有顶级菜单';
  }
  return `正在查看：${currentNodeName.value} → 包含当前节点及其直接子菜单`;
};

/**
 * 查看子菜单功能
 */
const handleViewChildren = (row: MenuVO) => {
  handleNodeClick(row);
};

/**
 * 切换树展开/收缩状态
 */
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    const allNodes = menuTreeRef.value?.store.nodesMap;
    if (allNodes) {
      Object.values(allNodes).forEach((node) => {
        node.expanded = isExpandAll.value;
      });
    }
  });
};

/**
 * 检测屏幕尺寸
 */
const checkScreenSize = () => {
  isSmallScreen.value = window.innerHeight < 768 || window.innerWidth < 1366;
};

/**
 * 加载树数据并计算子菜单和按钮统计信息
 */
const loadTreeData = async () => {
  treeLoading.value = true;
  try {
    const params = treeSearchText.value ? { menuName: treeSearchText.value } : undefined;
    const res = await listMenuManage(params);
    const data = proxy?.handleTree<MenuVO>(res.data, 'menuId');
    if (data) {
      const enhancedData = addMenuStatistics(data);
      treeData.value = filterTreeData(enhancedData);
    }
  } finally {
    treeLoading.value = false;
  }
};

/**
 * 为菜单树添加统计信息
 */
const addMenuStatistics = (data: MenuVO[]): (MenuVO & { menuCount: number; buttonCount: number })[] => {
  return data.map((item) => {
    let menuCount = 0;
    let buttonCount = 0;

    if (item.children && item.children.length > 0) {
      const enhancedChildren = addMenuStatistics(item.children);
      item.children.forEach((child) => {
        if (child.menuType === 'C') menuCount++;
        if (child.menuType === 'F') buttonCount++;
      });
      item.children = enhancedChildren;
    }

    return {
      ...item,
      menuCount,
      buttonCount
    };
  });
};

/**
 * 过滤树形数据，只保留目录和菜单类型
 */
const filterTreeData = (data: MenuVO[]) => {
  return data
    .filter((item) => item.menuType !== 'F')
    .map((item) => ({
      ...item,
      children: item.children ? filterTreeData(item.children) : []
    }));
};

/**
 * 加载表格数据 - 显示当前节点和直接子节点
 */
const loadTableData = async () => {
  tableLoading.value = true;
  try {
    const params = {
      ...queryParams,
      parentId: currentNode.value?.menuId || '0',
      includeCurrentNode: true
    };

    const res = await listMenuManage(params);

    if (res.data && res.code === 200) {
      if (currentNode.value) {
        const currentNodeData = res.data.find((item) => item.menuId === currentNode.value?.menuId);
        const childNodes = res.data.filter((item) => item.parentId === currentNode.value?.menuId);
        if (currentNodeData) {
          tableData.value = [currentNodeData, ...childNodes];
        } else {
          tableData.value = childNodes;
        }
      } else {
        tableData.value = res.data.filter((item) => item.parentId === '0' || item.parentId === 0);
      }
    } else {
      proxy?.$modal.msgError((res.data && res.msg) || '获取数据失败');
      tableData.value = [];
    }
  } catch (error) {
    proxy?.$modal.msgError('加载菜单数据失败');
    tableData.value = [];
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 搜索树节点
 */
const searchTree = () => {
  loadTreeData();
};

/**
 * 刷新树数据
 */
const refreshTreeData = () => {
  treeSearchText.value = '';
  loadTreeData();
};

/**
 * 树节点点击事件
 */
const handleNodeClick = (data: MenuVO) => {
  currentNode.value = data;
  currentNodeName.value = data.menuName;
  buildBreadcrumbPath(data);
  loadTableData();
};

/**
 * 刷新表格数据
 */
const refreshTableData = () => {
  loadTableData();
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  loadTableData();
};

/**
 * 重置查询参数
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/**
 * 新增菜单
 */
const handleAdd = (row?: MenuVO) => {
  currentRow.value = row || currentNode.value;
  editType.value = 'add';
  formVisible.value = true;
};

/**
 * 修改菜单 - 支持传入行数据或使用选中行
 */
const handleUpdate = (row?: MenuVO) => {
  const targetRow = row || selectedMenu.value;
  if (!targetRow) {
    proxy?.$modal.msgError('请先选择要修改的菜单');
    return;
  }
  currentRow.value = targetRow;
  editType.value = 'edit';
  formVisible.value = true;
};

/**
 * 保存成功后的处理
 */
const handleSave = () => {
  loadTreeData();
  loadTableData();
  proxy?.$modal.msgSuccess('操作成功！数据已更新');
};

/**
 * 删除菜单 - 支持传入行数据或使用选中行
 */
const handleDelete = async (row?: MenuVO) => {
  const targetRow = row || selectedMenu.value;
  if (!targetRow) {
    proxy?.$modal.msgError('请先选择要删除的菜单');
    return;
  }

  await proxy?.$modal.confirm('是否确认删除名称为"' + targetRow.menuName + '"的数据项?');
  await delMenu(targetRow.menuId);

  // 清空选中状态
  selectedMenu.value = null;

  loadTableData();
  loadTreeData();
  proxy?.$modal.msgSuccess('删除成功');
};

// 初始化
onMounted(() => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);
  loadTreeData();
  loadTableData();
  buildBreadcrumbPath(currentNode.value);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize);
});
</script>

<style scoped>
/* 关键样式修复 */
.menu-management-container {
  height: calc(100vh - 100px);
  padding: 10px;
  box-sizing: border-box;
}

.full-height-row {
  height: 100%;
}

.full-height-col {
  height: 100%;
}

.full-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 新增按钮布局样式 */
.table-header {
  padding: 12px 20px 8px;

  .header-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: 500;
  }
}

.button-actions-area {
  padding: 0 20px 8px;

  .mb8 {
    margin-bottom: 0;
  }

  .el-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .el-col {
    margin-bottom: 6px;
  }

  /* 下拉菜单样式 */
  .el-dropdown {
    .el-button {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }
}

/* 响应式适配 */
@media (max-width: 1600px) {
  .button-actions-area {
    .el-row {
      .el-col {
        flex: 0 0 auto;
        max-width: none;
      }

      /* 小屏幕下按钮换行 */
      .el-col:nth-child(n+7) {
        margin-top: 8px;
      }
    }
  }
}

@media (max-width: 1200px) {
  .button-actions-area {
    .el-row {
      flex-direction: column;
      align-items: stretch;

      .el-col {
        width: 100%;
        margin-bottom: 4px;

        .el-button {
          width: 100%;
          justify-content: center;
        }
      }
    }
  }
}

/* ============= 其他现有样式保持不变 ============= */
.breadcrumb-card {
  border: none;
  background: linear-gradient(90deg, #f8f9fa 0%, #e9ecef 100%);
}

.breadcrumb-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.custom-breadcrumb {
  font-size: 14px;
}

.breadcrumb-item {
  cursor: pointer;
  transition: color 0.3s;
}

.breadcrumb-item:hover {
  color: #409eff !important;
}

.breadcrumb-right {
  display: flex;
  gap: 8px;
}

.tree-status-bar {
  padding: 8px 15px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
}

.current-location-bar {
  padding: 0 20px 8px;
}

.location-alert {
  border: none;
  background: #fff7e6;
  border-left: 4px solid #faad14;
}

.location-alert :deep(.el-alert__title) {
  font-size: 13px;
  color: #d46b08;
  font-weight: 500;
}

.menu-name-cell {
  display: flex;
  align-items: center;
}

.tree-scroll-container {
  flex: 1;
  overflow: auto;
  padding: 0;
  min-height: 150px;
  position: relative;
  overflow-y: auto;
  height: calc(100% - 120px);
}

.full-height-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: auto;
  min-height: 200px;
  max-height: calc(100% - 40px);
  position: relative;
  overflow: hidden;
}

.fill-height-table {
  width: 100%;
  max-height: calc(100% - 40px);
  overflow: auto;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
}

.header-title {
  display: flex;
  align-items: center;
}

.search-container {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.node-left {
  display: flex;
  align-items: center;
}

.tree-icon {
  margin-right: 6px;
}

.node-label {
  flex: 1;
}

.node-statistics {
  display: flex;
  align-items: center;
}

.stat-tag {
  margin-left: 4px;
  font-size: 10px;
  padding: 0 4px;
  height: 18px;
  line-height: 18px;
}

.search-form-container {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
}

/* 改进hover效果 */
.breadcrumb-item:hover,
.custom-breadcrumb .el-breadcrumb__item:hover {
  color: #409eff;
  font-weight: 500;
}

/* 当前节点高亮 */
.custom-tree-node:has(.el-tag) {
  background-color: #f0f9ff;
}

/* 帮助对话框样式 */
.help-dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 20px;
}

.help-section {
  margin-bottom: 24px;
}

.help-section h4 {
  color: #409eff;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
}

.help-section ul {
  margin: 0;
  padding-left: 20px;
}

.help-section li {
  margin-bottom: 8px;
  line-height: 1.6;
  color: #606266;
}

.help-section strong {
  color: #303133;
  font-weight: 600;
}

.help-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
