import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../store/user';
import {
  ROLE_PERMISSIONS,
  hasRolePermission,
} from '../constants/role-permissions';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' },
  },
  {
    path: '/',
    component: () => import('../layouts/AdminLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '首页', requiresAuth: true },
      },
      // Placeholder routes for modules
      {
        path: 'organization/tree',
        name: 'OrgTree',
        component: () => import('../views/organization/OrgTree.vue'),
        meta: {
          title: '组织架构图',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.ORG_TREE,
        },
      },
      {
        path: 'organization/hospitals',
        name: 'Hospitals',
        component: () => import('../views/organization/Hospitals.vue'),
        meta: {
          title: '医院管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.ORG_HOSPITALS,
        },
      },
      {
        path: 'organization/departments',
        name: 'Departments',
        component: () => import('../views/organization/Departments.vue'),
        meta: {
          title: '科室管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.ORG_DEPARTMENTS,
        },
      },
      {
        path: 'organization/groups',
        name: 'Groups',
        component: () => import('../views/organization/Groups.vue'),
        meta: {
          title: '小组管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.ORG_GROUPS,
        },
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/users/Users.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.USERS,
        },
      },
      {
        path: 'dictionaries',
        name: 'Dictionaries',
        component: () => import('../views/dictionaries/Dictionaries.vue'),
        meta: {
          title: '字典管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.DICTIONARIES,
        },
      },
      {
        path: 'devices',
        name: 'Devices',
        component: () => import('../views/devices/Devices.vue'),
        meta: {
          title: '设备管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.DEVICES,
        },
      },
      {
        path: 'uploads',
        name: 'Uploads',
        component: () => import('../views/uploads/MediaLibrary.vue'),
        meta: {
          title: '影像库',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.UPLOADS,
        },
      },
      {
        path: 'tasks',
        name: 'Tasks',
        component: () => import('../views/tasks/Tasks.vue'),
        meta: {
          title: '任务管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.TASKS,
        },
      },
      {
        path: 'patients',
        name: 'Patients',
        component: () => import('../views/patients/Patients.vue'),
        meta: {
          title: '患者管理',
          requiresAuth: true,
          allowedRoles: ROLE_PERMISSIONS.PATIENTS,
        },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from) => {
  NProgress.start();
  document.title = `${to.meta.title || '管理后台'} - 调压通`;

  const userStore = useUserStore();
  const isLoggedIn = userStore.isLoggedIn;

  if (to.meta.requiresAuth && !isLoggedIn) {
    return `/login?redirect=${encodeURIComponent(to.fullPath)}`;
  }

  if (to.path === '/login' && isLoggedIn) {
    return '/';
  }

  // token 存在但内存里无用户信息时，先补拉当前用户上下文。
  if (isLoggedIn && !userStore.userInfo) {
    try {
      await userStore.fetchUserInfo();
    } catch (error) {
      return '/login';
    }
  }

  // 页面级权限校验：无权限时拦截并回到首页，避免进入页面后接口再报 403。
  if (to.meta.requiresAuth) {
    const allowedRoles = to.meta.allowedRoles;
    if (!hasRolePermission(userStore.role, allowedRoles)) {
      ElMessage.error('当前角色无权限访问该页面');
      return '/dashboard';
    }
  }

  return true;
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
