<template>
  <div
    class="avatar-wrapper"
    :style="{
      backgroundColor: backgroundColor
    }"
  >
    <el-avatar
      :size="size"
      :src="src"
      v-if="src"
    >
    </el-avatar>
    <el-avatar
      :size="size"
      v-else
    >
      {{ displayChar }}
    </el-avatar>
  </div>
</template>

<script>
export default {
  name: 'Avatar',
  props: {
    size: {
      type: Number,
      default: 24
    },
    src: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    charIndex: {
      type: Number,
      default: 0
    },
    id: {
      type: [String, Number],
      default: ''
    }
  },
  computed: {
    displayChar() {
      if (!this.name) {
        return '?';
      }
      if (this.charIndex < 0) {
        return this.name.charAt(this.name.length + this.charIndex);
      }
      return this.name.charAt(this.charIndex);
    },
    backgroundColor() {
      const colors = [
        '#BBDEFB', // 浅蓝色
        '#E1BEE7', // 浅紫色
        '#C8E6C9', // 浅绿色
        '#FFE0B2', // 浅橙色
        '#CFD8DC', // 浅灰蓝色
        '#B3E5FC', // 天蓝色
        '#F8BBD0', // 浅粉色
        '#D7CCC8'  // 浅棕色
      ]
      const index = parseInt(this.id) % colors.length
      return colors[index]
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;

  ::v-deep .el-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: inherit;
    font-size: 16px;
  }
}
</style>