import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import Layout from '@/components/Layout.vue'
import Login from '@/views/Login.vue'
import Dashboard from '@/views/Dashboard.vue'
import UserManagement from '@/views/UserManagement.vue'
import InsuranceTypeManagement from '@/views/InsuranceTypeManagement.vue'
import ApplicationManagement from '@/views/ApplicationManagement.vue'
import PolicyManagement from '@/views/PolicyManagement.vue'
import ClaimManagement from '@/views/ClaimManagement.vue'
import DataWarehouse from '@/views/DataWarehouse.vue'
import SupervisionTaskManagement from '@/views/SupervisionTaskManagement.vue'
import InstallationTaskManagement from '@/views/InstallationTaskManagement.vue'
import DatePickerTest from '@/views/DatePickerTest.vue'
import DatePickerDebug from '@/views/DatePickerDebug.vue'
import DayjsDebug from '@/views/DayjsDebug.vue'
import AntdConfigDebug from '@/views/AntdConfigDebug.vue'
import SimpleDayjsTest from '@/views/SimpleDayjsTest.vue'
import RangePickerTest from '@/views/RangePickerTest.vue'
import LoginTest from '@/views/LoginTest.vue'
import LivestockPolicyManagement from '@/views/LivestockPolicyManagement.vue'
import SystemSettings from '@/views/SystemSettings.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表板' }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement,
        meta: { title: '用户管理' }
      },
      {
        path: 'notifications',
        name: 'MessageNotification',
        component: () => import('@/views/MessageNotification.vue'),
        meta: { title: '消息通知', requiresAuth: true }
      },
      {
        path: 'insurance-types',
        name: 'InsuranceTypeManagement',
        component: InsuranceTypeManagement,
        meta: { title: '保险类型管理' }
      },
      {
        path: 'applications',
        name: 'ApplicationManagement',
        component: ApplicationManagement,
        meta: { title: '保险申请管理' }
      },
      {
        path: 'policies',
        name: 'PolicyManagement',
        component: PolicyManagement,
        meta: { title: '保单管理' }
      },
      {
        path: 'claims',
        name: 'ClaimManagement',
        component: ClaimManagement,
        meta: { title: '理赔管理' }
      },
      {
        path: 'data-warehouse',
        name: 'DataWarehouse',
        component: DataWarehouse,
        meta: { title: '数据览仓' }
      },
      {
        path: 'supervision-tasks',
        alias: 'supervision-task', // 添加别名兼容单数形式
        name: 'SupervisionTaskManagement',
        component: SupervisionTaskManagement,
        meta: { title: '监管任务管理' }
      },
      {
        path: 'completed-tasks',
        name: 'CompletedTasks',
        component: () => import('@/views/CompletedTaskManagement.vue'),
        meta: { requiresAuth: true, title: '监管任务结项' }
      },
      {
        path: 'installation-tasks',
        alias: ['pending-installation', 'installation-task'], // 添加别名兼容不同形式
        name: 'InstallationTaskManagement',
        component: InstallationTaskManagement,
        meta: { title: '待安装任务管理' }
      },
      {
        path: 'livestock-policies',
        name: 'LivestockPolicyManagement',
        component: LivestockPolicyManagement,
        meta: { title: '生资保单管理' }
      },
      {
        path: 'system-settings',
        name: 'SystemSettings',
        component: SystemSettings,
        meta: { title: '系统设置' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/UserProfile.vue'),
        meta: { 
          title: '个人中心',
          requiresAuth: true 
        }
      },
      {
        path: 'date-picker-test',
        name: 'DatePickerTest',
        component: DatePickerTest,
        meta: { title: '日期选择器测试' }
      },
      {
        path: 'date-picker-debug',
        name: 'DatePickerDebug',
        component: DatePickerDebug,
        meta: { title: '日期选择器调试' }
      },
      {
        path: 'dayjs-debug',
        name: 'DayjsDebug',
        component: DayjsDebug,
        meta: { title: 'Dayjs配置调试' }
      },
      {
        path: 'antd-config-debug',
        name: 'AntdConfigDebug',
        component: AntdConfigDebug,
        meta: { title: 'Antd配置调试' }
      },
      {
        path: 'simple-dayjs-test',
        name: 'SimpleDayjsTest',
        component: SimpleDayjsTest,
        meta: { title: '简单Dayjs测试' }
      },
      {
        path: 'range-picker-test',
        name: 'RangePickerTest',
        component: RangePickerTest,
        meta: { title: '范围选择器测试' }
      },
      {
        path: 'login-test',
        name: 'LoginTest',
        component: LoginTest,
        meta: { title: '登录和API测试' }
      },
      {
        path: 'token-debug',
        name: 'TokenDebug',
        component: () => import('@/views/TokenDebug.vue'),
        meta: { title: 'Token调试' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory('/insurance/'),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 如果访问登录页面且已登录，重定向到仪表板
  if (to.path === '/login' && userStore.accessToken) {
    next('/dashboard')
    return
  }
  
  // 如果访问受保护的路由
  if (to.path !== '/login') {
    try {
      // 确保Token有效（自动刷新或重新登录）
      await userStore.ensureValidToken()
      
      // 检查是否有有效的Token
      if (!userStore.accessToken) {
        // 尝试自动重新登录
        const autoLoginSuccess = await userStore.autoRelogin()
        
        if (!autoLoginSuccess) {
          // 自动重新登录失败，跳转到登录页
          next('/login')
          return
        }
      }
      
      next()
    } catch (error) {
      console.error('路由守卫认证检查失败:', error)
      // 认证失败，跳转到登录页
      next('/login')
    }
    return
  }
  
  next()
})

export default router