<template>
  <el-menu
    :default-active="defaultActive"
    class="el-menu-vertical"
    :collapse="isCollapse"
    :unique-opened="true"
    router
    @select="handleMenuSelect" 
  >
    <!-- 折叠按钮 -->
    <el-button 
      v-if="!isCollapse"
      icon="Expand" 
      size="mini" 
      class="collapse-btn"
      @click="$emit('toggle-collapse')"
      :title="t('common.collapseMenu')"
    />
    <el-button 
      v-else
      icon="Fold" 
      size="mini" 
      class="collapse-btn"
      @click="$emit('toggle-collapse')"
      :title="t('common.expandMenu')"
    />

    <template v-for="item in topLevelMenus" :key="item.id">
      <sidebar-item 
        :item="item" 
        :menu-data="rowData" 
        :depth="1"
      />
    </template>
  </el-menu>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, watch, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import request from '@/utils/api';
import SidebarItem from './SidebarItem.vue'

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})

// 注入主题配置
const theme = inject('theme', { currentTheme: 'light' });

// 国际化
const { t } = useI18n()

// 获取路由实例
const route = useRoute()
const router = useRouter()
const currentRouteFullPath = ref(route.fullPath)

// 监听路由变化
watch(
  () => route.fullPath,
  (newFullPath) => {
    currentRouteFullPath.value = newFullPath
  },
  { immediate: true }
)

// 处理菜单选中事件
const handleMenuSelect = (index) => {
  const targetRoute = router.resolve(index)
  if (targetRoute.fullPath === route.fullPath) {
    return false
  }
}

const emit = defineEmits(['toggle-collapse'])

const rowData = ref([])  // 响应式菜单数据

// 获取菜单数据
const getMenuData = async () => {
  try {
    const response = await request.postWithoutEncryption(
      '/api/i4/v1/get/menu.php',
      {
        login_name: 'NR1798' // 可替换为动态值
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json'
        },
        timeout: 10000
      }
    );

    if (response && response.code === 200 && Array.isArray(response.data)) {
      return response.data;
    } else {
      const errorMsg = response?.message || t('common.unknownError');
      ElMessage.error(`${t('menu.fetchFailed')}: ${errorMsg}`);
      console.error('后端错误:', response);
      return null;
    }
  } catch (error) {
    const msg = error.response?.data?.message 
                || error.message 
                || t('common.networkError');
    ElMessage.error(`${t('menu.fetchFailed')}: ${msg}`);
    console.error('获取菜单数据失败:', error);
    return null;
  }
};

onMounted(async () => {
  try {
    const data = await getMenuData();
    if (data) {
      rowData.value = data;
    } else {
      ElMessage.warning(t('menu.noMenuData'));
    }
  } catch (error) {
    ElMessage.error(t('menu.loadFailed'));
    console.error(error);
  }
});

// 顶级菜单过滤
const topLevelMenus = computed(() => {
  if (!Array.isArray(rowData.value)) return [];
  return rowData.value.filter(item => item.parent_id === 0);
});

// 默认激活项计算
const defaultActive = computed(() => {
  if (!Array.isArray(rowData.value) || !currentRouteFullPath.value) return '';
  
  // 查找与当前路由匹配的菜单项
  const matchedItem = rowData.value.find(item => {
    if (!item.menu_url) return false;
    // 处理完整匹配和部分匹配
    return currentRouteFullPath.value === item.menu_url || 
           currentRouteFullPath.value.startsWith(item.menu_url + '/');
  });
  
  return matchedItem ? (matchedItem.menu_url || String(matchedItem.id)) : '';
});
</script>

<style scoped>
/* 设置菜单项的高度 */
.el-menu-vertical :deep(.el-menu-item),
.el-menu-vertical :deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  color: var(--color-text); /* 使用全局主题文本色 */
}

/* 子菜单项的高度 */
.el-menu-vertical :deep(.el-menu-item) {
  height: 40px;
  line-height: 40px;
}

.sidebar-menu {
  height: 100vh;
  border-right: 1px solid var(--color-border); /* 使用全局主题边框色 */
  position: relative;
  width: 100%;
  background-color: var(--color-surface); /* 使用全局主题表面色 */
}

.collapse-btn {
  position: absolute;
  top: 10px;
  right: -10px;
  z-index: 10;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-surface); /* 使用全局主题表面色 */
  border: 1px solid var(--color-border); /* 使用全局主题边框色 */
  color: var(--color-text); /* 使用全局主题文本色 */
}

/* 适配全局主题的菜单样式 */
:deep(.el-menu) {
  background-color: var(--color-surface) !important;
  border-right-color: var(--color-border) !important;
}

/* 关键修改：通过样式设置激活文本颜色，替代属性绑定 */
:deep(.el-menu-item.is-active),
:deep(.el-sub-menu__title.is-active) {
  color: var(--color-primary) !important;
  background-color: var(--color-surface-alt) !important;
}

:deep(.el-menu-item:hover:not(.is-active)) {
  background-color: var(--color-surface-alt) !important;
}

:deep(.el-sub-menu__title:hover:not(.is-active)) {
  background-color: var(--color-surface-alt) !important;
}

/* 菜单折叠/展开动画 */
.el-menu-vertical {
  transition: all 0.3s ease;
}
</style>
