import type { Router, LocationQueryRaw } from 'vue-router'
// import { AxiosCanceler } from '@/utils/http/AxiosCancel'
import { unref } from 'vue'
import nProgress from 'nprogress'
import { isLogin } from '@/utils/auth'
import { useUserStore } from '@/store'
import { setRouteChange } from '@/logics/mitt/routeChange'
import { getPermissions } from '@/api/client'
import { PermissonListResParams } from '@/types/client'
// import { getWorkUndoneCount } from '@/api/project/work'

// // 切换界面的时候是否取消已经发送但是未响应的http请求。
// // 如果开启,想对单独接口覆盖。可以在单独接口设置
// function createHttpGuard(router: Router) {
//   const removeAllHttpPending = true
//   let axiosCanceler: Nullable<AxiosCanceler>
//   if (removeAllHttpPending) {
//     axiosCanceler = new AxiosCanceler()
//   }
//   router.beforeEach(async () => {
//     axiosCanceler?.removeAllPending()
//     return true
//   })
// }

/**
 * 缓存已加载页面状态
 */
function setupPageGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    next()
  })
  const loadedPageMap = new Map<string, boolean>()
  router.beforeEach(async to => {
    // emit route change
    to.meta.loaded = !!loadedPageMap.get(to.path)
    setRouteChange(to)
    return true
  })
  router.afterEach(to => {
    loadedPageMap.set(to.path, true)
  })
}

// 创建页面加载进度条守卫
export function createProgressGuard(router: Router) {
  const getOpenNProgress = true
  router.beforeEach(async to => {
    // 已加载过直接跳过进度条
    if (to.meta.loaded) {
      return true
    }
    unref(getOpenNProgress) && nProgress.start()
    return true
  })

  router.afterEach(async () => {
    unref(getOpenNProgress) && nProgress.done()
    return true
  })
}

const setPermissionsAndUndoneCount = async () => {
  const userStore = useUserStore()
  if (!userStore.permissionsList) {
    const { list }: PermissonListResParams = await getPermissions()
    userStore.setPermissionsList(list)
  }
}

export function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (isLogin()) {
      document.title = to.meta.title as string
      await setPermissionsAndUndoneCount()
      next()
      return
    }
    if (to.name === 'login') {
      next()
      return
    }
    next({
      name: 'login',
      query: {
        ...to.query,
        redirect: to.fullPath,
        data: JSON.stringify({ ...to.params })
      } as LocationQueryRaw
    })
  })
}

// Don't change the order of creation
export function setupRouterGuard(router: Router) {
  setupUserLoginInfoGuard(router)
  setupPageGuard(router)
  createProgressGuard(router)
  // createHttpGuard(router)
}
