  import {
   	createRouter,
   	createWebHistory
   } from 'vue-router';
   import {
   	userStore,
   	useExpressStore
   } from './store';
   import {
   	ElMessage
   } from 'element-plus';


   import request from "./request"

   const router = createRouter({
   	history: createWebHistory(),
   	routes: [{
   			path: "/",
   			redirect: "login"
   		},
   		{
   			path: '/login',
   			name: 'Login',
   			component: () => import("./view/login.vue")
   		},
   		{
   			path: "/register",
   			name: "Register",
   			component: () => import("./view/register.vue")
   		},
   		{
   			path: '/user',
   			name: 'User',
   			redirect: localStorage.getItem("isAdmin") ? '/user/expressList' : '/user/myInfo',
   			component: () => import("./view/user/index.vue"),
   			children: [{
   					path: 'myInfo',
   					component: () => import("./view/user/MyInfo.vue"),
   				},
   				{
   					path: 'expressList',
   					component: () => import("./view/user/ExpressList.vue"),
   				},
   				{
   					path: 'expressForm',
   					component: () => import("./view/user/ExpressForm.vue"),
   				},
   				{
   					path: "signed",
   					component: () => import("./view/user/SignedList.vue"),
   				}
   			]
   		},
   	]
   });

   router.beforeEach((to, from, next) => {
   	const userStore_ = userStore()
   	if (to.name === 'Login' || to.name === "Register") {
   		next();
   	} else {
   		const token = localStorage.getItem("token")
   		if (token) {
   			//重新请求express
   			const expressStore = useExpressStore()
   			request({
   				method: "get",
   				url: "/express",
   			}).then(({
   				data
   			}) => {
   				if (data.code === 0) {
   					expressStore.setExpress(data.data)
   					console.log(data.data, "重新设置express成功")

   				}
   			})

   			//有秘钥，重新请求userInfo
   			request({
   				method: "get",
   				url: "/user/whoami",
   			}).then(({
   				data
   			}) => {
   				//获取用户信息
   				if (data.code === 0) {
   					//重新设置信息
   					userStore_.setUserInfo(data.data)
   					//重新设置秘钥
   					userStore_.setToken(token)
   					userStore_.setAdmin(localStorage.getItem("isAdmin"))

   					console.log("重新响应成功", data.data)
   					if (localStorage.getItem("isAdmin") && token.name === "User") {
   						next({
   							path: "/user/expressList"
   						})
   					} else {
   						next()
   					}
   				} else {
   					//获取失败，秘钥过期
   					ElMessage({
   						message: "登录已过期,请重新登录",
   						type: "error"
   					})
   					//将过期的token删除
   					localStorage.removeItem("token")
   					next({
   						name: "Login"
   					})
   				}
   			})
   			//有秘钥就通过
   		} else {
   			next({
   				name: "Login"
   			})
   		}
   	}
   })


   export default router;