<template>
	<view>
		<view>
			<!-- <u-navbar back-text="返回" title="成品入库" :background="background"></u-navbar> -->
			<navVar :mysNavConfig="navConfig" @onLeftClick="onLeftClick"></navVar>
		</view>
		<view style="margin: 10rpx;">
			<u-form ref="testForm">
				<view class="content" :class="{'collapsed': isCollapsed}">
					<u-form-item :border-bottom="false">
						<label>选择仓库:</label>&nbsp;&nbsp;&nbsp;&nbsp;
						<zxzUniDataSelect filterable v-model="ERPLOCATION" :localdata="items" @change="change">
						</zxzUniDataSelect>
					</u-form-item>
					<u-form-item :border-bottom="false">
						<label>选择库位:</label>&nbsp;&nbsp;&nbsp;&nbsp;
						<zxzUniDataSelect filterable v-model="LOCATIONNAME" :localdata="items_Location"
							@inputChange="getitems_LocationAll" @change="changeLocationName"></zxzUniDataSelect>
					</u-form-item>
					<zb-table style="height: 200upx;" ref="zbTable" :show-header="true" :columns="column" :stripe="true"
						:fit="true" :highlight="true" :border="true" :data="sumList"></zb-table>
				</view>

				<!-- 			<view class="header" @click="toggle">
					<text style="width: 100%; text-align: center; align-self: center; display: flex; background-color:#777777">点击折叠/展开</text>
				</view> -->

				<u-form-item :border-bottom="false">
					<p>扫描条码:</p>
					<u-input :border="true" v-model="MATERIALPACKINGNAME" placeholder="请扫描条码" :focus="focusBarCode"
						@confirm="ScanFGBarCode" />
				</u-form-item>
				<!-- <br /> -->
				<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>数量：{{ MATERIALQUANTITY || '0' }}</view>
							</u-col>
							<u-col span="6">
								<view>标签数：{{ JS || '0' }}</view>
							</u-col>
						</u-row>
					</view>
				</u-card>
				<view>
					<u-input v-if="false" v-model="opCode" />
					<uni-datetime-picker style="align-items: center;" type="date" :default-date="timeDate"
						:clear-icon="false" v-model="commitDate" @maskClick="maskClick" />
					<u-button @click="FGStockIn" type="primary" :loading="loading">确定</u-button>
				</view>
			</u-form>
			<br />
			<view class="search-box">
				<input type="text" placeholder="请输入搜索批次" v-model="searchBatch" class="search-input" />
			</view>
			<u-modal :show="showModal" :title="titleModal" :content='contentModal'></u-modal>
			<view class="container" style="height: 800upx;">
				<view class="list-item" v-for="(item, index) in BoxListInfo" :key="item.id"
					@touchstart="onTouchStart(index, $event)" @touchmove="onTouchMove(index, $event)"
					@touchend="onTouchEnd(item,index, $event)" :style="getItemStyle(index)">

					<view :class="setVisableCharge( item.CHARGE )">
						<view>
							<div>
								<text class="card-description"> 批次: {{ item.CHARGE }}</text>
							</div>
							<div>
								<text class="card-description"> 料号: {{ item.MATERIALSPECNAME }}</text>
								<text class="card-description"> 阶段: {{ item.PHASE }}</text>
								<text class="card-description"> SDK规格: {{ item.SPECNAME }}</text>
							</div>
							<div>
								<text class="card-description"> 品名: {{ item.DESC_CN }}</text>
							</div>
							<div>
								<text class="card-description"> 实际规格: {{ item.TRUEGG }}</text>
							</div>
							<div>
								<text class="card-description"> 仓库: {{ item.ERPLOCATION }}</text>
							</div>
							<div>
								<text class="card-description"> 货位: {{ item.LOCATIONNAME }}</text>
							</div>
							<div>
								<text class="card-description"> 数量: {{ item.MATERIALQUANTITY }} {{ item.UNIT }}</text>
							</div>

							<div class="button-group" style="margin: 5rpx; align: center;">
								<u-button type="primary" size="mini" @click="deleteItem(item, index)">删除</u-button>
							</div>
						</view>
						<!-- <view class="delete-btn" @click="deleteItem(item, index)"  >删除</view> -->
					</view>
				</view>

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

</template>
<script>
	import zxzUniDataSelect from "@/components/zxz-uni-data-select/zxz-uni-data-select.vue"
	import {
		getOpCode
	} from '@/common/api.js';
	import {
		cals
	} from '@/utils/cal'
	import navVar from "@/components/navBar/navBar.vue"
	export default {
		components: {
			zxzUniDataSelect,
			navVar
		},
		data() {
			return {
				sumList: [],
				column: [ //列
					{
						name: 'RECEIVEREQUESTNAME',
						label: '单号'
					},
					{
						name: 'MATERIALSPECNAME',
						label: '料号'
					},
					{
						name: 'SDK_ID',
						label: '规格'
					}, {
						name: 'AREANAME',
						label: '阶段'
					},
					{
						name: 'QTY',
						label: '计划数量'
					},
					{
						name: 'REQTY',
						label: '剩余数量'
					},
				],
				showModal: false,
				titleModal: "提示",
				contentModal: '是否确定返回?',
				navConfig: {
					navBarHeight: "500rpx",
					navPadding: false,
					isHome: false,
					navPadding: true,
					navFixed: true,
					bgImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))',
					isCustomFn: true,
					navTitle: {
						text: "成品入库",
						color: "rgb(96, 98, 102)",
						fontSize: "14px", // px upx rpx
						fontWeight: "normal", // blod
					},
					leftText: {
						text: "返回",
						color: "rgb(96, 98, 102)",
						fontSize: "14px", // px upx rpx
						fontWeight: "", // blod
					},
					leftIconPath: '../../../../static/img/back.png'
				},
				RECEIVEREQUESTNAME: "",
				MATERIALQUANTITY: 0,
				items_In: [],
				items_En: [],
				INITILATION: '', //起始点
				ENDING: '', //目的地
				AB: '', //AB轴
				DURABLENAMECode: '', //卷芯
				AreaName: '',
				Area: [],
				value: '',
				show: false,
				AGVshow: false,
				orgObject: {
					ERPFACTORY: '',
					DESCRIPTION: ''
				}, // 组织对象
				datamodel: '',
				LocationName: '', //库位信息
				LOCATIONNAME: '',
				ERPFACTORY: JSON.parse(uni.getStorageSync('orgObject')).ERPFACTORY, //组织
				ERPLOCATION: '', //库位
				tabH: 800, //表格的宽度
				MATERIALSPECNAME: '',
				MATERIALPACKINGNAME: '', //条码
				MATERIALPACKINGNAME2: '', //条码
				CHARGE: '', //批次
				DESC_CN: '', //品名
				SPECNAME: '', //规格
				SDK_ID: '', //规格ID
				RECEIVEACTNO: '', //入库单号
				UNIT: '', //单位
				PHASE: '', //阶段
				QTY: '', //数量
				JS: 0, //卷数
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				}, //返回按钮的样式
				colors: ['#007aff', '#4cd964', '#dd524d'],
				styleType: 'button',
				current: 0,
				BoxListInfo: [], //后端传回来的绑定表格的数据
				colorIndex: 0,
				activeColor: '#007aff',
				loading: false,
				scanData: [], //已扫描箱
				barCode: "", //条码
				focusBarCode: false, //焦点是否被选中
				focusShipRequest: true, //默认焦点在单号
				siteName: "",
				userId: "",
				items: [],
				items_Location: [],
				commitDate: '',
				items_LocationAll: [],
				timeDate: '',
				opCode: '',
				startX: 0, // 触摸开始时的X坐标  
				endX: 0, // 触摸结束时的X坐标  
				isMoving: false, // 是否正在滑动  
				showDeleteBtn: null, // 显示删除按钮的索引 
				isCollapsed: false, // 默认为展开状态
				searchBatch: '', //搜索的批次
				lockInput:true
			}
		},
		mounted() {
			this.tabH = this.$GetRemainingHeight(4, 0); //定义表格的高度
			let that = this
			uni.getStorage({
				key: "sitename",
				success(res) {
					that.siteName = res.data
				}
			})
			uni.getStorage({
				key: "userid",
				success(res) {
					that.userId = res.data
				}
			})

			this.orgObject = JSON.parse(uni.getStorageSync('orgObject'))
			this.getERPLocation();
			//this.getLocationName();
			// this.GetLiberaryBaeIn()
			// this.GetLiberaryBaeEn()	
			this.getTimeData();
		},
		methods: {
			//折叠
			toggle() {
				this.isCollapsed = !this.isCollapsed;
			},
			//隐藏展示批次
			setVisableCharge(iCharge) {
				if (this.searchBatch == '') {
					return 'card-display'
				} else {
					if (iCharge.includes(this.searchBatch)) {
						return 'card-dispaly'
					} else {
						return 'card-hidden'
					}
				}
			},
			getTimeData() {
				var year = new Date().getFullYear(); //年
				if (year < 1900) year = year + 1900;
				var month = new Date().getMonth() + 1; //月
				if (month < 10) month = '0' + month;
				var day = new Date().getDate(); //日
				if (day < 10) day = '0' + day;
				const calendar1 = year + '-' + month + '-' + day
				this.commitDate = calendar1
			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			},
			onLeftClick() {
				uni.showModal({
					title: this.titleModal, // 模态框标题
					content: this.contentModal, // 模态框内容
					showCancel: true, // 是否显示取消按钮，默认为true
					cancelText: '取消', // 取消按钮的文字
					confirmText: '确定', // 确定按钮的文字
					success(res) {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
							});
							console.log('用户点击了确定');
							// 执行确认后的逻辑
						} else if (res.cancel) {
							console.log('用户点击了取消');
							// 执行取消后的逻辑
						}
					}
				})
			},

			onTouchStart(index, event) {
				this.startX = event.touches[0].clientX;
				this.isMoving = false;
				this.showDeleteBtn = null;

			},

			onTouchMove(index, event) {
				this.endX = event.touches[0].clientX;
				if (this.startX - this.endX > 50) { // 判断滑动距离，可以根据需要调整
					console.log("222")
					this.isMoving = true;
					this.showDeleteBtn = index;
				} else if (this.endX - this.startX > 50) {
					this.isMoving = false;
					this.showDeleteBtn = null;

				}

			},

			onTouchEnd(row, index, event) {
				if (this.isMoving && this.showDeleteBtn === index) {
					// this.deleteItem(row, index)
					console.log("111")
					this.isMoving = false;
					this.showDeleteBtn = null;
				} else {
					this.isMoving = false;
					this.showDeleteBtn = null;
				}
			},

			getItemStyle(index) {
				return {
					transform: this.showDeleteBtn === index ? 'translateX(-60px)' : 'translateX(0)', // 根据需要调整位移距离  
					transition: this.isMoving ? 'none' : 'transform 0.3s', // 滑动时禁用过渡效果  
				};

			},
			deleteItem(row, index) {
				console.log("***********" + index)
				this.BoxListInfo.splice(index, 1)
				this.MATERIALQUANTITY = this.MATERIALQUANTITY - row.MATERIALQUANTITY
				this.JS = this.JS - 1
				if (this.BoxListInfo.length > 0) {
					for (let i = 0; i < this.sumList.length; i++) {
						if (this.BoxListInfo.every(el => el.RECEIVEREQUESTNAME != this.sumList[i].RECEIVEREQUESTNAME)) {
							this.sumList.splice(i, 1)
						}
					}
				} else {
					this.sumList = []
				}
				this.deletingIndex = null;
				this.$showMessage("删除成功")
			},

			// del(row, index){
			// 	this.BoxListInfo.splice(index,1)
			// 	this.MATERIALQUANTITY = this.MATERIALQUANTITY - row.MATERIALQUANTITY
			// 	this.JS = this.JS - 1

			// 	if(this.BoxListInfo.length > 0) {
			// 		for (let i = 0; i < this.sumList.length; i++) {
			// 			if(this.BoxListInfo.every(el => el.RECEIVEREQUESTNAME != this.sumList[i].RECEIVEREQUESTNAME)) {
			// 				this.sumList.splice(i,1)
			// 			}
			// 		}
			// 	}else {
			// 		this.sumList = []
			// 	}

			// 	this.$showMessage("删除成功")
			// },
			change(e) {
				this.ERPLOCATION = e.value;
				this.LOCATIONNAME = ""
				this.getLocationName();
			},
			changeLocationName(e) {
				this.LOCATIONNAME = e.value;
			},
			//获取焦点的公共方法
			getfocus(nextfocus) {
				this.initfocus()
				this[nextfocus]
				this.$nextTick(() => { //vue是数据全部修改后才进行的视图更新，哪nextTick函数就是为了拿到最新的数据，还不懂的可以去百度
					this[nextfocus] = true
				})
			},
			getERPLocation() {
				this.items = [];
				this.$MyRequest('/api/storage/getERPLocation', {
					ERPFACTORYNAME: this.ERPFACTORY
				}).then(res => {
					if (res.data.success) {
						for (let i = 0; i < res.data.resultObj.length; i++) {
							var _Arr = res.data.resultObj[i];
							this.items.push({
								text: _Arr.DESCRIPTION,
								value: _Arr.ERPLOCATIONNAME
							});
						}
					} else {
						this.$showMessage(res.data.message)
					}
				});
			},
			getLocationName() {
				this.items_Location = []
				this.items_LocationAll = []
				let ERPFACTORY = JSON.parse(uni.getStorageSync('orgObject')).ERPFACTORY;
				this.$MyRequest('/api/storage/getLocationNameForERPLocation', {
					ERPLocation: this.ERPLOCATION
				}).then(res => {
					if (res.data.success) {
						for (let i = 0; i < res.data.resultObj.length; i++) {
							var _Arr = res.data.resultObj[i];
							this.items_LocationAll.push({
								text: _Arr.DESCRIPTION,
								value: _Arr.STORAGENAME
							});
						}
						console.log(this.items_LocationAll)
						this.getitems_LocationAll('');
					} else {
						this.$showMessage(res.data.message)
					}
					this.focusBarCode = true
					this.focusShipRequest = false
				}).catch(err => {
					this.$showMessage(err)
				});

			},
			getitems_LocationAll(query) {
				console.log(query + "&&&&&&&&&&&&&&")
				var arr = this.items_LocationAll.filter(item => {
					return (item.text.includes(query)) || (item.value.includes(query))
				})
				this.items_Location = arr.slice(0, arr.length)
				/* if (arr.length > 50) {
					this.items_Location = arr.slice(0, 50)
				} else {
					this.items_Location = arr
				} */
				console.log(this.items_Location)
			},
			//扫描成品入库条码
			ScanFGBarCode() {
				this.opCode = '';
				if (this.lockInput) {
					this.lockInput = false;
					this.focusBarCode = false;
					if (this.BoxListInfo.some(box => box.MATERIALPACKINGNAME === this.MATERIALPACKINGNAME)) {
						this.$showMessage("改标签已扫描，请不要重复扫描！");
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
						this.$playFail()
						return;
					}
					// if (this.LOCATIONNAME == null || this.LOCATIONNAME == "") {
					// 	this.$showMessage("请选择货位！");
					// 	this.$nextTick(() => {
					// 		this.MATERIALPACKINGNAME = ""
					// 		this.focusBarCode = true
					// 		this.focusShipRequest = false
					// 	})
					// 	this.$playFail()
					// 	return;
					// }
					if (this.ERPFACTORY == null || this.ERPFACTORY == "") {
						this.$showMessage("请选择组织！");
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
						this.$playFail()
						return;
					}
					if (this.ERPLOCATION == null || this.ERPLOCATION == "") {
						this.$showMessage("请选择仓库！");
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
						this.$playFail()
						return;
					}
					var barCodeArr = this.MATERIALPACKINGNAME.split("|");
					// 470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
					if (barCodeArr.length < 7) {
						this.$showMessage("条码规则不符合需求!")
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
						this.$playFail()
						return;
					}
					let orderList = this.sumList.map(item => item.RECEIVEREQUESTNAME)
					this.$MyRequest('/FGStockIn/getBarCode', {
						MATERIALPACKINGNAME: this.MATERIALPACKINGNAME,
						ERPFACTORY: this.ERPFACTORY,
						ERPLOCATION: this.ERPLOCATION,
						LOCATIONNAME: this.LOCATIONNAME,
						MATERIALSPECNAME: barCodeArr[0],
						user: this.userId,
						// commitDate : this.commitDate,
					}).then(res => {
						if (res.data.success) {
							console.log(res.data.resultObj[0])
							this.BoxListInfo.unshift(res.data.resultObj[0]);
							this.JS = 0
							this.MATERIALQUANTITY = 0
							this.sumList = [];
							for (let i = 0; i < this.BoxListInfo.length; i++) {
								this.JS = parseFloat(this.JS) + 1
								this.MATERIALQUANTITY = (cals.add(this.MATERIALQUANTITY, this.BoxListInfo[i]
									.MATERIALQUANTITY)).toNumber()
								if (this.sumList.every(el => el.RECEIVEREQUESTNAME != this.BoxListInfo[i]
										.RECEIVEREQUESTNAME)) {
									this.sumList.push(this.BoxListInfo[i])
								}
							}

							try {
								Vue.prototype.$playSuccess()
							} catch (e) {}

						} else {
							this.$showMessage(res.data.message)
							this.MATERIALPACKINGNAME = ""
							this.$playFail()
						}
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
					}).catch(err => {
						this.$showMessage(err)
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
							this.lockInput = true;
						})
						this.$playFail()
					});

				}
			},


			/**
			 * 入库审核
			 */
			FGStockIn() {
				console.log(this.commitDate)
				if (this.BoxListInfo.length > 0) {
					console.log(this.commitDate)
					this.loading = true;
					// if(this.commitDate == ''){
					// 	this.commitDate = this.timeDate
					// }
					this.opCode = '';
					console.log(this.commitDate)
					this.BoxListInfo.map(item => delete item.key)
					getOpCode({
						opcode: this.opCode,
						user: this.userId
					}).then((res) => {
						console.log(res.resultObj)
						this.opCode = res.resultObj
						this.$MyRequest('/FGStockIn/FGStockIn', {
							boxList: this.BoxListInfo,
							user: this.userId,
							opcode: this.opCode,
							commitDate: this.commitDate
						}).then(res => {
							if (res.data.success || res.data.code == 200) {
								this.opCode = '';
								this.loading = false;
								if (this.value == 'true') {
									if (this.AGVshow == true) {
										this.SendTransportTask()
									} else {
										this.SendTransportTaskNOAGV()
									}
								}
								this.loading = false;
								this.resetValue();
								this.$showMessage(res.data.message)
							} else {
								this.loading = false;
								this.$showMessage(res.data.message)
							}
							this.focusBarCode = true
							this.focusShipRequest = false
						}).catch(err => {
							this.loading = false;
							this.$showMessage(err)
						});
					})
				} else {
					this.$showMessage("入库数量为空！")
				}
			},

			resetValue() {
				this.opCode = "";
				this.MATERIALPACKINGNAME = "";
				this.BoxListInfo = [];
				this.RECEIVEACTNO = "";
				this.MATERIALSPECNAME = "";
				this.PHASE = "";
				this.SPECNAME = "";
				this.DESC_CN = "";
				this.CHARGE = "";
				this.MATERIALQUANTITY = 0;
				this.JS = 0;
			}
		}
	}
</script>

<style lang="scss">
	switch {
		color: #FFCC33;
	}

	u-form-item {
		margin: 5rpx;
		padding: 5rpx;
	}

	/* 基础样式 */
	.picker {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		width: 100%;
		/* 根据需要调整宽度 */
	}

	.row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
		/* 行与行之间的间距 */
	}

	.col {
		flex: 1;
		/* 使得每列占据相等的空间 */
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	label {
		// font-weight: bold;
		/* 标签加粗 */
		margin-bottom: 5px;
		/* 标签和值之间的间距 */
	}

	.value {
		/* 值的样式，可以根据需要调整 */
	}

	.container {

		padding: 10px;

	}

	.list-item {

		margin-top: 16px;
		/* 卡片之间的间距 */
		// padding: 12px;
		/* 卡片内部的内边距 */
		background-color: #aaaa7f;
		/* 卡片背景色 */
		border-radius: 8px;
		/* 卡片边框圆角 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 卡片阴影效果 */
	}

	// .item-content {
	// 	flex: 1;
	// 	padding-left: 10px;

	// }
	.card-display {
		flex: 1;
		// padding-left: 10px;
		display: flex;
		// margin-bottom: 16px;
		/* 卡片之间的间距 */
		// padding: 12px;
		/* 卡片内部的内边距 */
		background-color: #aaaa7f;
		/* 卡片背景色 */
		// border-radius: 8px;
		/* 卡片边框圆角 */
		// box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 卡片阴影效果 */
	}

	.card-description {
		margin: 5rpx;
	}

	.card-hidden {
		flex: 1;
		// padding-left: 10px;
		display: none;
		// margin-bottom: 16px;
		// /* 卡片之间的间距 */
		// padding: 12px;
		// /* 卡片内部的内边距 */
		// background-color: #aaaa7f;
		// /* 卡片背景色 */
		// border-radius: 8px;
		// /* 卡片边框圆角 */
		// box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 卡片阴影效果 */
	}

	// .delete-btn {  
	//     position: absolute;  
	//     right: 120;  
	//     top: 0;  
	//     width: 120px;  
	//     height: 100%;  
	//     background-color: red;  
	//     color: #fff;  
	//     text-align: center;  
	//     line-height: 120px; /* 仅当按钮高度固定为120px时使用 */  
	// }

	.collapsed {
		display: none;
	}
</style>