<template>
  <view class="rating">
    <view v-for="index in maxStars" :key="index" class="star" :style="{ fontSize: size }">
      <view
        class="filled"
        :style="{
          width: getStarWidth(index) + '%',
          color: color,
        }"
      >
        ★
      </view>
      ★
    </view>
  </view>
</template>

<script>
export default {
  name: 'Rating',
  props: {
    score: {
      type: Number,
      required: true,
    },
    maxStars: {
      type: Number,
      default: 5,
    },
    color: {
      type: String,
      default: '#FA5151',
    },
    size: {
      type: String,
      default: '30rpx',
    },
  },
  methods: {
    getStarWidth(index) {
      const fullStars = Math.floor(this.score);
      const fraction = this.score - fullStars;

      if (index <= fullStars) {
        return 100;
      } else if (index === fullStars + 1) {
        return fraction * 100;
      } else {
        return 0;
      }
    },
  },
};
</script>

<style scoped>
.rating {
  display: flex;
}

.star {
  position: relative;
  font-size: 22rpx;
  color: #d3d3d3;
}

.filled {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  overflow: hidden;
}
</style>
