<template>
	<div id="app">
		<router-view />
	</div>
</template>

<script>
	let timmer = null //超时退出 定时器 必须放到全局，解决vue数据同步导致无法清除定时器
	export default {
		name: 'App',
		data() {
			return {
				lastTime: null, //超时退出 最后时间
			}
		},
		created() {
			// 在页面加载时读取sessionStorage里的状态信息
			if (sessionStorage.getItem('store')) {
				this.$store.replaceState(
					Object.assign({},
						this.$store.state,
						JSON.parse(sessionStorage.getItem('store'))
					)
				)
			}
			// 在页面刷新时将vuex里的信息保存到sessionStorage里
			// beforeunload事件在页面刷新时先触发
			window.addEventListener('beforeunload', () => {
				sessionStorage.setItem('store', JSON.stringify(this.$store.state))
			});
			// 超时退出 start
			this.lastTime = new Date();

			window.addEventListener('resize', () => {
				if (timmer) {
					clearTimeout(timmer);
				}
				timmer = setTimeout(() => {
					if (this.$route.path != '/login') {
						this.currentTime();
					}
				}, 1000)
			})

			window.addEventListener('click', () => {
				if (timmer) {
					clearTimeout(timmer);
				}
				timmer = setTimeout(() => {
					if (this.$route.path != '/login') {
						this.currentTime();
					}
				}, 1000)
			})

			window.addEventListener('scroll', () => {
				if (timmer) {
					clearTimeout(timmer);
				}
				timmer = setTimeout(() => {
					if (this.$route.path != '/login') {
						this.currentTime();
					}
				}, 1000)
			}, true)

			window.addEventListener('mousemove', () => {
				if (timmer) {
					clearTimeout(timmer);
				}
				timmer = setTimeout(() => {
					if (this.$route.path != '/login') {
						this.currentTime();
					}
				}, 1000)
			}, true)
			// 超时退出 end
		},
		methods: {
			currentTime() { // 超时退出     
				const currentTime = new Date();
				if (currentTime - this.lastTime > 1000 * 60 * 20) {
					this.lastTime = currentTime
					if (this.$route.path != '/login') {
						this.$message({
							message: '登录超时，将返回登录页',
							type: 'error',
							duration: 2000
						})
						setTimeout(() => {
							this.$store.dispatch('user/logout')
							this.$router.push(`/login?redirect=${this.$route.fullPath}`)
						}, 2000)
					}
				} else {
					this.lastTime = currentTime;
				}
			}
		}
	}
</script>
