<script setup>
import { ref, watch, onMounted } from "vue";
const props = defineProps({
  isRed: {
    type: Boolean,
    default: true,
  },
  team: {
    type: Array,
    default: () => [],
  },
  currentShooterId: {
    type: Number,
    default: "",
  },
  youTurn: {
    type: Boolean,
    default: false,
  },
});
const players = ref({});
const youTurn = ref(false);
const firstName = ref("");

onMounted(() => {
  props.team.forEach((p, index) => {
    players.value[p.id] = { sort: index, ...p };
  });
});

watch(
  () => props.currentShooterId,
  (newVal) => {
    if (!newVal) return;
    const index = props.team.findIndex((p) => p.id === newVal);
    youTurn.value = index >= 0;
    if (index >= 0) {
      const newPlayers = [...props.team];
      const target = newPlayers.splice(index, 1)[0];
      if (target) {
        newPlayers.unshift(target);
        firstName.value = target.name;
        newPlayers.forEach((p, index) => {
          players.value[p.id] = { sort: index, ...p };
        });
      }
    }
  },
  { immediate: true }
);
</script>

<template>
  <view class="container">
    <view
      v-for="(item, index) in team"
      :key="index"
      class="player"
      :style="{
        width:
          (youTurn ? 40 - ((players[item.id] || {}).sort || 0) * 5 : 35) + 'px',
        height:
          (youTurn ? 40 - ((players[item.id] || {}).sort || 0) * 5 : 35) + 'px',
        borderColor: isRed ? '#ff6060' : '#5fadff',
        zIndex: team.length - ((players[item.id] || {}).sort || 0),
        top: youTurn ? ((players[item.id] || {}).sort || 0) * 2 + 'px' : '6px',
        left:
          (isRed
            ? ((players[item.id] || {}).sort || 0) * 20
            : 35 - ((players[item.id] || {}).sort || 0) * 15) + 'px',
      }"
    >
      <image :src="item.avatar || '../static/user-icon.png'" mode="widthFix" />
      <text
        v-if="youTurn && ((players[item.id] || {}).sort || 0) === 0"
        :style="{ backgroundColor: isRed ? '#ff6060' : '#5fadff' }"
        >{{ isRed ? "红队" : "蓝队" }}</text
      >
    </view>
    <text
      v-if="youTurn"
      class="truncate"
      :style="{
        color: isRed ? '#ff6060' : '#5fadff',
        [isRed ? 'left' : 'right']: 0,
      }"
      >{{ firstName }}</text
    >
  </view>
</template>

<style scoped>
.container {
  display: flex;
  align-items: center;
  position: relative;
  width: 20vw;
  height: 45px;
}
.container > text {
  position: absolute;
  font-size: 10px;
  text-align: center;
  width: 40px;
  bottom: -12px;
}
.player {
  transition: all 0.3s ease;
  position: absolute;
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid;
}
.player > image {
  width: 100%;
}
.player > text {
  position: absolute;
  font-size: 8px;
  text-align: center;
  width: 40px;
  left: 0px;
  bottom: 0px;
  color: #fff;
}
</style>
