import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { sessionStorage } from '@/plugins/storage'
import Bootstrap from './/bootstrap'
import AnalysisRoutes from './analysis'
import MonitorRoutes from './monitor'
import MarkingRoutes from './marking'
import ExampleRoutes from './example'
import ExpertRoutes from './expert'
import QualityRoutes from './quality'
import AdminRoutes from './admin'
import useMainStore from '@/store/main'

export const routes: RouteRecordRaw[] = [
  ...Bootstrap,
  ...AnalysisRoutes,
  ...MonitorRoutes,
  ...MarkingRoutes,
  ...ExpertRoutes,
  ...QualityRoutes,
  ...AdminRoutes,
  {
    name: 'Error',
    path: '/:path(.*)*',
    component: () => import('@/modules/error/404.vue'),
  },
]

if (import.meta.env.DEV) {
  routes.unshift(...ExampleRoutes)
}

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

const pageJumpsMap: any = {
  SubjectManage: ['StructManage'],
  StructManage: ['EditStruct'],
  // ExamManage: ['EditExam'],
  AnalysisStatistics: ['AnalysisViewMarked'],
  AnalysisPersonnelStatistics: ['MarkingAssess', 'AnalysisPersonnelStatisticsMarker'],
  AnalysisGroupMonitoring: ['AnalysisGroupDetail'],
  MarkingInquiry: ['MarkingInquiryResult'],
  QualitySelfCheck: ['QualitySelfCheckDetail'],
  TrainingMonitoring: ['TrainingDetail'],
  ExamManage: ['EditExam'],
  UserManage: ['EditUser'],
  RoleManage: ['RoleSetting'],
  AnalysisMonitoring: ['AnalysisViewMarked'],
}
const keepAliveJupms = (from: any, to: any) => {
  const mStore = useMainStore()
  if (from.name in pageJumpsMap) {
    if (pageJumpsMap[from.name].includes(to.name)) {
      mStore.setKeepAliveViews(from.name)
    } else {
      mStore.cutKeepAliveViews(from.name)
    }
  }
}
router.beforeEach(async (to, from, next) => {
  keepAliveJupms(from, to)
  const mainStore = useMainStore()
  if (to.name === 'Login') {
    mainStore.setLockScreen(false)
    next()
    return
  }
  if (
    !mainStore.myUserInfo &&
    sessionStorage.get('LOGIN_RESULT') &&
    !['Login', 'CheckExam', 'InitCreateExam', 'InitUserName'].includes(String(to.name))
  ) {
    try {
      await mainStore.getMyUserInfo()
    } catch (e) {
      next({ name: 'Login' })
      return
    }
  }
  if (
    sessionStorage.get('LOGIN_RESULT') &&
    !['Bootstrap', 'Login', 'InitUserName', 'CheckExam', 'InitCreateExam', 'ChangePassword'].includes(
      to.name?.toString() || ''
    ) &&
    mainStore.myUserInfo?.passwordWeak
  ) {
    next({ name: 'ChangePassword', query: { redirectPath: encodeURIComponent(to.fullPath) } })
  } else if (to.meta?.auth === false || to.name === 'Login' || sessionStorage.get('LOGIN_RESULT')) {
    next()
  } else {
    // next({ name: 'Login' })
    next()
  }
})

export default router
