import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user-store'
import { getToken } from '@/utils/auth'
import { isRoutePathAllowed } from '@/utils/permission'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
      meta: { hidden: true },
    },
    {
      path: '/profile',
      component: () => import('@/components/Layout/index.vue'),
      meta: { hidden: true },
      children: [
        {
          path: '',
          name: 'Profile',
          component: () => import('@/views/profile/index.vue'),
          meta: { title: '个人中心' },
        },
      ],
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/error/404.vue'),
      meta: { hidden: true },
    },
    {
      path: '/',
      component: () => import('@/components/Layout/index.vue'),
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: { title: '首页', icon: 'HomeFilled' },
        },
      ],
    },
    {
      path: '/analysis',
      component: () => import('@/components/Layout/index.vue'),
      redirect: '/analysis/flow',
      meta: { title: '数据看板', icon: 'TrendCharts', permissions: ['dept_manager', 'flow_manager', 'super_admin'] },
      children: [
        {
          path: 'flow',
          name: 'FlowAnalysis',
          component: () => import('@/views/analysis/index.vue'),
          meta: {
            title: '流程分析看板',
            icon: 'TrendCharts',
            permissions: ['dept_manager', 'flow_manager', 'super_admin'],
          },
        },
      ],
    },
    {
      path: '/system',
      component: () => import('@/components/Layout/index.vue'),
      redirect: '/system/user',
      meta: { title: '系统管理', icon: 'Setting', permissions: ['dept_manager', 'super_admin'] },
      children: [
        {
          path: 'user',
          name: 'User',
          component: () => import('@/views/system/user/index.vue'),
          meta: { title: '用户管理', icon: 'UserFilled', permissions: ['dept_manager', 'super_admin'] },
        },
        {
          path: 'role',
          name: 'Role',
          component: () => import('@/views/system/role/index.vue'),
          meta: { title: '审批角色', icon: 'User', permissions: ['dept_manager', 'super_admin'] },
        },
      ],
    },
    {
      path: '/flow',
      component: () => import('@/components/Layout/index.vue'),
      redirect: '/flow/definition',
      meta: { title: '流程管理', icon: 'Connection', permissions: ['flow_manager', 'super_admin'] },
      children: [
        {
          path: 'designer',
          name: 'FlowDesigner',
          component: () => import('@/views/flow/designer/index.vue'),
          meta: { title: '流程设计器', icon: 'EditPen', permissions: ['flow_manager', 'super_admin'] },
        },
        {
          path: 'definition',
          name: 'FlowDefinition',
          component: () => import('@/views/flow/definition/index.vue'),
          meta: { title: '流程管理', icon: 'Document', permissions: ['flow_manager', 'super_admin'] },
        },
      ],
    },
    {
      path: '/approval',
      component: () => import('@/components/Layout/index.vue'),
      redirect: '/approval/todo',
      meta: { title: '审批中心', icon: 'Stamp' },
      children: [
        {
          path: 'todo',
          name: 'Todo',
          component: () => import('@/views/flow/task/todo.vue'),
          meta: { title: '我的待办', icon: 'Bell' },
        },
        {
          path: 'handled',
          name: 'Handled',
          component: () => import('@/views/flow/task/handled.vue'),
          meta: { title: '我的已办', icon: 'CircleCheck' },
        },
        {
          path: 'cc',
          name: 'Cc',
          component: () => import('@/views/flow/task/cc.vue'),
          meta: { title: '我的抄送', icon: 'Message' },
        },
        {
          path: 'mine',
          name: 'MyInstance',
          component: () => import('@/views/flow/instance/mine.vue'),
          meta: { title: '我的发起', icon: 'List' },
        },
        {
          path: 'execute',
          name: 'FlowExecute',
          component: () => import('@/views/flow/execute/index.vue'),
          meta: { title: '流程执行', icon: 'Pointer' },
        },
        {
          path: 'all',
          name: 'AllInstance',
          component: () => import('@/views/flow/instance/all.vue'),
          meta: { title: '流程明细', icon: 'Document', hidden: true },
        },
      ],
    },
  ],
})

const publicPaths = new Set(['/login'])

// 防止快速切换 tab 时并发多次拉取用户信息
let fetchingUserInfo: Promise<unknown> | null = null

router.beforeEach(async (to, from, next) => {
  // 404、登录页等公开页面直接放行
  if (publicPaths.has(to.path) || to.name === 'NotFound') {
    next()
    return
  }

  const token = getToken()
  if (!token) {
    next(`/login?redirect=${to.path}`)
    return
  }

  const userStore = useUserStore()
  if (!userStore.userInfo) {
    try {
      if (!fetchingUserInfo) {
        fetchingUserInfo = userStore.fetchUserInfo().catch(async (err) => {
          await userStore.logoutAction()
          throw err
        })
      }
      await fetchingUserInfo
    } catch {
      next(`/login?redirect=${to.path}`)
      return
    } finally {
      fetchingUserInfo = null
    }
  }

  const employeeType = userStore.userInfo?.employeeType || 'common_user'
  if (!isRoutePathAllowed(to, employeeType)) {
    next('/dashboard')
    return
  }

  next()
})

export default router
