<template>
	<view>
		<u-navbar back-text="返回" title="组托" :background="background"></u-navbar>
		<u-form>
			<u-form-item :border-bottom="false">
				<p>扫描托盘：</p>
				<u-input :focus="focusBarcode" v-model="SettobarCode" placeholder="请扫描托盘" @confirm="submit"
					:border="true" />
			</u-form-item>
			<u-form-item>
				<p>来料条码：</p>
				<u-input class="uni-input" v-model="MaterialPackingcode" :focus="focusKw" placeholder="请扫描供应商条码"
					:border="true" @confirm="submit2" />
			</u-form-item>
		</u-form>
		<u-form-item>
			<button type="primary" size="mini" @click="SettoSubmit">组托</button>
			<button type="warn" size="mini" @click="SettoDelete">删除</button>
		</u-form-item>
		<uni-segmented-control :current="current" :values="items" :style-type="styleType" :active-color="activeColor" />
		<view v-if="current === 0">
			<uni-z-table :style="{'height': tabH+'px'}" :tableData="matData" :columns="matColumns" :showBottomSum="true"
				:rowNumbers="true" :pagination="true">
			</uni-z-table>

		</view>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				SettobarCode: "", //单据编号
				date: this.getDate(),
				MaterialPackingcode: '', //标签编号
				LocalName: '', //位置
				materialList: [], //接收后端传回来的数据
				ischecked: false, //默认不使用库位
				matData: [], //后端传回来的绑定表格的数据
				focusKw: false, //库位输入框焦点
				items: ['物料清单'], //'材料列表', 
				focusBarcode: true, //默认聚焦到条码框	
				styleType: 'button',
				current: 0,
				actionSheetList: [], // 用于存储查询结果的列表  
				ReceiveDetailAllArray: [], //用于存储明细查询明细所有结果的列表
				showActionSheet: false, // 控制下拉列表的显示与隐藏  
				focusBarcode: false, // 控制输入框的焦点状态  
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				}, //返回按钮的样式
				useId: "",
				//对应的材料列表
				matColumns: [{
						title: '标签编号',
						field: "MATERIALPACKINGNAME",
						width: 420,
						sort: true,
						align: "left"
					},
					{
						title: '数量',
						field: "REQUESTQUANTITY",
						width: 200,
						sort: true,
						align: "right"
					}
				],
			};

		},

		mounted() {
			let that = this
			uni.getStorage({
				key: "userid",
				success(res) {
					that.userId = res.data
				}
			})
		},

		methods: {
			//设置选中状态
			changeischecked() {
				this.ischecked = !this.ischecked //设置选中状态
			},

			//焦点初始化，让页面所有的焦点同时只能存在一个
			initfocus() {
				this.focusKw = false //单号焦点
				this.focusBarcode = false //条码焦点
			},

			//获取焦点的公共方法
			getfocus(nextfocus) {
				this.initfocus()
				this[nextfocus] //不能用this.nextfocus
				this.$nextTick(() => { //vue是数据全部修改后才进行的视图更新，哪nextTick函数就是为了拿到最新的数据，还不懂的可以去百度
					this[nextfocus] = true
				})
			},


			getDate() {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},

			submit2() {
				const str = this.MaterialPackingcode;
				const elements = str.split("|");
				this.matData.push({
					"MATERIALPACKINGNAME":  this.MaterialPackingcode,
					"REQUESTQUANTITY": elements[7]
				})
			},
			formatDate(dateStr) {
				// 确保输入是有效的日期字符串（长度为8）  
				if (dateStr.length !== 8) {
					throw new Error('Invalid date format. Expected 8-digit YYYYMMDD format.');
				}

				// 将字符串分割为年、月、日  
				const year = dateStr.slice(0, 4);
				const month = dateStr.slice(4, 6);
				const day = dateStr.slice(6, 8);

				// 创建一个新的Date对象  
				const date = new Date(year, month - 1, day); // 注意月份是从0开始的  

				// 验证日期是否有效（例如，2月30日是无效的）  
				if (isNaN(date.getTime())) {
					throw new Error('Invalid date');
				}

				// 使用padStart方法确保月份和日期都是两位数  
				const formattedMonth = (month - 1).toString().padStart(2, '0');
				const formattedDay = day.toString().padStart(2, '0');

				// 返回格式化后的日期和时间字符串  
				return `${date.getFullYear()}-${formattedMonth}-${formattedDay} 00:00:00`;
			},


			fetchSearchResults(query) {
				// 假设您有一个API或方法来执行模糊查询  
				// 这里使用Promise模拟异步请求  
				this.$api.searchMaterialStockIn(query).then(response => {
					// 假设response.data是查询结果列表  
					this.actionSheetList = response.data;
					// 显示下拉列表  
					this.showActionSheet = true;
				}).catch(error => {
					// 处理错误  
				});
			},
			SettoSubmit() {
				if (this.matData.length > 0) {
					let MATERIALPACKINGList = [];
					for (let item of this.matData) {
						MATERIALPACKINGList.push({
							"MATERIALPACKINGNAME": item.MATERIALPACKINGNAME,
							"REQUESTQUANTITY": item.REQUESTQUANTITY
						})
					}
					this.$MyRequest('/bpel/event', {
						header: {
							MESSAGENAME: 'AssignBoxByTray',
							LANGUAGE: 'Chinese',
							Flag: 'LK' //立库标志
						},
						body: {
							SITENAME: 'SDK',
							DURABLENAME: this.SettobarCode,
							BOXList: MATERIALPACKINGList,
						}
					}).then(res => {
						if (res.data.code == "0") {
							this.matData.push(res.data.data)
							this.PRTBARCODEQTY = this.PRTBARCODEQTY + parseInt(elements[7])
							this.$showMessage(res.data.msg)
						}
					}).catch(err => {
						this.$showMessage(err)
					})
					this.matData = []
				}else{
					this.$showMessage("请先扫托盘和条码")
				}

			},
			SettoDelete() {
				for (let i = 0; i < this.matData.length; i++) {
					if (this.matData[i].rowChecked.toString() === 'true') {
						this.matData.splice(i, 1); // 删除索引为i的元素  
					}
				}
			}

		}
	}
</script>

<style lang="scss">

</style>
