import { eRole } from '@/types/role'
import { getOldRoleFromUserMsg } from '@/utils/user'
import { getUserMsg } from '@/utils/userMsg/userMsg'
import { menuList } from '@/views/Root/getMenuList'
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'

const Index = () => import('@/views/Root/index.vue')

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
  },
  {
    path: '/adminLogin',
    name: 'adminLogin',
    component: () => import('@/views/Login/index.vue'),
    props: (query) => ({ adminLogin: true }),
  },
  {
    path: '/backend',
    component: Index,
    children: menuList.map((item) => {
      return {
        name: item.routeName,
        path: item.path,
        component: item.component,
        meta: {
          roles: item.roles,
          selectedName: item.belongToMenuName
            ? item.belongToMenuName
            : item.routeName,
        },
        children: ((item.getChildren && item.getChildren()) || []).map(
          (subItem) => {
            return {
              name: subItem.routeName,
              path: subItem.path,
              component: subItem.component,
              meta: {
                roles: subItem.roles,
                selectedName: subItem.routeName,
              },
            }
          },
        ),
      }
    }),
  } as RouteConfig,
  {
    path: '*',
    redirect: { name: 'home' },
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

router.beforeEach((to, from, next) => {
  console.log({ from, to })

  const usermsg = getUserMsg()
  if (usermsg === undefined) {
    /* 没有登录 */
    if (to.name == 'adminLogin' || to.name == 'login') {
      console.log(1)

      next()
    } else {
      console.log(2)
      next({
        name: 'login',
      })
    }
  } else {
    console.log(3)
    /* 有登录 */
    const roles = (to.meta as { roles?: eRole[] }).roles
    const oldRole = getOldRoleFromUserMsg(usermsg)
    // console.log(oldRole, roles, oldRole && roles && roles.includes(oldRole))
    const userHasRoleInCurPage =
      oldRole !== undefined && roles !== undefined && roles.includes(oldRole)
    if (userHasRoleInCurPage) {
      console.log(4)
      next()
    } else {
      if (oldRole == eRole.platform_management) {
        if (getUserMsg()?.phone) {
          console.log(5)
          next({ name: 'platformUserManagement' })
        } else {
          console.log(6)
          next({ name: 'changePhone' })
        }
      } else {
        console.log(7)
        next({ name: 'home' })
      }
    }
  }
})

export default router
