<template>
  <el-menu
    :default-active="activeMenu"
    class="sidebar-menu"
    mode="vertical"
    @select="handleMenuSelect"
    background-color=""
    text-color="#94a3b8"
    active-text-color="#ffffff"
    :collapse="isCollapse"
    :collapse-transition="false"
  >
    <!-- 加载状态 -->
    <template v-if="loading">
      <el-menu-item v-for="i in 3" :key="i">
        <el-skeleton active :width="isCollapse ? '24px' : '100%'" />
      </el-menu-item>
    </template>
    
    <!-- 错误状态 -->
    <template v-else-if="error">
      <el-menu-item disabled>
        <el-alert
          title="菜单加载失败"
          type="error"
          show-icon
          :closable="false"
          class="error-alert"
        />
        <el-button 
          size="mini" 
          type="text" 
          @click="fetchMenuData"
          class="retry-btn"
        >
          重试
        </el-button>
      </el-menu-item>
    </template>
    
    <!-- 菜单内容 -->
    <template v-else>
      <menu-item
        v-for="item in menuData"
        :key="item.id"
        :menu-item="item"
        :is-collapse="isCollapse"
      />
    </template>
  </el-menu>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import MenuItem from './MenuItem.vue';
import { request } from '@/utils/api'; // 假设request工具已存在
import { Menu } from '@element-plus/icons-vue';

// 组件属性
const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
});

// 状态管理
const loading = ref(true);
const error = ref(false);
const rawMenuData = ref([]);
const menuData = ref([]);
const route = useRoute();
const router = useRouter();

// 当前激活的菜单
const activeMenu = computed(() => {
  return route.path;
});

// 监听路由变化，更新激活菜单
watch(
  () => route.path,
  (newPath) => {
    // 可以在这里添加额外的逻辑
  }
);

// 处理菜单选择
const handleMenuSelect = (key) => {
  // 如果是外部链接
  if (key.startsWith('http://') || key.startsWith('https://')) {
    window.open(key, '_blank');
    return;
  }
  
  // 内部路由跳转
  if (key && key !== route.path) {
    router.push(key);
  }
};

// 将扁平数据转换为树形结构
const buildMenuTree = (items) => {
  const map = new Map();
  const tree = [];

  // 首先将所有项存入map
  items.forEach(item => {
    map.set(item.id, { ...item, children: [] });
  });

  // 构建树形结构
  items.forEach(item => {
    const current = map.get(item.id);
    if (!current) return;

    if (item.parent_id === null || !map.has(item.parent_id)) {
      // 顶级菜单
      tree.push(current);
    } else {
      // 子菜单
      const parent = map.get(item.parent_id);
      if (parent) {
        parent.children.push(current);
      }
    }
  });

  // 按menu_code排序，确保菜单顺序正确
  return tree.sort((a, b) => a.menu_code.localeCompare(b.menu_code));
};

// 从API获取菜单数据
const fetchMenuData = async () => {
  try {
    loading.value = true;
    error.value = false;
    
    const response = await request.postWithoutEncryption(
      '/api/i4/v1/get/menu.php', 
      {},
      {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        timeout: 10000
      }
    );

    // 假设后端返回的数据结构是 { code: 200, data: MenuItem[] }
    if (response.code === 200 && Array.isArray(response.data)) {
      rawMenuData.value = response.data;
      menuData.value = buildMenuTree(rawMenuData.value);
    } else {
      throw new Error('菜单数据格式不正确');
    }
  } catch (err) {
    console.error('获取菜单数据失败:', err);
    error.value = true;
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取菜单数据
onMounted(() => {
  fetchMenuData();
});
</script>

<style scoped>
.sidebar-menu {
  height: 100%;
  border-right: none;
}

.error-alert {
  margin: 10px;
}

.retry-btn {
  margin-left: 10px;
  color: #409eff;
}
</style>
    