<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="barCode" placeholder="请输入单据号进行搜索" @confirm="submit"
					:border="true" />
				<u-action-sheet :list="actionSheetList" v-model="showActionSheet" @click="actionSheetCallback">
				</u-action-sheet>
			</u-form-item>
			<!-- <u-form-item :border-bottom="false">
				<picker @change="bindPickerChange" :range="ReceiveDetailArray">
					<label>选择行：</label>
					<label class=""> {{ selectedValue }}</label>
					<br />
					<div class="row">
						<div class="col">
							<label>物料属性：{{MATERIALSPECNAME}}</label>
						</div>
						<div class="col">
							<label> 物料规格：{{SDK_ID}}</label>
						</div>
					</div>
				</picker>
			</u-form-item> -->
			<!-- <u-form-item :border-bottom="false">
				<u-row>
					<u-col span="20">
						<picker mode="date" :end="endDate" @change="bindDateChange">
							<label>制造日期：</label>{{date}}
						</picker>
					</u-col>
				</u-row>
			</u-form-item> -->
			<!-- <u-card style="border: 1rpx solid #0081ff" :show-head="false" :full="true"
				:body-style="{ height: '100rpx' }">
				<view slot="body">
					<u-row>
						<u-col span="6">
							<view>应扫数量：{{ PLAN_QTY || '0' }} {{MATERIALUNIT}}</view>
						</u-col>
						<u-col span="6">
							<view>扫码数量：{{ PRTBARCODEQTY || '0' }} {{MATERIALUNIT}}</view>
						</u-col>
					</u-row>
				</view>
			</u-card> -->
			<u-form-item>
						<p>选择位置：</p>
						<u-input class="uni-input" v-model="Localtion" :focus="focusKw" placeholder="请扫描供应商条码"
							: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>
		<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 {
				Localtion: '',
				ActNo: '',
				SUPPLIERNAME: '', //供应商
				ERPLOCATION: '',
				MATERIALUNIT: '', //单位
				REQUESTQUANTITY: '', //明细中的数量
				barCode: "", //单据编号
				selectedValue: '', //选中的行号
				MATERIALSPECNAME: '', //选中行号带出的物料信息
				SDK_ID: '', //SDK规格
				date: this.getDate(),
				PLAN_QTY: 0,
				PRTBARCODEQTY: 0,
				MaterialPackingcode: '', //标签编号
				LocalName: '', //位置
				materialList: [], //接收后端传回来的数据
				ischecked: false, //默认不使用库位
				matData: [], //后端传回来的绑定表格的数据
				focusKw: false, //库位输入框焦点
				items: ['物料清单'], //'材料列表', 
				focusBarcode: true, //默认聚焦到条码框	
				styleType: 'button',
				current: 0,
				barCode: '',
				actionSheetList: [], // 用于存储查询结果的列表  
				ReceiveDetailArray: [], // 用于存储明细查询明细号结果的列表
				ReceiveDetailAllArray: [], //用于存储明细查询明细所有结果的列表
				showActionSheet: false, // 控制下拉列表的显示与隐藏  
				focusBarcode: false, // 控制输入框的焦点状态  
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				}, //返回按钮的样式
				useId: "",
				//对应的材料列表
				matColumns: [{
						title: '标签编号',
						field: "MATERIALPACKINGNAME",
						width: 120,
						sort: true,
						align: "left"
					},
					{
						title: '单据',
						field: "RECEIVEREQUESTNAME",
						width: 150,
						sort: true,
						align: "right"
					},
					{
						title: '单据明细',
						field: "RECEIVEREQUESTDETAILNAME",
						width: 150,
						sort: true,
						align: "right"
					},
					{
						title: '货位',
						field: "LOCATIONNAME",
						width: 260,
						sort: true,
						align: "left"
					},
					{
						title: '抬头文本',
						field: "RECEIVEACTNO",
						width: 280,
						sort: true,
						align: "left"
					},

					{
						title: '物料编号',
						field: "MATERIALSPECNAME",
						width: 150,
						sort: true,
						align: "right"
					},
					{
						title: '入库时间',
						field: "MAKEDATE",
						width: 150,
						sort: true,
						align: "right"
					},
					{
						title: '数量',
						field: "REQUESTQUANTITY",
						width: 150,
						sort: true,
						align: "right"
					}
				],
			};

		},

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

		methods: {
			bindPickerChange(e) {
				this.selectedValue = this.ReceiveDetailArray[e.detail.value]; // 假设e.detail.value是索引  
				// 您可以根据索引或其他逻辑更新物料属性和物料规格  
				this.SDK_ID = this.ReceiveDetailAllArray[e.detail.value].SDK_ID;
				this.MATERIALSPECNAME = this.ReceiveDetailAllArray[e.detail.value].DESCRIPTION;
				this.MATERIALUNIT = this.ReceiveDetailAllArray[e.detail.value].MATERIALUNIT;
				this.SUPPLIERNAME = this.ReceiveDetailAllArray[e.detail.value].SUPPLIERNAME;
				this.ERPLOCATION = this.ReceiveDetailAllArray[e.detail.value].ERPLOCATION;
				console.log("this.ReceiveDetailAllArray[e.detail.value].REQUESTQUANTITY")
				this.PLAN_QTY=this.PLAN_QTY+parseInt(this.ReceiveDetailAllArray[e.detail.value].REQUESTQUANTITY)
				this.CreateActNo();
				
				let colum1 = this.isWeightOrLength(this.MATERIALUNIT)
				if (colum1.type == 'weight') {
					this.MATERIALUNIT = colum1.unit
				} else if (colum1.type == 'length') {
					this.MATERIALUNIT = colum1.unit
				} else {
					this.MATERIALUNIT = '个';
				};
				
			},
			CreateActNo() {
				this.$MyRequest('/bpel/event', {
					header: {
						MESSAGENAME: 'GenerateActNo',
						LANGUAGE: 'Chinese',
						Flag: 'LK', //立库标志
						User: ''
					},
					body: {
						SITENAME: 'SDK',
						ACTTYPE: 'Normal',
					}
				}).then(res => {
					if (res.data.code == "0") {
						this.ActNo = res.data.data.RECEIVEACTNO
					} else {

					}
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			//设置选中状态
			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
				})
			},

			//单据编号查询事件（待补充）
			searchMaterialStockIn() {
				this.$MyRequest('', {}).then(res => {}).catch(err => {
					this.$showMessage(err)
				})
			},
			//用来选择行号，行号唯一就自动选择
			QueryReceiveDetail: function(e) { //改变的事件名
				this.ReceiveDetailArray = [];
				this.$MyRequest('/api/ApiQuery', {
					queryId: "GetMaterialReceiveActDetail",
					version: "00001",
					params: {
						RECEIVEREQUESTNAME: this.barCode,
					}
				}).then(res => {
					if (res.data.message == "SUCCESS!") {
						for (const item of res.data.data) {
							this.ReceiveDetailAllArray.push(item)
							this.ReceiveDetailArray.push(item.RECEIVEREQUESTDETAILNAME);
						}
					}
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			computed: {
				endDate() {
					return this.getDate();
				}
			},
			bindDateChange: function(e) {
				this.date = e.detail.value;
			},
			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}`;
			},
			submit() {
				this.actionSheetList = [];
				//发送请求
				this.$MyRequest('/api/ApiQuery', {
					queryId: "GetPdaMaterialReceiveRequest",
					version: "00001",
					params: {
						MATERIALPACKINGNAME: this.barCode,
					}
				}).then(res => {
					if (res.data.message == "SUCCESS!") {
						for (const item of res.data.data) {
							this.actionSheetList.push({
								text: item.RECEIVEREQUESTNAME,
								color: 'blue',
								fontSize: 28
							});

						}
						this.showActionSheet = true;
					} else {
						this.actionSheetList = [];
						this.showActionSheet = true;
					}
				}).catch(err => {
					this.$showMessage(err)
				})

			},
			submit2() {
				const str = this.MaterialPackingcode;
				const elements = str.split("|");
				//发送请求
				this.$MyRequest('/bpel/event', {
					header: {
						MESSAGENAME: 'CreateBoxByLabel',
						LANGUAGE: 'Chinese',
						Flag: 'LK' //立库标志
					},
					body: {
						RECEIVEREQUESTDETAILNAME: this.selectedValue,
						MATERIALPACKINGNAME: elements[4],
						SITENAME: 'SDK',
						RECEIVEREQUESTNAME: this.barCode,
						LOCATIONNAME: this.Localtion,
						RECEIVEQTY: elements[7],
						RECEIVEACTNO: this.ActNo,
						MAKEDATE: this.formatDate(elements[5]) ,
						EXPIRINGDATE: '',
						MATERIALSPECNAME: elements[0],
						SUPPLIERNAME: this.SUPPLIERNAME,
						ERPLOCATION: this.ERPLOCATION,

					}
				}).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)
				})

			},
			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`;
			},
			isWeightOrLength(quantityString) {
				// 常见的重量单位  
				const weightUnits = ['g', 'kg', 'lb', 'oz', 'ton', 'mg']; // 添加你需要的单位  

				// 常见的长度单位  
				const lengthUnits = ['cm', 'm', 'km', 'mm', 'in', 'ft', 'yd', 'mi']; // 添加你需要的单位  

				// 转换为小写以进行不区分大小写的比较  
				const lowerCaseString = quantityString.toLowerCase();

				// 检查是否包含任何重量单位  
				for (let unit of weightUnits) {
					if (lowerCaseString.equals(unit)) {
						return {
							type: 'weight',
							unit: unit
						};
					}
				}

				// 如果没有找到重量单位，则检查长度单位  
				for (let unit of lengthUnits) {
					if (lowerCaseString.equals(unit)) {
						return {
							type: 'length',
							unit: unit
						};
					}
				}

				// 如果没有找到任何单位，返回null或undefined  
				return null;
			},
			searchMaterialStockIn() {
				// 发送请求到后端进行模糊查询  
				this.fetchSearchResults(this.barCode);
			},
			fetchSearchResults(query) {
				// 假设您有一个API或方法来执行模糊查询  
				// 这里使用Promise模拟异步请求  
				this.$api.searchMaterialStockIn(query).then(response => {
					// 假设response.data是查询结果列表  
					this.actionSheetList = response.data;
					// 显示下拉列表  
					this.showActionSheet = true;
				}).catch(error => {
					// 处理错误  
				});
			},
			actionSheetCallback(item) {
				// 用户在下拉列表中选择了一个项目  
				this.barCode = this.actionSheetList[item].text; // 更新输入框的值  
				this.showActionSheet = false; // 关闭下拉列表  
				this.QueryReceiveDetail();
				// 如果需要，您可以发送请求到后端处理选择的结果  
			},
		}
	}
</script>

<style lang="scss">

</style>
