<template>
  <div class="user-avatar" :style="avatarStyle" :title="name">
    {{ avatarText }}
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'

const props = defineProps({
  name: {
    type: String,
    required: false,
    default: '未知'
  },
  size: {
    type: Number,
    default: 40
  },
  userId: {
    type: [Number, String],
    default: 0
  }
})

// 预设的莫兰迪色系背景，柔和护眼
const backgroundColors = [
  '#7265e6', '#ffbf00', '#00a2ae', '#f56a00', '#1890ff', 
  '#69c0ff', '#87e8de', '#ff85c0', '#5cdbd3', '#ffc069'
]

// 根据 UserID 或 名字 计算固定的背景色
const backgroundColor = computed(() => {
  let hash = 0
  const seed = props.userId ? props.userId.toString() : props.name
  for (let i = 0; i < seed.length; i++) {
    hash = seed.charCodeAt(i) + ((hash << 5) - hash)
  }
  const index = Math.abs(hash % backgroundColors.length)
  return backgroundColors[index]
})

// 提取文字逻辑：中文取后2位，英文取前2位大写
const avatarText = computed(() => {
  const name = props.name ? props.name.trim() : '?'
  if (!name) return '?'
  
  // 判断是否包含中文字符
  if (/[\u4e00-\u9fa5]/.test(name)) {
    return name.length > 2 ? name.slice(-2) : name
  }
  // 英文名取前两个字母
  return name.slice(0, 2).toUpperCase()
})

const avatarStyle = computed(() => ({
  width: `${props.size}px`,
  height: `${props.size}px`,
  lineHeight: `${props.size}px`,
  fontSize: `${props.size * 0.4}px`, // 字体大小随尺寸自适应
  backgroundColor: backgroundColor.value,
  borderRadius: '50%', // 圆形
  color: '#fff',
  textAlign: 'center' as const,
  display: 'inline-block',
  fontWeight: 'bold',
  flexShrink: 0 // 防止在 Flex 布局中被压缩
}))
</script>

<style scoped>
.user-avatar {
  user-select: none;
  cursor: pointer;
  transition: opacity 0.2s;
}
.user-avatar:hover {
  opacity: 0.9;
}
</style>