<template>
  <span>
    <ui-user-avatar v-if="!!user" :user="user" class="cursor-pointer" />
    <q-btn v-else dense round loading flat class="no-pointer-events" />
    <q-menu v-if="user" v-model="isShowMenu">
      <q-item class="q-my-sm">
        <q-item-section avatar>
          <ui-user-avatar v-if="!!user" :user="user" />
        </q-item-section>
        <q-item-section>
          <q-item-label class="text-no-wrap">
            {{ userFullName }}
          </q-item-label>
          <q-item-label caption lines="1">
            {{ user.positionName }}
          </q-item-label>
        </q-item-section>
      </q-item>
      <q-item @click="logout" clickable class="q-mb-sm">
        <q-item-section avatar>
          <q-icon name="las la-sign-out-alt" />
        </q-item-section>
        <q-item-section>
          <q-item-label>Выйти</q-item-label>
        </q-item-section>
      </q-item>
    </q-menu>
  </span>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import User from '../types/User'
import UserService from '../services/UserService'
import UiUserAvatar from './UiUserAvatar.vue'
import { QBtn, QIcon, QItem, QItemLabel, QItemSection, QMenu } from 'quasar'

@Component({
  components: {
    UiUserAvatar,
    QBtn,
    QMenu,
    QItem,
    QItemSection,
    QItemLabel,
    QIcon,
  },
  inheritAttrs: false,
})
export default class UiUserMenu extends Vue {
  user: User | null = null
  isShowMenu = false

  created() {
    UserService.loadUser().then(user => (this.user = user as User))
  }

  get userFullName(): string {
    if (!this.user) {
      return ''
    }

    return UserService.getUserFullName(this.user)
  }

  logout() {
    UserService.logout().then(({ url }) => {
      location.assign(url)
    })
  }
}
</script>
