Component({
  properties: {
    value: {
      type: Number,
      value: 0,
      observer: 'updateStars'
    },
    count: {
      type: Number,
      value: 0
    },
    showText: {
      type: Boolean,
      value: true
    },
    showCount: {
      type: Boolean,
      value: false
    },
    size: {
      type: Number,
      value: 28
    },
    readonly: {
      type: Boolean,
      value: true
    }
  },

  data: {
    stars: [1, 2, 3, 4, 5],
    halfValue: 0,
    valueText: ''
  },

  methods: {
    updateStars(val) {
      const v = parseFloat(val) || 0;
      this.setData({
        halfValue: v % 1 >= 0.25 ? v + 0.5 : Math.floor(v),
        valueText: v > 0 ? v.toFixed(1) : '暂无评分'
      });
    },

    onTap(e) {
      if (this.properties.readonly) return;
      // 计算点击位置对应的星级
      this.triggerEvent('change', { value: this.data.value });
    },

    onStarTap(e) {
      if (this.properties.readonly) return;
      const star = e.currentTarget.dataset.star;
      this.triggerEvent('change', { value: star });
    }
  },

  lifetimes: {
    attached() {
      this.updateStars(this.properties.value);
    }
  }
});
