<template>
  <div class="avatar-wrapper" :style="{backgroundColor: backgroundColor}">
    <el-avatar :size="size" :src="src" v-if="src"/>
    <el-avatar :size="size" v-else :style="{fontSize: fontSize}">
      {{ 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
    },
  },
  computed: {
    fontSize() {
      return `${this.size / 1.8}px`
    },
    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 = [
        '#90CAF9', // 蓝色
        '#CE93D8', // 紫色
        '#FFB74D', // 橙色
        '#81D4FA', // 天蓝色
        '#F48FB1', // 粉色
        '#E57373', // 红色
        '#9575CD', // 深紫色
        '#4DB6AC', // 青色
        '#FF8A65', // 珊瑚色
        '#7986CB'  // 靛蓝色
      ]
      // 将中文字符串转换为数字
      const nameStr = this.name || ''
      const sum = nameStr.split('').reduce((acc, char) => {
        return acc + char.charCodeAt(0)
      }, 0)
      const index = Math.abs(sum) % 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>