import modules from './modules'
import Vue from 'vue'
import Router from '@/plugin/uni-simple-router/index.js'
import { ACCESS_TOKEN } from '@/common/util/constants.js'
import configService from '@/common/service/config.service.js'
import api from "@/api/api";
import { SKIP_SSO_URL_QUERY, locationUrl, openSso, getUrlParam } from './sso.js'

Vue.use(Router)
//初始化
const router = new Router({
	encodeURI: true,
	routes: [...modules]//路由表
});

const whiteList = ['/pages/login/login']
//全局路由前置守卫
router.beforeEach((to, from, next) => {
	let token = uni.getStorageSync(ACCESS_TOKEN);
	
	console.log("-----to---------------------"+JSON.stringify(token))
	if (token) {
		next()
	} else {
		// query如果没有明确要求跳过sso则执行sso登录
				// const token = uni.getStorageSync(ACCESS_TOKEN);
			const ticket = getUrlParam('ticket');
			console.log("-----ticket---------------------"+ticket)
		if (ticket != null && ticket != '') {
			/**
			   * 单点登录，返回是否需要跳转到单点登录页
			*/
			let redirect = false;
			// if (openSso == 'true') {
				if (!token) {
					if (ticket) {
						try {
							new Promise((resolve, reject) => {
								api
									.validateCasLogin({
										ticket: ""+ticket,
										service: "http://localhost:8080/",
									})
									.then((response) => {
										if (response.data.code == 200) {
											uni.setStorageSync(ACCESS_TOKEN, response.data.result.token);
											redirect = true;
										} else {
											reject(response);
										}
									})
									.catch((error) => {
										console.log("catch===>response", response);
										reject(error);
									});
							});

						} catch (e) {
							redirect = true;
							// if (process.env.VUE_APP_PLATFORM != 'h5') {
							// 	uni.navigateTo({
							// 		url: 'https://id.shendong.com.cn/default' + '/login?service=' + encodeURIComponent(locationUrl())
							// 	});
							// } else {
							// 	window.location.href = 'https://id.shendong.com.cn/default' + '/login?service=' + encodeURIComponent(locationUrl());
							// }

						}
					} else {
						if (window.location.search == '?type=noCas') {
						} else {
							redirect = true;
								uni.navigateTo({
									url: 'https://id.shendong.com.cn/default' + '/login?service=' + encodeURIComponent(locationUrl())
								});
							// if (process.env.VUE_APP_PLATFORM != 'h5') {
							// 	uni.navigateTo({
							// 		url: 'https://id.shendong.com.cn/default' + '/login?service=' + encodeURIComponent(locationUrl())
							// 	});
							// } else {
							// 	window.location.href = 'https://id.shendong.com.cn/default' + '/login?service=' + encodeURIComponent(locationUrl());
							// }
						}
					}
				}
			// }
			let redirectSso = redirect;

			// 如果需要重定向到sso页面则取消路由导航
			if (redirectSso) return;
		} else if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next({ path: '/pages/login/login' })
		}
	}
})
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log("afterEach")
})
export default router;