<template>
  <div
    :class="bem([round?'round':'',type||'',size||''])"
    :style="style"
    @click="onClick"
  >
    <!--图片-->
    <a v-if="hasImage" class="image">
      <div v-if="badge" :class="bem('image-badge')" class="van-badge">{{ badge }}</div>
      <van-image ref="img" :src="thumb" :alt="alt" :error-icon="thumbError" :round="round" />
    </a>
    <!--图标-->
    <van-icon v-else-if="icon" :class-prefix="iconPrefix" :name="icon" :badge="badge" :style="iconStyle" />
    <!--字体-->
    <a v-else-if="text" :style="textStyle" class="text">
      <div v-if="badge" :class="bem('text-badge')" class="van-badge">{{ badge }}</div>
      {{ text|format(textSubstr) }}
    </a>
  </div>
</template>
<script>
import bem from '@/mixins/bem'
import { isDef, addUnit } from 'vant/lib/utils'

export default {
  name: 'ibps-avatar',
  filters: {
    format(value, length) {
      if (value === null || value === '') {
        return ''
      }
      if (value.length <= length) { return value }
      return value.substr(value.length - length, length)
    }
  },
  mixins: [bem],
  props: {
    color: String, // 文字的颜色
    type: String,
    size: String,
    bgColor: String, // 组件的背景色
    width: [String, Number],
    height: [String, Number],
    fontSize: {
      type: String // 尺寸
    },
    iconSize: {
      type: String // 尺寸
    },
    textSize: {
      type: String // 尺寸
    },
    thumb: String, // 头像
    thumbError: String, // 失败的头像
    alt: String, // 描述
    iconPrefix: String, // 图标
    icon: String, // 图标
    badge: [String, Number],
    text: String,
    textSubstr: {
      type: Number,
      default: 2
    },
    round: Boolean, // 圆形
    radius: [Number, String] // 圆角大小，默认单位为px
  },
  data() {
    return {
      imageSrc: this.thumb
    }
  },
  computed: {
    hasImage() {
      return this.thumb
    },
    style() {
      const style = {}

      if (isDef(this.width)) {
        style.width = addUnit(this.width)
      }

      if (isDef(this.height)) {
        style.height = addUnit(this.height)
      }

      if (isDef(this.radius)) {
        style.overflow = 'hidden'
        style.borderRadius = addUnit(this.radius)
      }
      if (isDef(this.fontSize)) {
        style.fontSize = addUnit(this.fontSize)
      }
      if (!this.hasImage && isDef(this.bgColor)) {
        style.backgroundColor = this.getColor(this.bgColor)
        style.borderColor = this.getColor(this.bgColor)
      }
      if (isDef(this.color)) {
        style.color = this.getColor(this.color)
      }

      return style
    },
    iconStyle() {
      const style = {}
      if (isDef(this.iconSize)) {
        style.fontSize = addUnit(this.iconSize)
      }
      return style
    },
    textStyle() {
      const style = {}
      if (isDef(this.textSize)) {
        style.fontSize = addUnit(this.textSize)
      }
      return style
    }
  },
  methods: {
    getColor(color) {
      return color
    },
    onClick(e) {
      this.$emit('click', e)
    }
  }
}
</script>
