<template>
	<uni-easyinput v-model="inputNumber" placeholder="请输入数量" @change="change" :disabled="disabled" type="number" @input="input"/>
</template>

<script>
	import {
		listUnit,
		getUnit,
		delUnit,
		addUnit,
		updateUnit,
		listUnitConvertible,
		convertBySecondUnitOrNum,
	} from "@/api/basic/unit";

	export default {
		name: "secondNumberChangeToConvert",
		props: {
			materialCode: String,
			number: Number,
			unitId: Number,
			secondNumber: Number,
			secondUnitId: Number,
			disabled: Boolean,
		},
		watch: {
			// materialCode: {
			//   handler(newVal) {
			//     this.secondNumberChange();
			//   },
			// },
			secondNumber: {
				handler(newVal) {
					console.log('new',newVal);
					// 去重，防止重复请求
					if (Number(newVal) != this.inputNumber) {
						this.inputNumber = Number(newVal);
						if (this.inputNumber == null || this.inputNumber == "") {
							this.inputNumber = this.number;
							this.$emit("update:secondNumber", Number(this.inputNumber));
						}
						this.secondNumberChange();
					}
				},
				immediate: true,
			},
		},
		data() {
			return {
				unitOptions: [],
				inputNumber: null,
			};
		},
		methods: {
			input(data){
				console.log(data)
				this.$emit('input', data);
			},
			change(data) {
				console.log(data)
				this.$emit('change', data);
				this.onIuputChange()
			},
			onIuputChange() {
				// setTimeout(() => {
				// 需要延迟执行的代码
				this.$emit("update:secondNumber", Number(this.inputNumber));
				this.$emit("change", Number(this.inputNumber));
				this.secondNumberChange();
				// }, 200); // 0.2秒延迟

			},
			/**第二数量（数量改变）
			 * 要求基本单位和数量不为空
			 * */
			secondNumberChange() {
				//设置父组件的第一数量
				//   console.log(
				//     "convertParams",
				//     this.materialCode,
				//     this.inputNumber, 
				//     this.unitId,
				//     this.secondUnitId
				//   );
				console.log(this.inputNumber)
				// console.log('this.inputNumber',this.inputNumber)
				if (this.inputNumber == null || this.inputNumber == "") {
					this.$emit("update:number", 0);
				}
				if (this.unitId == null || this.unitId == "") {
					this.$emit("update:number", this.inputNumber);
				} else if (
					this.inputNumber &&
					this.materialCode &&
					this.materialCode != "" &&
					this.unitId &&
					this.secondUnitId
				) {
					console.log(this.inputNumber)
					let params = {
						materialCode: this.materialCode,
						number: null,
						unitId: this.unitId,
						secondUnitId: this.secondUnitId,
						secondNumber: this.inputNumber,
					};
					console.log(params)
					convertBySecondUnitOrNum(params).then((response) => {
						console.log(response.data.number)
						this.$emit("update:number", response.data.number);
					});
				} else { //其它所有异常情况，都将第二数量同步传给第一数量
					this.$emit("update:number", this.inputNumber);
				}
			},
		},
	};
</script>

<style>
</style>