<template>
	<view class="_input" :class="{_left:left,_disabled:disabled}">
		<view class="_btn" @tap="op(-1)">-</view>
		<input :name="name" :value="tvalue" @input="textinput" :disabled="disabled" @confirm="textconfirm" :cursor-spacing="120" :style="{width:width}" />
		<view class="_btn" @tap="op(1)">+</view>
	</view>
</template>

<script>
	export default {
		behaviors: ['uni://form-field-group'],
		emits: ['change', 'update:modelValue', 'input'],
		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
			},
			width: {
				type: String,
				default: "2em"
			},
			min: {
				type: [String, Number],
				default: 1
			},
			max: {
				type: [String, Number],
				default: 9999999
			}
		},
		data() {
			return {
				tvalue: 0
			};
		},
		watch: {
			modelValue(n, d) {
				this.emit(n, 'watch'); //computed不触发
			},
			value(n, d) {
				this.emit(n, 'watch'); //computed不触发
			}
		},
		computed: {
			innervalue() {
				var val = 0;
				if (this.modelValue)
					val = this.toint(this.modelValue);
				if (this.value)
					val = this.toint(this.value);
				if (val > this.max)
					val = this.max;
				if (val < this.min)
					val = this.min;
				this.tvalue = val;
				return val;
			}
		},
		mounted() {
			if (this.initevent) {
				this.emit(this.innervalue, 'init');
			}
		},
		methods: {
			emit(val, from) {
				val = this.toint(val);
				if (val > this.max)
					val = this.max;
				if (val < this.min)
					val = this.min;
				if (this.old === val)
					return;
				if (this.modelValue !== undefined && from != 'watch') {
					this.$emit('update:modelValue', val);
				} else {}
				this.tvalue = val;
				this.$emit('change', {
					name: this.name,
					from: from,
					value: val
				});
				this.old = val;
			},
			textinput(e) {
				this.emit(e.detail.value || e.data, 'input');
			},
			textconfirm(e) {
				this.emit(e.detail.value || e.data, 'confirm');
			},
			op(oe) {
				if (this.disabled)
					return;
				this.emit(this.tvalue + oe, 'op');
			}
		}
	}
</script>

<style scoped>
	._input {
		padding: 0;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		gap: 0.5em;
	}

	._input._left {
		justify-content: flex-start;
	}

	._input input {
		font-size: 1em;
		height: 2em;
		text-align: center;
	}

	._btn {
		background: linear-gradient(100deg, var(--bg4), var(--bg6));
		width: 2rem;
		height: 2rem;
		font-size: 1.5rem;
		text-align: center;
		line-height: 2rem;
		border-radius: 0.3em;
	}

	._input._disabled input {
		color: var(--txt1);
	}

	._input._disabled ._btn {
		color: var(--txt1);
		background: linear-gradient(100deg, var(--bg3), var(--bg5));
	}
</style>