<template>
  <header class="header">
    <el-image class="logo" :src="$store.state.app.config.logo_image_url" />
    <div v-if="!token" class="selectLoginOrRegistration">
      <span>登录</span>
    </div>
    <!-- 用户头像和用户名 -->
    <el-dropdown v-else trigger="click" class="user">
      <span class="el-dropdown-link">
        <img
          class="avatar"
          :src="token.image_url ? token.image_url : require('@/assets/header/avatar-default.png')"
          alt="head portrait"
        />
        <span class="real_name">{{ token.user_real_name }}</span>
      </span>
      <el-dropdown-menu slot="dropdown" class="user-menu">
        <el-dropdown-item @click.native="logout">
          <img :src="require('@/assets/header/exit.png')" /><span>退出登录</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </header>
</template>

<script>
import { getToken } from '@/utils/auth';

export default {
  name: 'LayoutAnswerHeader',
  data() {
    const token = getToken();

    return {
      token,
    };
  },
  watch: {
    '$store.state.user.access_token': {
      handler() {
        this.token = getToken();
      },
    },
  },
  methods: {
    logout() {
      this.$store.dispatch('user/signOut');
      window.location.href = '/';
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  position: sticky;
  top: 0;
  left: 0;
  display: flex;
  column-gap: 24px;
  align-items: center;
  justify-content: space-between;
  height: $header-h;
  padding: 0 24px;
  overflow: hidden;
  background-color: #fff;
  border-bottom: 1px solid #ebebeb;

  .logo {
    height: 48px;
    margin-right: 36px;
  }

  .user {
    cursor: pointer;

    .el-dropdown-link {
      display: flex;
      align-items: center;

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
      }

      .real_name {
        display: inline-block;
        padding-left: 10px;
        font-size: 16px;
        color: #000;
        vertical-align: super;
      }
    }
  }
}
</style>

<style lang="scss">
.user-menu {
  min-width: 156px;

  .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #000;

    img {
      width: 24px;
      height: 24px;
      margin-right: 10px;
    }
  }
}
</style>
