import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { userStore, urgeStore } from '@/stores'
import { useTips, useLog, LogType } from '@/hooks'
import { isWebEvn } from '@/utils'
import { dialog } from '@/components/mj/mj-dialog'
import { loading } from '@/components/mj/mj-loading'
import NProgress from 'nprogress'
import '@/styles/nprogress.scss'
import { useStudentAccessStore } from '@/stores/student-access'

// 配置NProgress选项
NProgress.configure({
  easing: 'ease',
  speed: 500,
  showSpinner: false,
})
// import {
// 	wxLogin,
// 	qwLogin,
// 	activateCompanyCallBack,
// 	sendWXAuthCode,
// 	sendDYAuthCode,
// } from "@/api";

const routes: RouteRecordRaw[] = [
  {
    name: 'layout',
    path: '',
    component: () => import('@/layouts/index.vue'),
    children: [],
  },
  // {
  //     path: '/:pathMatch(.*)*',
  //     name: 'NotFound',
  //     redirect: '/',
  // },
]
const modules = import.meta.glob(['../page/*/routes.ts'], {
  eager: true,
})

const moduleRoutes: { key: string; mod: RouteRecordRaw }[] = []

for (const path in modules) {
  const key = path.split('/')[2]
  moduleRoutes.push({
    key,
    mod: (modules[path] as { default: RouteRecordRaw }).default,
  })
}
moduleRoutes.forEach(router => {
  // 一级路由
  if (router.mod.meta?.level === 0) {
    routes.push(router.mod)
    return
  }
  if (router.mod instanceof Array) {
    routes[0].children?.push(...router.mod)
  } else {
    routes[0].children?.push(router.mod)
  }
})

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

// fix: vite路由报错
// https://github.com/vitejs/vite/issues/11804#issuecomment-1406182566
// 原因：
// 发版的时候旧的文件全部删除，但是浏览器还在使用旧的文件，导致报错
// 解决：
// 静默帮用户刷新页面
router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

router.onError(error => {
  // 关闭全局弹框
  dialog.hide()
  loading.hide()
  if (error.message.includes('Failed to fetch dynamically imported module')) {
    useTips({
      tips: '新版本已经准备好，是否重启应用？',
      onOk: () => {
        window.location.reload()
      },
    })
  }
})

// 进入路由时间戳
let startTime = 0
let endTime = 0
// 当前记录类型
let currentLogType: LogType | null
router.beforeEach(async (to, from, next) => {
  // 权限控制
  const { canAccessRoute } = useStudentAccessStore()
  if (!canAccessRoute(to)) {
    next(false)
    return
  }

  // 开启进度条
  NProgress.start()
  // 关闭全局弹框
  dialog.hide()
  loading.hide()

  // 免密登陆
  const userStoreObj = userStore()
  if (to.query.token) {
    const { setToken, loginAfter } = userStoreObj
    to.meta.hiddenBack = true
    setToken(to.query.token as string)
    await loginAfter()
  }

  const { token, userInfo } = userStoreObj
  if (to.meta.logType !== undefined && currentLogType !== to.meta.logType) {
    currentLogType = to.meta.logType as LogType
    startTime = new Date().getTime()
  }

  if (to.meta.logType !== from.meta.logType) {
    currentLogType = null
    endTime = new Date().getTime()
    if (from.meta.logType === LogType.StudyTime) {
      const fromResourceType = ((from.meta.extra as anyObj) || from.query)?.resourceType || '0'
      if (fromResourceType !== '10' && fromResourceType !== '11') {
        useLog(LogType.StudyTime, {
          resourceType: fromResourceType,
          studyTime: endTime - startTime,
          subjectId: (from.params.subjectId || from.query.subjectId) as string,
          userId: userInfo.userId,
          endTime,
          startTime,
        })
      }
    }
  }

  if (!to.meta.isPublic && !token) {
    return next('/login')
  }

  // if (to.meta.isWxLogin) {
  // 	if (to.query.code && to.query.state === "wx" && to.query.appid) {
  // 		try {
  // 			const { data: res } = await wxLogin({
  // 				code: to.query.code as string,
  // 				appid: to.query.appid as string,
  // 			});
  // 			if (res.code === 200) {
  // 				localStorage.setItem("WX_ACCOUNT_SOURCE", "wx");
  // 				return next();
  // 			}
  // 		} catch (e: any) {
  // 			localStorage.removeItem("WX_ACCOUNT_SOURCE");
  // 			return next("/");
  // 		}
  // 	}
  // }

  // 公众号授权
  // if (to.query.auth_code && to.query.state == null) {
  // 	const id = localStorage.getItem("QY_APP_ID");
  // 	sendWXAuthCode({ auth_code: to.query.auth_code, function_appId: id });
  // 	return next(to.path);
  // }
  if (to.name !== 'login') {
    // 督学模式强制进入督学页面
    const { inspectorInfo } = urgeStore()
    if (inspectorInfo?.conductInspectorPlanId && to.name !== 'urge-learning') {
      return next('/urge/learning')
    }
    // 督学模式不可离开
    if (from.name === 'urge-learning' && inspectorInfo?.conductInspectorPlanId) {
      return
    }
    // 非督学模式不可进入督学
    if (to.name === 'urge-learning' && !inspectorInfo?.conductInspectorPlanId) {
      return next('/')
    }
  }

  // 路由不存在
  if (!router.hasRoute(to.name as string)) {
    return next('/')
  }

  // 权限控制
  // if (typeof to.meta.auth === 'string' && !user.auth.includes(to.meta.auth as string)) {
  //     XMessage.error('暂无访问权限');
  //     return;
  // }

  next()
})

// 全局的返回函数
export function globalBack(home = false) {
  if (window.history.state?.position === 1 || !window.history.state.back || home) {
    router.push('/')
  } else {
    const afterRoute = router.currentRoute.value.fullPath
    router.back()
    if (!isWebEvn) {
      setTimeout(() => {
        const nowRoute = router.currentRoute.value.fullPath
        if (afterRoute === nowRoute) {
          router.replace(window.history.state.back)
        }
      }, 300)
    }
  }
}

export default router
