<template>
	<view class="uni-rate" :class="['uni-rate-'+type]">
		<view :key="index" :style="{ marginLeft: margin + 'px' }" @click="_onClick(index)" class="uni-rate__icon" v-for="(star, index) in stars">
      <image class="uni-rate-icon" :src="valueSync>index?checkIcon:icon"></image>
		</view>
	</view>
</template>

<script>
	import uniIcons from "../uni-icons/uni-icons.vue";
	export default {
		name: "UniRate",
		components: {
			uniIcons
		},
		props: {
			color: {
				// 星星的颜色
				type: String,
				default: "#ececec"
			},
			activeColor: {
				// 星星选中状态颜色
				type: String,
				default: "#ffca3e"
			},
			size: {
				// 星星的大小
				type: [Number, String],
				default: 24
			},
			value: {
				// 当前评分
				type: [Number, String],
				default: 0
			},
			max: {
				// 最大评分
				type: [Number, String],
				default: 5
			},
			margin: {
				// 星星的间距
				type: [Number, String],
				default: 5
			},
			disabled: {
				// 是否可点击
				type: [Boolean, String],
				default: false
			},
      type:{
			  type:String,
        default:'default'
      },
		},
		data() {
			return {
				valueSync: "",
        icon: require('./images/rate.png'),
        checkIcon:require('./images/rate-active.png')
			};
		},
		computed: {
			stars() {
				const value = this.valueSync ? this.valueSync : 0;
				const starList = [];
				const floorValue = Math.floor(value);
				const ceilValue = Math.ceil(value);
				// console.log("ceilValue: " + ceilValue);
				// console.log("floorValue: " + floorValue);
				for (let i = 0; i < this.max; i++) {
					if (floorValue > i) {
						starList.push({
							activeWitch: "100%"
						});
					} else if (ceilValue - 1 === i) {
						starList.push({
							activeWitch: (value - floorValue) * 100 + "%"
						});
					} else {
						starList.push({
							activeWitch: "0"
						});
					}
				}
				//console.log("starList[4]: " + starList[4].activeWitch);
				return starList;
			}
		},
		created() {
			this.valueSync = Number(this.value);
		},
		methods: {
			_onClick(index) {
				if (this.disabled) {
					return;
				}
				this.valueSync = index + 1;
        this.$emit("input", this.valueSync);
				this.$emit("change", {
					value: this.valueSync
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.uni-rate {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		line-height: 0;
		font-size: 0;
		flex-direction: row;
	}

  .uni-rate-icon{
    width: 22upx;
    height: 22upx;
  }

  .uni-rate-comment .uni-rate-icon{
    width: 30upx;
    height: 30upx;
  }

  .uni-rate-icon:first-child{
    margin-left: 0 !important;
  }

	.uni-rate__icon {
		position: relative;
		line-height: 0;
		font-size: 0;
		display: inline-block;
	}

	.uni-rate__icon-on {
		overflow: hidden;
		position: absolute;
		top: 0;
		left: 0;
		line-height: 1;
		text-align: left;
	}
</style>
