<template>
    <router-view></router-view>
</template>

<script>
import { mapState } from 'vuex';
export default {
    data() {
        return {
            timer: null,
            x: null,
            y: null,
            count: 0,
            outTime: 60
        };
    },
    computed: {
        ...mapState(['userInfo'])
    },
    watch: {
        userInfo() {
            if (!this.timer) {
                this.timer = setInterval(this.go, 1000);
            }
        }
    },
    mounted() {
        // window.addEventListener('visibilitychange', this.focusChange);
        document.onmousemove = event => {
            /* Act on the event */
            var x1 = event.clientX;
            var y1 = event.clientY;
            if (this.x != x1 || this.y != y1) {
                this.count = 0;
            }
            this.x = x1;
            this.y = y1;
        };
        document.onkeydown = event => {
            this.count = 0;
        };
        this.timer = setInterval(this.go, 1000);
    },
    destroyed() {
        // window.removeEventListener('visibilitychange');
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    methods: {
        go() {
            this.count++;
            if (this.count == this.outTime * 60 && this.$route.name !== 'login') {
                sessionStorage.removeItem('token');
                clearInterval(this.timer);
                this.$alert('网站由于长时间未访问，已经下线账号', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                        this.$router.push('/login');
                    }
                });
            }
        },
        focusChange() {
            if (document.hidden) {
                // 失去焦点
                console.log('失去焦点');

                if (this.timer) {
                    clearTimeout(this.timer);
                }

                this.timer = setTimeout(() => {
                    if (this.$route.name !== 'login' && document.hidden) {
                        sessionStorage.removeItem('token');
                        this.$alert('网站由于长时间未访问，已经下线账号', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.$router.push('/login');
                            }
                        });
                    }
                }, 1000 * 60 * this.outTime);
            } else {
                // 获取焦点
            }
        }
    }
};
</script>

<style lang="less">
@import url(./styles/app.less);
</style>
