<template>
	<view class="u-flex number-box">
		<view class="u-flex u-flex-1">
			<up-input @blur="priceFormat" border="none" v-model="number" type="number" :placeholder="placeholder"></up-input>
		</view>
		<view class="u-flex u-flex-col right">
			<view class="u-flex-1 u-p-l-8 u-p-r-8" @click="changeNumber('add')">
				<up-icon name="arrow-up" color="#E5E5E5"></up-icon>
			</view>
			<view class="line"></view>
			<view class="u-flex-1 u-p-l-8 u-p-r-8" @click="changeNumber('reduce')">
				<up-icon name="arrow-down" color="#E5E5E5"></up-icon>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		formatPrice
	} from "@/commons/utils/format.js";
	import {
		ref,
		watch,nextTick
	} from 'vue';
	const props = defineProps({
		modelValue: {
			type: [String, Number]
		},
		min: {
			type: Number,
			default: 0
		},
		max: {
			type: Number,
			default: 999999999
		},
		step: {
			type: Number,
			default: 1
		},
		placeholder: {
			type: String,
			default: '请输入'
		}
	})
	let number = ref(props.modelValue)

	function changeNumber(type) {
		const newval = number.value + props.step * (type == 'add' ? 1 : -1)
		if (newval < props.min) {
			number.value = props.min
		}
		if (newval > props.max) {
			number.value = props.max
		}
		priceFormat(newval)
	}

	function priceFormat(e) {
		nextTick(() => {
			const min = props
				.min;
			const max = props.max;
			if (e === '') {
				return
			}
			const newval = formatPrice(e, min, max, true)
			if (typeof newval !== 'number') {
				number.value = newval.value
				uni.showToast({
					title: `请输入${min}到${max}范围内的数字`,
					icon: 'none'
				})
			} else {
				number.value = newval
			}
		})
	}
	watch(() => props.modelValue, (newval) => {
		number.value = newval
	})
	const emits = defineEmits(['update:modelValue'])
	watch(() => number.value, (newval) => {
		emits('update:modelValue', newval)
	})
</script>

<style lang="scss" scoped>
	.line {
		width: 100%;
		height: 1px;
		background-color: #E5E5E5;
	}

	.number-box {
		border: 1px solid #E5E5E5;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		padding-left: 24rpx;

		.right {
			border-left: 1px solid #E5E5E5;
		}
	}
</style>