<template>
	<view class="wrpper flex j-between a-center" @touchmove.stop.prevent="clear">
		<view 
			class="btn iconfont icon-jianhao flex j-center a-center"
			:class="calVal <= min ? 'disabled' : null"
			@click.stop="subtraction"
		></view>
		<input 
			class="input"
			type="number"
			v-model="calVal"
			@confirm="inputVal"
			@blur="inputVal"
		/>
		<view 
			class="btn iconfont icon-hao flex j-center a-center"
			:class="(max && (calVal >= max)) ? 'disabled' : null"
			@click.stop="add"
		></view>
	</view>
</template>

<script>
import { throttle } from '@/utils/common.js'
export default {
	props: {
		min: {
			type: Number,
			default: 0
		},
		max: {
			type: Number,
			default: 0
		},
		defaultVal: {
			type: Number,
			default: 1
		},
		params: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			calVal: this.defaultVal
		}
	},
	watch: {
		// calVal用于内部计算，但是父组件改变了defaultVal的值会不更新calVal(临时解决)
		defaultVal(newVal) {
			this.calVal = ~~newVal
		},
		calVal: throttle(function(newVal) {
			const max = this.max
			const min = this.min
			const newVal_number = ~~newVal
			if(max && newVal_number >= max) return
			if(newVal_number <= min) return
			this.$emit('change', {
				params: this.params,
				val: newVal_number
			})
		}, 500)
	},
	methods: {
		clear(e) {
			// TODO nvue 取消冒泡
			e.stopPropagation()
			return
		},
		subtraction() {
			const val = this.calVal
			if(val <= this.min) return this.$toast({title: `数量不能少于${this.min}`})
			this.calVal -= 1
		},
		add() {
			const val = this.calVal
			const max = this.max
			if(max && val >= max) {
				this.calVal = max
				this.$toast({title: '数量不能大于商品库存'})
				return
			}
			this.calVal += 1
		},
		inputVal(e) {
			let inputVal = ~~e.detail.value
			const max = this.max
			const min = this.min
			if(max && inputVal >= max) {
				inputVal = max
				this.$toast({title: '数量不能大于商品库存'})
			} else if(inputVal < min) {
				inputVal = min
				this.$toast({title: `数量不能少于${min}`})
			}
			this.calVal = inputVal
		}
	}
}
</script>

<style lang="scss" scoped>
@import "./iconfont.css";
.wrpper {
	width: 100%;
	height: 100%;
	display: inline-block;
	display: flex;
	justify-content: space-around;
	align-items: center;
	text-align: center;
	background-color: #fff;
	.btn {
		display: inline-block;
		width: 34rpx;
		height: 100%;
	}
	.disabled {
		color: #ccc!important;
	}
	.input {
		width: 120rpx;
		height: 100%;
		border-radius: 4rpx;
		background-color: $mainBg;
	}
}
</style>
