<template>
	<view class="_star" :class="{_left:left,_disabled:disabled}">
		<input type="hidden" :name="name" :value="innervalue" style="display:none;" />
		<view @tap="selstar(item.id)" :class="item.cls" v-for="(item, index) in stars" :key="index" :style="{width:size,height:size}"></view>
	</view>
</template>

<script>
	export default {
		behaviors: ['uni://form-field-group'],
		emits: ['change', 'update:modelValue', 'update:value'],
		props: {
			name: {
				type: String
			},
			modelValue: {
				type: [String, Number]
			},
			value: {
				type: [String, Number]
			},
			disabled: {
				type: Boolean,
				default: false
			},
			initevent: {
				type: Boolean,
				default: false
			},
			left: {
				type: Boolean,
				default: false
			},
			maxstar: {
				type: [String, Number],
				default: 5
			},
			size: {
				type: String,
				default: '2em'
			},
		},
		data() {
			return {
				innervalue: this.modelValue !== undefined ? this.modelValue : this.value
			};
		},
		watch: {
			modelValue(newD) {
				if (newD !== undefined) {
					this.innervalue = newD;
				}
			},
			value(newD) {
				if (this.modelValue === undefined) {
					this.innervalue = newD;
				}
			}
		},
		computed: {
			stars() {
				var stars = [];
				for (var i = 1; i <= this.maxstar; i++) {
					if (i <= this.innervalue)
						stars.push({
							id: i,
							cls: '_sel'
						});
					else
						stars.push({
							id: i,
							cls: '_unsel'
						});
				}
				return stars;
			},
		},
		mounted() {
			if (this.initevent) {
				this.$emit('change', {
					name: this.name,
					from: 'init',
					value: this.innervalue
				});
			}
		},
		methods: {
			updatevalue(val) {
				if (val > this.maxstar)
					val = this.maxstar;
				this.innervalue = val;
			},
			selstar(id) {
				if (this.disabled)
					return;
				var val = this.toint(id);
				this.updatevalue(val);
				this.$emit('update:modelValue', val);
				this.$emit('change', {
					name: this.name,
					from: 'click',
					value: val
				});
			}
		}
	}
</script>
<style scoped>
	._star {
		display: flex;
		justify-content: flex-end;
	}

	._star._left {
		justify-content: start;
	}

	._star._disabled ._sel,
	._star._disabled ._unsel {
		opacity: 0.3;
	}

	._star ._sel {
		width: 2em;
		height: 2em;
		background-image: url("data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDA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