import { createRouter, createWebHistory } from 'vue-router'
// import Cookie from 'js-cookie'
import routes from './routes'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { storeToRefs } from 'pinia'
NProgress.configure({ showSpinner: false }) // 进度环显示/隐藏

const router = createRouter({
  history: createWebHistory(), // hash 模式，想要改为history 模式可以使用createWebHistory
  routes
})

// 路由守卫
const filterNoName = (item) => {
  item.forEach(i => {
    if (i.children?.length) {
      i.children = filterNoName(i.children)
    }
  })
  return item.filter(i => i.name && i.path)
}
let registerRouteFresh = true
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (to.name === 'expertEnroll') {
    store.dictStore.setDictStore()// 获取字典
    store.dictStore.setTagStore()// 获取标签字典
  }
  if (to.name !== 'login' && to.name !== 'commonLogin' && to.name !== 'expertEnroll') {
    const menus = await store.menuStore.setMenuStore()
    !registerRouteFresh && await store.userStore.setUserStore() // 获取用户信息
    store.dictStore.setDictStore()// 获取字典
    store.dictStore.setTagStore()// 获取标签字典
    /*
      如果首次或者刷新界面，next(...to, replace: true)会循环遍历路由，
      如果to找不到对应的路由那么他会再执行一次beforeEach((to, from, next))直到找到对应的路由，
      我们的问题在于页面刷新以后异步获取数据，直接执行next()感觉路由添加了但是在next()之后执行的，
      所以我们没法导航到相应的界面。这里使用变量registerRouteFresh变量做记录，直到找到相应的路由以后，
      把值设置为false然后走else执行next(),整个流程就走完了，路由也就添加完了。
      */
    if (registerRouteFresh) {
      menus.forEach(item => {
        item = {
          ...item,
          children: item.children ? filterNoName(item.children) : []
        }
        router.addRoute('index', item)
      })
      router.addRoute({ path: '/', name: '/', redirect: menus[0].path })
      if (!router.getRoutes().find(i => i.component === '/:pathMatch(.*)*')) {
        router.addRoute({
          path: '/:pathMatch(.*)*',
          redirect: menus[0].path
        })
      }
      next({ ...to, replace: true })
      registerRouteFresh = false
    } else {
      if (!to.meta.isShowTag) {
        if (from.path !== '/' && to.meta.topMenu !== from.meta.topMenu) {
          store.appStore.clearTag()
        }
        store.appStore.addTag({
          name: to.meta.title,
          path: to.path.split('/')[to.path.split('/').length - 1],
          query: to.query,
          params: to.params
        })
      }
      next()
    }
  } else {
    console.log(333)
    next()
  }
  // }
})

// 动态修改路由过度动画
router.afterEach((to) => {
  const userInfo = storeToRefs(store.userStore).userInfo || {}
  if (userInfo.value && userInfo.value.accountId) {
    console.log(to)
    window.aplus_queue.push({
      action: 'aplus.setMetaInfo',
      arguments: ['_hold', 'BLOCK']
    })
    window.aplus_queue.push({
      action: 'aplus.sendPV',
      arguments: [
        {
          is_auto: false
        },
        {
          sapp_id: '43032',
          sapp_name: 'lsxmglxt',
          _user_id: userInfo.value.accountId,
          _user_nick: userInfo.value.realName,
          page_id: to.fullPath,
          page_name: to.meta.title || '丽水信息化项目管理系统',
          page_url: location.host + to.fullPath
        }
      ]
    })
    window.aplus_queue.push({
      action: 'aplus.setMetaInfo',
      arguments: ['_user_nick', userInfo.value.realName]
    })
    window.aplus_queue.push({
      action: 'aplus.setMetaInfo',
      arguments: ['_user_id', userInfo.value.accountId.toString()]
    })
    window.aplus_queue.push({
      action: 'aplus.setMetaInfo',
      arguments: ['_hold', 'START']
    })
  }
  NProgress.done()
})

export default router
