import $cookie from 'vue-cookie';

export default async function({ store, route, redirect }) {
	// const menuId = route.query.menuId;
	// const FEMS_SESSION = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTYiLCJyb2xlIjoiYWRtaW4ifQ.sflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
	const FEMS_SESSION = $cookie.get('FEMS_SESSION');
	if (!FEMS_SESSION) {
		if (route.name !== 'login') redirect('/login');
	} else {
		const userInfo = parseJwt(FEMS_SESSION);
		if (store.state.userInfo && !store.state.userInfo.comId) {
			store.commit('setUserInfo', userInfo);
		}
	}
}

function parseJwt(token) {
	var base64Url = token.split('.')[1];
	var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
	var jsonPayload = decodeURIComponent(
		atob(base64)
			.split('')
			.map(function(c) {
				return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
			})
			.join(''),
	);
	return JSON.parse(jsonPayload);
}
