<template>
	<uni-data-select v-model="secondUnitId" :localdata="unitOptions" @change="secondUnitChange" style="z-index: 100;">
	</uni-data-select>
</template>

<script>
	import {
		listUnitConvertible,
		convertBySecondUnitOrNum,
	} from "@/api/basic/unit";

	export default {
		name: "selectUnitConvertible",
		props: {
			materialCode: {
				type: String,
				default: "",
			},
			// secondUnitId
			value: {
				type: Number,
				default: null,
			},
			secondNumber: {
				type: Number,
				default: null,
			},
			number: {
				type: Number,
				default: null,
			},
			unitId: {
				type: Number,
				default: null,
			},
			disabled: Boolean,
		},
		watch: {
			materialCode: {
				handler(newVal, oldVal) {
					console.log(newVal)
					this.selectConvertibleUnitList();
				},
				immediate: true,
			},
			value: {
				handler(newVal) {
					console.log(newVal)
					this.secondUnitId = newVal;
					this.selectConvertibleUnitList();
				},
				immediate: true,
			},
		},
		created() {
			this.selectConvertibleUnitList();
		},
		data() {
			return {
				secondUnitId: null,
				unitOptions: [],
			};
		},
		methods: {
			//单位下拉框点击事件
			selectConvertibleUnitList() {
				let query = {
					materialCode: this.materialCode,
					id: this.value,
				};
				listUnitConvertible(query).then((response) => {
					this.unitOptions = response.rows.map(item => {
						let obj = {
							text: item.unitCode + ":" + item.unitName,
							value: item.id
						}
						return obj
					});
				});
			},
			/**第二单位（显示单位改变）
			 * 要求基本单位和数量不为空 
			 * */
			secondUnitChange(e) {
				console.log(e, this.secondUnitId)
				// 给单位赋值 
				this.$emit("input", e);
				//   console.log(
				//     "unitParams",
				//     this.materialCode,
				//     this.number,
				//     this.unitId,
				//     this.secondNumber,
				//     this.secondUnitId
				//   );
				if (
					this.number &&
					this.unitId &&
					this.materialCode &&
					this.materialCode != "" &&
					e
				) {
					let params = {
						materialCode: this.materialCode,
						number: this.number,
						unitId: this.unitId,
						secondUnitId: e,
						secondNumber: null,
					};

					// 修改第二数量
					convertBySecondUnitOrNum(params).then((response) => {
						this.$emit("update:secondNumber", response.data.secondNumber);
					});
				}
			},
		},
	};
</script>

<style>
</style>