<template>
  <view 
    :class="[
      'nana-avatar',
      round ? 'round' : '',
    ]"
    :style="style"
    @click="$emit('click')"
  >
    <image 
      v-if="url || defaultAvatar" :src="url || defaultAvatar"
      :style="{
        width: themeContext.resolveThemeSize(size),
        height: themeContext.resolveThemeSize(size),
      }"
    />
    <text 
      v-else 
      :style="{ 
        width: themeContext.resolveThemeSize(size),
        height: themeContext.resolveThemeSize(size),
        lineHeight: themeContext.resolveThemeSize(size),
        color: textColor,
        ...textStyle
      }"
    >
      {{ text }}
    </text>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { propGetThemeVar, useTheme } from '../theme/ThemeDefine';

const themeContext = useTheme();

export interface AvatarProps {
  /**
   * 默认头像，在 url 为空或者加载失败时使用此头像
   */
  defaultAvatar?: string,
  /**
   * 随机背景颜色
   */
  randomColor?: boolean,
  /**
   * 头像的图标URL
   */
  url?: string,
  /**
   * 背景颜色
   */
  background?: string,
  /**
   * 当未提供 url 时，支持在头像上显示文字, 建议显示1-2个汉字
   */
  text?: string,
  /**
   * 文字的颜色
   * @default '#fff'
   */
  textColor?: string,
  /**
   * 文字的样式
   */
  textStyle?: object,
  /**
   * 头像的样式
   */
  innerStyle?: object,
  /**
   * 头像的大小。
   * @default 40
   */
  size?: number,
  /**
   * 头像圆角大小
   * @default 0
   */
  radius?: number,
  /**
   * 头像是否是圆型，设置后 radius 无效
   * @default false
   */
  round?: boolean,
}

const props = withDefaults(defineProps<AvatarProps>(), {
  defaultAvatar: '',
  background: () => propGetThemeVar('AvatarBackground', 'background.imageBox'),
  url: '',
  text: '',
  textColor: () => propGetThemeVar('AvatarTextColor', 'text.content'),
  size: () => propGetThemeVar('AvatarSize', 70),
  radius: () => propGetThemeVar('AvatarRadius', 0),
  round: () => propGetThemeVar('AvatarRound', true),
});

const randomBackgroundColors = [
  'background.primary', 'background.danger', 'background.success', 'background.warning',
]

const style = computed(() => {
  return {
    backgroundColor: themeContext.resolveThemeColor(props.randomColor ? 
      randomBackgroundColors[Math.floor(Math.random() * randomBackgroundColors.length)] :
      props.background
    ),
    borderRadius: props.round ? 
      themeContext.resolveThemeSize('AvatarRoundRadius', '50%') : 
      themeContext.resolveThemeSize(props.radius),
    width: themeContext.resolveThemeSize(props.size),
    height: themeContext.resolveThemeSize(props.size),
    ...props.innerStyle,
  }
});

defineEmits([ 'click' ]);
</script>

<style lang="scss">
.nana-avatar {
  overflow: hidden;
  flex-shrink: 0;

  text {
    display: block;
    text-align: center;
    user-select: none;
    font-weight: bold;
  }
}
</style>