<template>
	<view>
		<u-form ref="uForm">
			<view class="flex-white-plr26 ptb10 mt32 bdb_f5">
				<text class="mr26">盘点凭证</text>
				<u-input disabled placeholder="自动生成" v-model="GoodsCheckBillNo" />
				<text class="mr26">盘点日期</text> {{$u.timeFormat(GoodsCheckBillDate, 'yyyy-mm-dd')}}
			</view>
			<view @click="pickerSelectFun('仓库名称')" class="flex-white-plr26 ptb20 bdb_f5">
				<text class="mr26">仓库名称<text class="redXingh">*</text></text>
				<view :class="StoreName ? '' : 'cBlack'"> {{StoreName ? StoreName : '请选择'}}
					<u-icon class="ml26" name="arrow-right" size="40" color="#888888"></u-icon>
				</view>
			</view>
<!-- 			<view @click="pickerSelectFun('单据类型')" class="flex-white-plr26 ptb20 bdb_f5">
				<text class="mr26">单据类型<text class="redXingh">*</text></text>
				<view :class="BillTypeName ? '' : 'cBlack'"> {{BillTypeName ? BillTypeName : '请选择'}}
					<u-icon class="ml26" name="arrow-right" size="40" color="#888888"></u-icon>
				</view>
			</view> -->
			<view class="flex-white-plr26 ptb20 bdb_f5">
				<text class="mr26" >仓位编号<text class="redXingh">*</text></text>
				<input type="text" v-model="StoreStationNo" style="width:80px;" @confirm="GetStoreStationName" />
				<text class="title" style="width:120px;">仓位名称：{{StoreStationName}}</text>
			</view>
			<view class="flex-white-plr26-column ptb20 m2t32">
				<view style="margin-bottom: 8rpx;">
					<text>备注内容</text>
				</view>
				<u-input v-model="Remark" maxlength="-1" type="textarea" :border="true" :height="100" :auto-height="true" />
			</view>
			<u-form-item label-width="150" label="条码资料:">
				<input type="text" maxlength="-1" v-model="QRBarCode" style="width:200px;" @confirm="GoodsCheckBillDetailScan" />
				<u-icon
					v-if="usePhoneScanFallback"
					name="scan"
					size="44"
					color="#2979ff"
					style="margin-left: 8px;"
					@click="handlePhoneScan"
				/>
				<checkbox-group @change="BarCodeDelChange">
					<checkbox ref="checkBoxRef" :checked="BarCodeDelStatus">删除</checkbox>
				</checkbox-group>
			</u-form-item>
			<u-form-item>
				<text class="title">{{BillDataMessage}}</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">成品编号：{{FabricGoodsNo}}</text>
				<text class="title" style="width:200px;">成品重量：{{GoodsQty}}KG</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">成品色号：{{GoodsCodeNo}}</text>
				<text class="title" style="width:200px;">成品颜色：{{GoodsCodeName}}</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">成品缸号：{{CrockNo}}</text>
				<text class="title" style="width:200px;">缸号卷号：{{GoodsBillNo}}</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">本架盘前：{{BillSumOldRoll}}条</text>
				<text class="title" style="width:200px;">本架实盘：{{BillSumNewRoll}}条</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">本色盘前：{{GoodsCodeNoSumOldRoll}}条</text>
				<text class="title" style="width:200px;">本色实盘：{{GoodsCodeNoSumNewRoll}}条</text>
			</u-form-item>
			<u-form-item>
				<text class="title" style="width:200px;">本缸盘前：{{CrockNoSumOldRoll}}条</text>
				<text class="title" style="width:200px;">本缸实盘：{{CrockNoSumNewRoll}}条</text>
			</u-form-item>
		</u-form>
		<view class="u-demo-area">
			<u-toast ref="uToast"></u-toast>
			<wyb-table ref="table" :headers="headersMaster" :contents="GoodsDetailList"
				@onCellClick="GetDetailCrockNoListData" />
			<!--	<wyb-table ref="table" :headers="headersDetail" :contents="GoodsCrockNoDataList"  height="600rpx" /> !-->
		</view>

		<!--提交按钮-->
		<view class="submitView">
			<u-button type="primary" style="width:100px;" class="submitBtn" :ripple="true" ripple-bg-color="#909399" @click="submitBtnFun">
				{{pageType ? '保存' : '提交'}}
			</u-button>

			<!-- <u-button type="primary" style="width:100px;" class="commitBtn"
				:ripple="true" ripple-bg-color="#909399" @click="commitBtnFun">
				{{CommitType ? '消审' : '审核'}}
			</u-button> -->
		</view>
		<!--组件-->
		<!-- <u-action-sheet :list="StoreNameDataList" v-model="actionSheetShow" @click="actionSheetCallback"></u-action-sheet> -->
		<u-select v-model="selectShow" :list="selectList" @confirm="selectConfirmFun"></u-select>

	</view>
</template>

<script>
	let that = '';
	import util, {
		parFabricGoodsBarCode2D,
		parYarnGoodsBarCode2D,
		playSuccessAudio,
		playErrorAudio
	} from '../../common/util';
	import scanMixin from '@/common/scanMixin.js';
	import wybTable from '@/components/wyb-table/wyb-table.vue';
	export default {
		mixins: [scanMixin],
		data() {
			return {
				selectShow: false,
				selectList: [],
				selectType: '',
				pageType: '',
				CommitType: '',
				CommitProcName: '',
				GoodsCheckBillID: 0,
				GoodsCheckBillNo: '',
				GoodsCheckBillDate: '',
				GoodsCheckBillMasterNo: '',
				StoreNameID: 0,
				StoreName: '',
				StoreStationID: 0,
				StoreStationNo: '',
				StoreStationName: '',
				CustomerID: 0,
				CustomerName: '',
				PlanDepartmentID: 0,
				PlanDepartmentName: '',
				SaleUserID: 0,
				SaleUserName: '',
				SaleCustomerAddress: '',
				BillBusinessID: 0,
				BillTypeName: '',
				actionSheetShow: false,
				Remark: '',
				GoodsDetailList: [],
				StoreNameDataList: [],
				BillBusinessDataList: [],
				QRBarCode: '',
				FabricGoodsNo: '',
				FabricGoodsName: '',
				GoodsCodeNo: '',
				GoodsCodeName: '',
				CrockNo: '',
				GoodsBillNo: '',
				GoodsQty: 0,
				BillSumOldRoll: 0,
				BillSumNewRoll: 0,
				GoodsCodeNoSumOldRoll: 0,
				GoodsCodeNoSumNewRoll: 0,
				CrockNoSumOldRoll: 0,
				CrockNoSumNewRoll: 0,
				BarCodeDelStatus: false,
				BillDataMessage: '',
				headersMaster: [{
					label: "成品编号",
					key: "product_code"
				}, {
					label: "成品名称",
					key: "product_name"
				}, {
					label: "成品色号",
					key: "product_color_code"
				}, {
					label: "成品颜色",
					key: "product_color_name"
				}, {
					label: "成品缸号",
					key: "dyelot_number"
				}, {
					label: "盘前条数",
					key: "roll"
				}, {
					label: "实盘条数",
					key: "check_roll"
				}, {
					label: "盈亏条数",
					key: "different_roll"
				}],
				// 移除了 scanReceiver 和 isPageActive，因为它们现在由 scanMixin 提供
			}
		},
		watch: {
			cpList: function(val, old) {
				that.cpCalcFun();
			}
		},
		onLoad(e) {
			that = this;
			this.getStoreNameData();
		},
		
		onBackPress() {
/* 			uni.$off('bjdKehuBindFun', that.bjdKehuBindFun)
			uni.$off('chanpinBindFun', that.chanpinBindFun)
			uni.$off('bjdLxrBindFun', that.bjdLxrBindFun)
			uni.$off('shangjiBindFun', that.shangjiBindFun) */
		},
		
		onUnload() {
			this.isPageActive = false;
			this.unregisterScanBroadcast();
		},

		onHide() {
			this.isPageActive = false;
			this.unregisterScanBroadcast();
		},

		onShow() {
			this.isPageActive = true;
			this.registerScanBroadcast((scanResult) => {
				console.log("扫码结果:", scanResult);
				
				if(!this.StoreName){
					this.showError('请先选择仓库');
					return;
				}
				if(!this.StoreStationNo){
					console.log("请先扫描仓库编号！", scanResult);
					this.StoreStationNo = scanResult;
					this.$nextTick(() => {
						this.GetStoreStationName();
					});
					return;
				}
				if(!this.GoodsCheckBillID){
					this.showError('请先提交');
					return;
				}
				if(!this.QRBarCode){
					console.log("请先扫描资料！", scanResult);
					this.QRBarCode = scanResult;
					this.$nextTick(() => {
						this.GoodsCheckBillDetailScan();
					});
					return;
				}
			});
		},
		methods: {
			handlePhoneScan() {
				this.openPhoneScan();
			},

			// 添加通用错误提示方法
			showError(message) {
				this.playError();
				uni.showModal({
					title: '提示',
					content: message,
					showCancel: false
				});
			},

			// 添加成功提示方法
			showSuccess(message) {
				this.playSuccess();
				uni.showToast({
					title: message,
					icon: 'success'
				});
			},

			
			
			playSuccess() {
				util.playSuccessAudio();
			},
			playError() {
				util.playErrorAudio();
			},

			BarCodeDelChange: function() {
				this.BarCodeDelStatus = !this.BarCodeDelStatus;
			},


			// 展示相应数据选择框
			pickerSelectFun: function(str) {
				console.log("---->>>" + str);
				that.selectList = [];
				if (str == '仓库名称') {
					that.selectList = this.StoreNameDataList;
				} else if (str == '单据类型') {
					that.selectList = this.BillBusinessDataList;
				}
				that.selectShow = true;
				that.selectType = str;
			},
			// 选择框选中事件
			selectConfirmFun: function(e) {
				if (that.selectType == '仓库名称') {
					that.StoreNameID = e[0].value;
					that.StoreName = e[0].label;

				} else if (that.selectType == '单据类型') {
					that.BillBusinessID = e[0].value;
					that.BillTypeName = e[0].label;
				}

				console.log("--->>" + that.StoreNameID);
			},


			getStoreNameData() {
				util.request({
					url: '/warehouse/physicalWarehouse/getPhysicalWarehouseDropdownList',
					method: 'GET',
					data: {
						'warehouse_type_id': 103,
					},
					success: (res) => {
						//console.log("-->>--" + JSON.stringify(res.data));
						if (res.data.msg == 'success'){
							var aResultData = res.data.data.list;
							for (var i = 0; i < aResultData.length; i++) {
								//console.log("--->>>" + aResultData[i].name);
								this.StoreNameDataList.push({
									value: aResultData[i].id,
									label: aResultData[i].name
								})
							}
						}
						else{
							this.StoreNameDataList = []
						}
					},
					fail: (error) => {
						uni.showToast({
							icon: 'none',
							title: '连接服务器出错，请检查后台服务是否启动！' + res.data.msg
						});
						setTimeout(function() {
							uni.hideLoading();
						}, 5000);
					},
				})
			},

			GetStoreStationName: function() {
				console.log("<<<>>>>>" + this.StoreStationNo + '<<<<>>>>');
				util.request({
					url: '/warehouse/warehouseBin/getWarehouseBin',
					method: 'GET',
					data: {
						'qr_code': this.StoreStationNo,
					},
					success: (res) => {
						if (res.data.msg == 'success'){
							if(this.StoreNameID !== res.data.data.physical_warehouse_id){
								this.showError('该仓位不属于当前仓库')
								return
							}
							console.log("<<<>>>>>" + JSON.stringify(res.data.data))
							this.StoreStationID = res.data.data.id;
							this.StoreStationNo = res.data.data.code;
							this.StoreStationName = res.data.data.name;
						}
					},
					fail: (error) => {
						uni.showToast({
							icon: 'none',
							title: '连接服务器出错，请检查后台服务是否启动！' + res.data.msg
						});
						setTimeout(function() {
							uni.hideLoading();
						}, 5000);
					},
				})
			},

			GetDetailCrockNoListData() {
				console.log("00000");
			},

			getBillBusinessData() {
				uni.request({
					url: util.apiurl + 'rest/db/opensql',
					data: {
						token: getApp().globalData.Token,
						format: 'json',
						data: {
							db_name: getApp().globalData.AppDBName,
							sql_command_id: 'APP.GetBillBusinessList',
							params: [{
								name: 'TypeStatus',
								value: '3'
							}, {
								name: 'TypeNo',
								value: 'BusinessTypeStoreGoods'
							}]
						},
					},
					success: (res) => {
						if (res.data.status == 0 && res.data.count == 1) {
							var aResultData = res.data.data;
							for (var i = 0; i < aResultData.length; i++) {
								this.BillBusinessID = aResultData[i].BillBusinessID;
								this.BillTypeName = aResultData[i].BillTypeName;
								this.BillBusinessDataList.push({

									value: aResultData[i].BillBusinessID,
									label: aResultData[i].BillTypeName
								})
							}
						}
						else if (res.data.status == 0 && res.data.count > 0) {
							var aResultData = res.data.data;
							for (var i = 0; i < aResultData.length; i++) {
								this.BillBusinessDataList.push({
									value: aResultData[i].BillBusinessID,
									label: aResultData[i].BillTypeName
								})
							}
						} else if (res.data.status == 0 && res.data.count <= 0) {
							this.BillBusinessDataList = [];
						} else {
							this.BillBusinessDataList = [];
						}
					},
					fail: (error) => {
						uni.showToast({
							icon: 'none',
							title: '连接服务器出错，请检查后台服务是否启动！' + res.data.msg
						});
						setTimeout(function() {
							uni.hideLoading();
						}, 5000);
					},
				})
			},

			GoodsCheckBillDetailData: function() {
				console.log("--aaa->>" + this.GoodsCheckBillID);
				util.request({
					url: '/product/productCheckOrder/getProductCheckOrder',
					data: {
						'id': this.GoodsCheckBillID,
						method: 'GET',
					},
					success: (res) => {
						console.log("-->>--" + JSON.stringify(res.data));
						this.GoodsDetailList = [];
						this.GoodsCheckBillNo = res.data.data.order_no;
						/* this.BillSumOldRoll = res.data.data.item_data.roll;
						this.BillSumNewRoll = res.data.data.item_data.check_roll; */
						var aResultData = res.data.data.item_data;
						this.BillSumOldRoll = 0;
						this.BillSumNewRoll = 0;
						for (var i = 0; i < aResultData.length; i++) {
							aResultData[i].roll = aResultData[i].roll / 100;
							aResultData[i].check_roll = aResultData[i].check_roll / 100;
							aResultData[i].different_roll = aResultData[i].different_roll / 100;

							this.BillSumOldRoll = this.BillSumOldRoll + aResultData[i].roll;
							this.BillSumNewRoll = this.BillSumNewRoll + aResultData[i].check_roll;
						};

						this.GoodsDetailList = aResultData;
					},
				})
			},

			// 日期修改
			bindDateChange: function(e) {
				that.bjdDate = e.detail.value;
				that.bjdDateTime = new Date(e.detail.value + ' 00:00:00').getTime()
			},
			// 展示相应数据选择框


			scanFun: function() {
				uni.scanCode({
					success(res) {
						that.code = res.result;
					}
				})
			},
			// 选择所属客户
			selectCustomer: function() {
				uni.navigateTo({
					url: '../basedata/customer/customer?type=染整厂'
				})
			},
			// 绑定客户
			bjdKehuBindFun: function(e) {
				console.log("CustomerName===" + e.CustomerName);
				that.CustomerID = e.CustomerID;
				that.CustomerName = e.CustomerName;
				that.PlanDepartmentID = e.PlanDepartmentID;
				that.PlanDepartmentName = e.PlanDepartmentName;
				that.SaleUserID = e.SaleUserID;
				that.SaleUserName = e.SaleUserName;
				that.SaleCustomerAddress = e.CustomerAddress + ' ' + e.CustomerPhone + ' ' + e.CustomerLinkName;

				/*
				that.clientId = e.clientId;
				that.clientName = e.clientName;
				*/
			},

			// 提交按钮方法
			submitBtnFun: function() {
				if (this.StoreName == '') {
					this.showError('仓库名称不能为空，请先输入仓库名称！');
					return;
				}

				if (this.StoreStationName == '') {
					this.showError('仓位名称不能为空，请先输入仓位编号！');
					return;
				}

				if (this.GoodsCheckBillID > 0) {
					this.showError('当前单据已经提交，不能重复提交！');
					return;
				}
				util.request({
					url: '/product/productCheckOrder/addProductCheckOrder',
					method: 'POST',
					data: {
						"check_time": this.GoodsCheckBillDate,
						"remark": this.Remark,
						"warehouse_bin_id": this.StoreStationID,
						"warehouse_id": this.StoreNameID
					},
					success: (res) => {
						if (res.data.code == '0') {
							console.log("-->>--" + JSON.stringify(res.data.data));
							this.GoodsCheckBillID = res.data.data.id;
							console.log("---GoodsCheckBillID>>" + this.GoodsCheckBillID);
							if (this.GoodsCheckBillID > 0){
								this.GoodsCheckBillDetailData();
							}
						}else{
							this.showError(res.data.msg || '提交失败');
						}
					},
					fail: (error) => {
						this.showError('连接服务器出错，请检查后台服务是否启动！');
					},
				})
			},

			GoodsCheckBillDetailScan() {
				if (this.StoreNameID == 0 && this.GoodsCheckBillNo == '') {
					this.QRBarCode = '';
					this.showError('请先新增单据');
					return;
				}
				console.log("this.QRBarCode ---->>" + this.QRBarCode);

				var aQRBarCode = '';
				var aBarCode = '';
				console.log('QRBarCode',this.QRBarCode.startsWith('66^')>0)
				if (this.QRBarCode.startsWith('66^')>0 || this.QRBarCode.startsWith('99^')>0 || /[\u4E00-\u9FA5]/.test(this.QRBarCode)){
					aQRBarCode = this.QRBarCode
				}else {
					aBarCode = this.QRBarCode;
				}

				if (aQRBarCode == '' && aBarCode == ''){
					this.QRBarCode = '';
					this.aBarCode = ''
					this.showError('请扫描二维码或者条形码');
					return;
				}

				let aBarCodeDelStatus = 1
				if (this.BarCodeDelStatus) {
					aBarCodeDelStatus = 3;
				};

				util.request({
					url: '/product/productCheckOrder/updateProductCheckOrder',
					method: 'put',
					data: {
						'arrange_type': aBarCodeDelStatus,
						'id': parseInt(this.GoodsCheckBillID),
						'bar_code': aBarCode,
						'qr_code': aQRBarCode,
					},
					success: (res) => {
						console.log("-->>--" + JSON.stringify(res.data));
						if (res.data.code == '0'){
							let aResultData = res.data.data;
							this.FabricGoodsNo = aResultData.product_code;
							this.FabricGoodsName = aResultData.product_name;
							this.GoodsCodeNo = aResultData.product_color_code;
							this.GoodsCodeName = aResultData.product_color_name;
							this.CrockNo = aResultData.dyelot_number;
							this.GoodsBillNo = aResultData.volume_number;
							this.GoodsQty = aResultData.weight / 10000;
							this.BillSumOldRoll = aResultData.warehouse_bin_check_before_roll/100;
							this.BillSumNewRoll = aResultData.warehouse_bin_check_roll/100;
							this.GoodsCodeNoSumOldRoll = aResultData.color_check_before_roll/100;
							this.GoodsCodeNoSumNewRoll = aResultData.color_check_roll/100;
							this.CrockNoSumOldRoll = aResultData.dye_check_before_roll/100;
							this.CrockNoSumNewRoll = aResultData.dye_check_roll/100;

							this.GoodsCheckBillDetailData();
							this.showSuccess(res.data.msg);
							this.QRBarCode = '';

						}
						else {
							this.showError(res.data.msg);
							this.QRBarCode = '';

						}
					},
				})
			},


			// 审核按钮方法
			commitBtnFun: function() {
				if (this.BillMasterID <= 0) {
					this.showError('当前单据未提交，不能审核或消审！');
					return;
				}

				var aCommitRecallName = '审核';
				if (this.CommitType == ''){
					aCommitRecallName = '审核';
				} else {
					aCommitRecallName = '消审';
				}

				if (this.CommitProcName == ''){
					this.showError('当前'+ aCommitRecallName +'操作配置有误，不能审核！');
					return;
				}

				uni.request({
					url: util.apiurl + 'rest/db/storedproc',
					data: {
						token: getApp().globalData.Token,
						format: 'json',
						data: {
							db_name: getApp().globalData.AppDBName,
							proc_name: this.CommitProcName,
							method: 'open_proc',
							params: [{
								name: '@BillID',
								value: this.GoodsCheckBillID
							}, {
								name: '@BillNo',
								value: this.GoodsCheckBillNo
							}, {
								name: '@UserName',
								value: getApp().globalData.UserName
							}]
						},
					},
					success: (res) => {
						if (res.data.status == 0) {
							var aResultData = JSON.parse(res.data.data);
							if (aResultData.code == 0 && aResultData.msg ==
								'success') {
								this.showSuccess(aCommitRecallName + "成功！");

								if (aCommitRecallName == '审核'){
									this.CommitType = '已审核'
								} else {
									this.CommitType = ''
								}
							} else {
								this.showError(aCommitRecallName + '出错，' + res.data.msg);
								return;
							}
						} else {
							this.playError();
							this.BillDataMessage = aCommitRecallName + '出错，' + res.data.msg
							return;
						}
					},
					fail: (error) => {
						this.showError('连接服务器出错，请检查后台服务是否启动！');
					},
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #F8F8F8;
		padding-bottom: 260rpx;
	}

	.u-radio {
		width: 200rpx !important;
	}

	.submitView {
		width: 100%;
		padding: 16rpx 0 26rpx;
		background-color: #FFFFFF;
		position: fixed;
		bottom: 0;
		left: 0;
		border-top: 1rpx solid #f1f1f1;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
	}

	.submitBtn {
		width: 666rpx;
	}

	.productBox {
		background-color: #FFFFFF;
		margin-top: 32rpx;
		padding: 26rpx 0;
	}

	.tjcpName {
		width: 686rpx;
		height: 40rpx;
		font-size: 16px;
		font-weight: bold;
		border-left: 6rpx solid #007AFF;
		padding-left: 12rpx;
		margin-left: 26rpx;
		margin-top: 26rpx;
	}

	.cpInput {
		width: 150rpx !important;
		margin-right: 12rpx;
	}

	.cpInput>input {
		box-sizing: border-box;
		border: 1rpx solid #DDDDDD;
		width: 100%;
		height: 60rpx;
		border-radius: 10rpx;
		padding: 0 10rpx;
	}

	.cpInput1 {
		width: 200rpx !important;
		margin-right: 12rpx;
	}

	.cpInput1>input {
		box-sizing: border-box;
		border: 1rpx solid #DDDDDD;
		width: 100%;
		height: 60rpx;
		border-radius: 10rpx;
		padding: 0 10rpx;
	}

	.clearIcon {
		position: absolute;
		right: 6rpx;
		top: 6rpx;
	}

	.greenPrice {
		font-size: 16px;
		color: #19BE6B !important;
		font-weight: bold;
	}

	.disFlex {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.inputName {
		color: #ADADAD;
		font-size: 16px;
	}

	.addHKQS {
		display: flex;
		align-items: center;
		padding: 16rpx 26rpx;
		font-size: 15px;
		font-weight: bold;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
