<script setup>
import { computed, ref, watch } from "vue";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { getLvlImage } = store;
const { config } = storeToRefs(store);
const props = defineProps({
  src: {
    type: String,
    default: "",
  },
  rankLvl: {
    type: Number,
    default: undefined,
  },
  onClick: {
    type: Function,
    default: () => {},
  },
  rank: {
    type: Number,
    default: 0,
  },
  size: {
    type: Number,
    default: 45,
  },
  sizeUnit: {
    type: String,
    default: "px",
  },
  imageMode: {
    type: String,
    default: "widthFix",
  },
  borderColor: {
    type: String,
    default: "",
  },
});
const avatarFrame = ref("");
const sizeValue = computed(() => `${Number(props.size)}${props.sizeUnit}`);
const frameSizeValue = computed(() => `${Number(props.size) + 10}${props.sizeUnit}`);
const avatarImageStyle = computed(() => ({
  width: sizeValue.value,
  height: sizeValue.value,
  minHeight: sizeValue.value,
  borderColor: props.borderColor || "#fff",
}));
const avatarFrameStyle = computed(() => ({
  width: frameSizeValue.value,
  height: frameSizeValue.value,
}));

watch(
  () => [config.value, props.rankLvl],
  () => {
    if (props.rankLvl !== undefined) {
      avatarFrame.value = getLvlImage(props.rankLvl);
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <view class="avatar" @click="onClick">
    <image
      v-if="avatarFrame"
      :src="avatarFrame"
      mode="widthFix"
      :style="avatarFrameStyle"
      class="avatar-frame"
    />
    <image
      v-if="rank === 1"
      src="../static/champ1.png"
      mode="widthFix"
      class="avatar-rank"
    />
    <image
      v-if="rank === 2"
      src="../static/champ2.png"
      mode="widthFix"
      class="avatar-rank"
    />
    <image
      v-if="rank === 3"
      src="../static/champ3.png"
      mode="widthFix"
      class="avatar-rank"
    />
    <view v-if="rank > 3" class="rank-view">{{ rank }}</view>
    <image
      :src="src || '../static/user-icon.png'"
      :mode="imageMode"
      :style="avatarImageStyle"
      class="avatar-image"
    />
  </view>
</template>

<style scoped>
.avatar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-frame {
  position: absolute;
}
.avatar-rank,
.rank-view {
  position: absolute;
  width: 20px;
  height: 15px;
  top: -6px;
  right: -4px;
}
.rank-view {
  background-color: #6d6d6d;
  text-align: center;
  line-height: 15px;
  font-size: 12px;
  border-top-left-radius: 50%;
  border-bottom-right-radius: 50%;
}
.avatar-image {
  border-radius: 50%;
  border: 1px solid #fff;
}
</style>
