<template>
  <a-layout style="min-height: 100vh">
    <!-- 侧边栏 -->
    <a-layout-sider v-model:collapsed="collapsed" collapsible>
      <div class="logo">
        <h2 v-if="!collapsed">保险管理系统</h2>
        <h2 v-else>保险</h2>
      </div>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        theme="dark"
        mode="inline"
        @click="handleMenuClick"
      >
        <template v-for="menu in menus" :key="menu.key">
          <a-menu-item
            v-if="!menu.children || menu.children.length === 0"
            :key="menu.key"
            :path="menu.path"
          >
            <template #icon v-if="menu.icon">
              <component :is="menu.icon" />
            </template>
            {{ menu.label }}
          </a-menu-item>
          <a-sub-menu
            v-else
            :key="menu.key"
            :title="menu.label"
          >
            <template #icon v-if="menu.icon">
              <component :is="menu.icon" />
            </template>
            <template v-for="subMenu in menu.children" :key="subMenu.key">
              <a-menu-item
                :path="subMenu.path"
              >
                <template #icon v-if="subMenu.icon">
                  <component :is="subMenu.icon" />
                </template>
                {{ subMenu.label }}
              </a-menu-item>
            </template>
          </a-sub-menu>
        </template>
      </a-menu>
    </a-layout-sider>

    <!-- 主内容区 -->
    <a-layout>
      <!-- 头部 -->
      <a-layout-header style="background: #fff; padding: 0 16px; display: flex; justify-content: space-between; align-items: center">
        <div>
          <menu-unfold-outlined
            v-if="collapsed"
            class="trigger"
            @click="() => (collapsed = !collapsed)"
          />
          <menu-fold-outlined
            v-else
            class="trigger"
            @click="() => (collapsed = !collapsed)"
          />
        </div>
        <div>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <user-outlined />
              {{ userStore.userInfo.real_name || '管理员' }}
              <down-outlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item key="profile">
                  <user-outlined />
                  个人中心
                </a-menu-item>
                <a-menu-item key="logout" @click="handleLogout">
                  <logout-outlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>

      <!-- 内容区 -->
      <a-layout-content style="margin: 16px">
        <div :style="{ padding: '24px', background: '#fff', minHeight: '360px' }">
          <router-view />
        </div>
      </a-layout-content>

      <!-- 底部 -->
      <a-layout-footer style="text-align: center">
        保险端口后台管理系统 ©2024
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, computed, onMounted, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
  DownOutlined,
  LogoutOutlined,
  DashboardOutlined,
  FileTextOutlined,
  FileDoneOutlined,
  SafetyCertificateOutlined,
  DatabaseOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  BellOutlined,
  SettingOutlined,
  UserAddOutlined,
  ShopOutlined,
  FileProtectOutlined,
  MedicineBoxOutlined,
  UserSwitchOutlined,
  InsuranceOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { menuAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const collapsed = ref(false)
const selectedKeys = ref([route.name])
const menus = ref([])

// 图标映射，直接返回图标组件而不是渲染函数
const iconMap = {
  DashboardOutlined: DashboardOutlined,
  DatabaseOutlined: DatabaseOutlined,
  CheckCircleOutlined: CheckCircleOutlined,
  FileTextOutlined: FileTextOutlined,
  FileDoneOutlined: FileDoneOutlined,
  SafetyCertificateOutlined: SafetyCertificateOutlined,
  ShopOutlined: ShopOutlined,
  FileProtectOutlined: FileProtectOutlined,
  MedicineBoxOutlined: MedicineBoxOutlined,
  InsuranceOutlined: InsuranceOutlined,
  BellOutlined: BellOutlined,
  UserAddOutlined: UserAddOutlined,
  SettingOutlined: SettingOutlined,
  UserSwitchOutlined: UserSwitchOutlined
};

// 格式化菜单数据
const formatMenuItems = (menuList) => {
  return menuList.map(menu => {
    const menuItem = {
      key: menu.key,
      label: menu.name,
      path: menu.path
    };
    
    // 添加图标组件引用
    if (menu.icon && iconMap[menu.icon]) {
      menuItem.icon = iconMap[menu.icon];
    }
    
    // 添加子菜单
    if (menu.children && menu.children.length > 0) {
      menuItem.children = formatMenuItems(menu.children);
    }
    
    return menuItem;
  });
};

// 获取动态菜单数据
const fetchMenus = async () => {
  try {
    const response = await menuAPI.getMenus();
    if (response.status === 'success') {
      menus.value = formatMenuItems(response.data);
    }
  } catch (error) {
    // 提供默认菜单作为备用
    menus.value = [
      {
        key: 'Dashboard',
        icon: DashboardOutlined,
        label: '仪表板',
        path: '/dashboard'
      },
      {        
        key: 'DataWarehouse',
        icon: DatabaseOutlined,
        label: '数据览仓',
        path: '/dashboard' // 重定向到仪表板
      },
      {        
        key: 'SupervisionTask',
        icon: CheckCircleOutlined,
        label: '监管任务',
        path: '/supervision-tasks' // 使用正确的复数路径
      },
      {
        key: 'PendingInstallationTask',
        icon: ExclamationCircleOutlined,
        label: '待安装任务',
        path: '/pending-installation' // 使用正确的路径
      },
      {
        key: 'CompletedTask',
        icon: FileDoneOutlined,
        label: '监管任务已结项',
        path: '/completed-tasks'
      },
      {
        key: 'InsuredCustomers',
        icon: ShopOutlined,
        label: '投保客户单',
        children: [
          {
            key: 'ApplicationManagement',
            label: '参保申请',
            path: '/applications'
          }
        ]
      },
      {
        key: 'AgriculturalInsurance',
        icon: FileProtectOutlined,
        label: '生资保单',
        children: [
          {
            key: 'PolicyManagement',
            label: '生资保单列表',
            path: '/policies'
          },
          {
            key: 'LivestockPolicyManagement',
            label: '生资保单管理',
            path: '/livestock-policies'
          }
        ]
      },
      {
        key: 'InsuranceTypeManagement',
        icon: MedicineBoxOutlined,
        label: '险种管理',
        children: [
          {
            key: 'InsuranceTypeList',
            label: '险种管理',
            path: '/insurance-types'
          }
        ]
      },
      {
        key: 'CustomerClaims',
        icon: ExclamationCircleOutlined,
        label: '客户理赔',
        children: [
          {
            key: 'ClaimManagement',
            label: '客户理赔',
            path: '/claims'
          }
        ]
      },
      {        
        key: 'Notifications',
        icon: BellOutlined,
        label: '消息通知',
        path: '/notifications'
      },
      {
        key: 'UserManagement',
        icon: UserAddOutlined,
        label: '子账号管理',
        path: '/users'
      },
      {
        key: 'SystemSettings',
        icon: SettingOutlined,
        label: '系统设置',
        path: '/system-settings'
      },
      {
        key: 'UserProfile',
        icon: UserSwitchOutlined,
        label: '个人中心',
        path: '/dashboard' // 重定向到仪表板
      }
    ];
  }
};

// 菜单点击处理
const handleMenuClick = (e) => {
  // 递归查找菜单项
  const findMenuByKey = (menuList, key) => {
    for (const item of menuList) {
      if (item.key === key) {
        return item;
      }
      if (item.children) {
        const found = findMenuByKey(item.children, key);
        if (found) return found;
      }
    }
    return null;
  };
  
  const menuItem = findMenuByKey(menus.value, e.key);
  if (menuItem && menuItem.path) {
    router.push(menuItem.path);
  }
};

// 退出登录处理
const handleLogout = () => {
  userStore.logout();
  router.push('/login');
};

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

<style scoped>
.logo {
  height: 32px;
  margin: 16px;
  color: white;
  text-align: center;
}

.trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color 0.3s;
}

.trigger:hover {
  color: #1890ff;
}
</style>