<template>
	<div id="app" class="theme-light">
		<div class="error-tips" v-if="ready && showErrorTips">
			<p>{{errorTipsStr}}</p>
			<el-button @click="jump">direct link</el-button>
		</div>
		<router-view v-else/>
	</div>
</template>

<script>
	import i18n from "./i18n";
	import {SSO_VERIFY_PAGE_URL} from "./config";
	import {getCookie} from "./api/utils";

	const errorTipsArr = [
		'',
		i18n.t('Access denied'),
		i18n.t('Invalid router'),
	];

	export default {
		name: "App",
		data() {
			return {
				cd: 5,
				ready: false,
				errorType: 0,
				errorTips: '',
			}
		},
		mounted() {
			let sso_ticket = getCookie('sso_ticket');
			if (!sso_ticket) {
				this.dealError(1);
			}
		},
		computed: {
			showErrorTips() {
				let sso_ticket = getCookie('sso_ticket');
				return !sso_ticket || !this.$route.matched || this.$route.matched.length === 0;
			},
			errorTipsStr() {
				return this.errorTips + ' ' + this.$t('Jump after', {cd: this.cd});
			},
		},
		watch: {
			$route: {
				handler: function (val, oldVal) {
					this.dealError(2);
				},
				deep: true
			}
		},
		methods: {
			dealError(type) {
				this.errorType = type;
				this.errorTips = errorTipsArr[type];
				this.ready = true;

				if (this.showErrorTips) {
					this.cd = 5;
					this.startCD();
				}
			},
			startCD() {
				clearInterval(this.timer);
				this.timer = setInterval(() => {
					if (this.cd <= 0) {
						clearInterval(this.timer);
						this.jump();
						return;
					}
					this.cd--;
				}, 1000)
			},
			jump() {
				switch (this.errorType) {
					case 1:
						location.href = SSO_VERIFY_PAGE_URL;
						break;
					case 2:
						this.$router.replace({name: 'home'});
						break;
				}
			},
		},
	}
</script>

<style>
	.error-tips {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
