<template>
    <div class='app-header-user'>
        <dropdown @on-click="userSelect" :transfer="true">
            <div class='user'>
                <span>{{$t('user.name')}}</span>
                &nbsp;&nbsp;<avatar :src="user.avatar" />
            </div>
            <dropdown-menu class='menu' slot='list' style='font-size: 15px !important;'>
                <dropdown-item name='logout' style='font-size: 15px !important;'>
                    <span><i aria-hidden='true' class='fa fa-cogs' style='margin-right: 8px;'></i></span>
                    <span>{{$t('user.logout')}}</span>
                </dropdown-item>
            </dropdown-menu>
        </dropdown>
    </div>
</template>
<script lang = 'ts'>
import { Vue, Component } from 'vue-property-decorator';

@Component({
    i18n: {
        messages: {
            'zh-CN': {
                user: {
                    name: '匿名访问',
                    logout: '退出登陆',
                    surelogout: '确认要退出登陆？',
                }
            },
            'en-US': {
                user: {
                    name: 'Anonymous access',
                    logout: 'Logout',
                    surelogout: 'Are you sure logout?',
                }
            }
        }
    }
})
export default class AppUser extends Vue {

    /**
     * 用户信息 
     *
     * @memberof AppUser
     */
    public user = {
        name: 'user.name',
        avatar: './assets/img/avatar.png',
    }

    /**
     * 下拉选选中回调
     *
     * @param {*} data
     * @memberof AppUser
     */
    public userSelect(data: any) {
        if (Object.is(data, 'logout')) {
            const title: any = this.$t('user.surelogout');
            this.$Modal.confirm({
                title: title,
                onOk: () => {
                    this.logout();
                }
            });
        }
    }

    /**
     * vue  生命周期
     *
     * @memberof AppUser
     */
    public mounted() {
        if (window.localStorage.getItem('user')) {
            const _user: any = window.localStorage.getItem('user') ? window.localStorage.getItem('user') : '';
            const user = JSON.parse(_user);
            Object.assign(this.user, user, {
                time: +new Date
            });
        }
    }

    /**
     * 退出登录
     *
     * @memberof AppUser
     */
    public logout() {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        this.$router.push({ name: 'login' });
    }
}
</script>

<style lang="less">
@import './app-user.less';
</style>