<template>
  <v-menu v-if="this.$store.state.user.userInfo" top offset-y>
    <template v-slot:activator="{ on, attrs }">
      <v-btn
        dark
        v-bind="attrs"
        icon
        large
        v-on="on"
      >
        <v-avatar
          size="32px"
          item
        >
          <v-img
            :src="userInfo.avatarUrl"
            :alt="userInfo.username"
            :title="userInfo.username"
          /></v-avatar>
      </v-btn>
    </template>
    <v-list>
      <v-list-item
        v-for="(item, index) in headItem"
        :key="index"
        link
        @click="headClick(item.id)"
      >
        <v-list-item-action>
          <v-icon>{{ item.icon }}</v-icon>
        </v-list-item-action>
        <v-list-item-content>
          <v-list-item-title>
            {{ item.text }}
          </v-list-item-title>
        </v-list-item-content>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<script>
export default {
  name: 'Head',
  data() {
    return {
      userInfo: {},
      headItem: [
        { icon: 'mdi-account', text: '个人中心', link: '/user/my', id: 0 },
        { icon: 'mdi-application', text: '收藏列表', link: '/user/my/favlist', id: 2 },
        { icon: 'mdi-application', text: '历史记录', link: '/user/my/hislist', id: 3 },
        { icon: 'mdi-application', text: '创作中心', link: '/studio', id: 4 },
        { icon: 'mdi-logout', text: '退出', link: '/logout', id: 5 }
      ]
    }
  },
  created() {
    this.userInfo = this.$store.state.user.userInfo
  },
  methods: {
    headClick(value) {
      if (value === 0) {
        this.$router.push('/user/home')
        /* this.$router.push('/user/' + this.userInfo.userId)
        location.replace('/user/' + this.userInfo.userId)*/
      } else if (value === 1 && this.$route.path !== '/user/playlist') {
        this.$router.push('/user/playlist')
      } else if (value === 2 && this.$route.path !== '/user/favlist') {
        this.$router.push('/user/favlist')
      } else if (value === 3 && this.$route.path !== '/user/hislist') {
        this.$router.push('/user/hislist')
      } else if (value === 4 && this.$route.path !== '/user/studio') {
        this.$router.push('/studio')
      } else {
        this.logout()
      }
    },
    logout() {
      // 调用 store/modules/user.js 中的 logout 方法
      this.$store.dispatch('user/logout').then(() => {
        if (this.$route.path === '/') {
          location.reload()
        } else {
          this.$router.push('/')
        }
      }).catch(() => {
        console.log('用户登录失败')
      })
    }
  }
}
</script>

<style>
</style>
