<template>
	<view>
		<u-navbar back-text="返回" title="预备货出库" :background="background"></u-navbar>
		<u-form ref="testForm">
			<u-form-item :border-bottom="false">
				<p>单号:</p>
				<u-select v-model="dlistShow" mode="single-column" value-name="id" :list="dlist"
					@confirm="selShipRequestName" confirm-text="确认选择" class="single-out" />
				<u-input :focus="focusShipRequest" :border="true" v-model="ShipRequestName" placeholder="请输入单号"
					@confirm="handleQuery" />
				<u-button @click="selectShipRequestName" type="primary" size="mini">选择单号</u-button>
				<!-- <u-button @click="handleQuery" type="primary" size="mini">查询</u-button> -->
			</u-form-item>
		</u-form>
		<!-- fit 列的宽度是否自撑开 -->
		<view>
			<zb-table style="height: 400upx;" ref="zbTable" :showSelect="true" :singleSelect="true" :stripe="true"
				:show-header="true" :columns="column" :fit="false" :highlight="true" :border="true" :data="list_d"
				:cell-style="cellStyleFn" @toggleAllSelection="detailToggleAllSelection"
				@toggleRowSelection="detailSelectionChange" @rowClick="selectRow"></zb-table>
		</view>
		<view>
			<zb-table style="height: 400upx;" ref="zbTable" :show-header="true" :columns="column_bh" :stripe="true"
				:fit="false" :highlight="true" :border="true" :data="list" :cell-style="cellStyleFn"
				@toggleAllSelection="toggleAllSelection" @toggleRowSelection="stockSelectionChange"></zb-table>
		</view>
		<u-form>
			<u-form-item>
				<u-button @click="handleFn" type="primary" :disabled="button_but" style="width: 100%;">绑定</u-button>
			</u-form-item>
		</u-form>
		<view>
			<zb-table style="height: 400upx;" ref="zbTable" :show-header="true" :columns="column_det" :stripe="true"
				:fit="false" :highlight="true" :border="true" :data="list_detail" :cell-style="cellStyleFn"></zb-table>
		</view>
		<view class="tabbar_bottom_1">
			<u-input v-if="false" v-model="opCode" />
			<uni-datetime-picker style="align-items: center;" type="date" :clear-icon="false" v-model="commitDate"
				@maskClick="maskClick" />
			<u-button @click="ConfirmButton" type="primary" :disabled="button_state">提交</u-button>
		</view>
	</view>
</template>

<script>
	import {
		getOpCode
	} from '@/common/api.js';
	export default {
		data() {
			return {
				commitDate: '',
				opCode: '',
				loading: false,
				loading_d: false,
				button_state: false,
				button_but: false,
				active_row: {},
				list_d: [],
				list: [],
				list_detail: [],
				queryParams: {
					ShipRequestName: ''
				},
				detailChoose: [],
				stockChoose: [],
				column: [ //列
					{
						type: 'selection',
						width: 40
					},
					{
						label: '物料号',
						name: 'MATERIALSPECNAME'
					},
					{
						label: '规格',
						name: 'SPECNAME'
					},
					{
						label: '阶段',
						name: 'PHASE',
					},
					{
						label: '组织',
						name: 'ERPFACTORY'
					},
					{
						label: '单号',
						name: 'SHIPREQUESTNAME'
					},
					{
						label: '业助',
						name: 'LASTEVENTUSER'
					},
					{
						label: '请求数量',
						name: 'REQUESTQUANTITY'
					},
					{
						label: '绑定数量',
						name: 'ASSIGNEDQUANTITY'
					},
					{
						label: '剩余数量',
						name: 'MINUSQTY'
					}
				],
				column_bh: [ //列
					{
						type: 'selection',
						width: 40
					},
					{
						label: '物料号',
						name: 'MATERIALSPECNAME'
					},
					{
						label: '规格',
						name: 'SPECNAME'
					},
					{
						label: '阶段',
						name: 'PHASE',
					},
					{
						label: '组织',
						name: 'ERPFACTORY'
					},
					{
						label: '单号',
						name: 'SHIPREQUESTNAME'
					},
					{
						label: '业助',
						name: 'LASTEVENTUSER'
					},
					{
						label: '备货数量',
						name: 'ASSIGNEDQUANTITY'
					},
				],
				column_det: [ //列
					{
						label: '物料号',
						name: 'MATERIALSPECNAME'
					},
					{
						label: '规格',
						name: 'SPECNAME'
					},
					{
						label: '阶段',
						name: 'PHASE',
					},
					{
						label: '组织',
						name: 'ERPFACTORY'
					},
					{
						label: '仓库',
						name: 'ERPLOCATION'
					},
					{
						label: '货位',
						name: 'LOCATIONNAME'
					},
					{
						label: '条码',
						name: 'MATERIALPACKINGNAME'
					},
					{
						label: '条码数量',
						name: 'MATERIALQUANTITY'
					},
					{
						label: '单号',
						name: 'SHIPREQUESTNAME'
					},
					{
						label: '备货数量',
						name: 'MATERIALQUANTITY2'
					}
				],
				disableButton: false,
				pageNum: 1, // 页数
				pageSize: 8, // 条数
				total: 0, //每页总数
				totalAll: 0,
				bqts: 0,
				bqkcs: 0,
				moreStatus: 'more', // 上拉加载更多  more加载前 loading加载中	no-more没有更多数据
				flag: true, // 上拉加载开关 防止一次触底查询多次问题,防止数据查完后触底还调接口问题
				dlist: [{
					id: '',
					label: ''
				}], //选择内容
				dlistShow: false, //是否显示选择框				
				BoxInfoList: [],
				ShipRequestName: "",
				shipRequestType: "",
				barCode: "",
				userId: "",
				siteName: "",
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				},
				focusBarCode: false, //焦点是否被选中
				focusShipRequest: 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.getTimeData();
		},
		methods: {
			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);
			},
			handleQuery() {
				this.list_d = []
				// state.loading = true
				console.log(this.ShipRequestName)
				let param = {
					SHIPREQUESTNAME: this.ShipRequestName
				}
				this.$MyRequest('/SaleOut/getSaleOrderInvoice', param).then((res) => {
					console.log(res.data.resultObj)
					this.list_d = res.data.resultObj
				})
			},
			getBhQuery(data) {
				this.loading = true
				this.$MyRequest('/SaleOut/getSalePreOrderInvoice', data).then((res) => {
					this.list = res.data.resultObj
					this.loading = false
				})
			},
			getDetailQuery(data) {
				this.loading = true
				this.$MyRequest('/SaleOut/getChargeBindBySale', data).then((res) => {
					this.list_detail = res.data.resultObj
					this.loading = false
				})
			},
			handleFn() {
				// if (this.detailChoose.length > 1) {
				//   this.$showMessage("发货单详情列表只能勾选一行") 
				//   return
				// }
				console.log(this.detailChoose)
				console.log(this.stockChoose)
				let allQty = 0;
				this.stockChoose.map(value => {
					allQty += parseFloat(value.ASSIGNEDQUANTITY)
				})
				let mins = 0;
				this.detailChoose.map(value => {
					mins += parseFloat(value.MINUSQTY)
				})
				if (allQty != parseFloat(mins)) {
					this.$showMessage("数量不一致")
					return
				}
				// if (this.detailChoose.MINUSQTY == this.stockChoose.ASSIGNEDQUANTITY){
				// if(this.stockChoose.ASSIGNEDQUANTITY != 0 && this.detailChoose.MINUSQTY != 0){
				if (this.detailChoose.length && this.stockChoose.length) {
					this.button_but = true
					let salePreList = this.stockChoose.map(item => {
						return {
							salePreNo: item.SHIPREQUESTNAME,
							salePreQty: item.ASSIGNEDQUANTITY,
							salePreMaterialSpecName: item.MATERIALSPECNAME,
							salePreSdk_id: item.SDK_ID,
							salePrePhase: item.PHASE
						}
					})
					this.$MyRequest('/SaleOut/BindSalePreToSale', {
							user: uni.getStorageSync('userid'),
							//   ...state.detailChoose,  第一表格
							//   ...state.stockChoose 第二表格
							saleOrder: this.detailChoose[0].SHIPREQUESTNAME,
							// salePreNo:this.stockChoose[0].SHIPREQUESTNAME,
							// salePreQty:this.stockChoose[0].ASSIGNEDQUANTITY,
							saleQty: this.detailChoose[0].MINUSQTY,
							saleMaterialSpecName: this.detailChoose[0].MATERIALSPECNAME,
							// salePreMaterialSpecName:this.stockChoose[0].MATERIALSPECNAME,
							// salePreSdk_id:this.stockChoose[0].SDK_ID,
							saleSdk_id: this.detailChoose[0].SDK_ID,
							// salePrePhase:this.stockChoose[0].PHASE,
							salePhase: this.detailChoose[0].PHASE,
							salePreList: salePreList
						})
						.then((res) => {
							this.$showMessage(res.data.message)
							this.button_but = false
							this.handleQuery();
							this.getDetailQuery({
								...this.active_row,
								user: uni.getStorageSync('userid')
							})
						})
						.catch((error) => {
							this.$showMessage(error)
							this.button_but = false
						})
				} else {
					this.$showMessage("请各勾选一行")
				}
				// } else {
				//  this.$showMessage("选择的数量不能为零")
				//  return
				// }
				// } else {
				//  this.$showMessage("数量不一致") 
				//  return
				// }
			},
			selectRow(row) {
				this.active_row = row
				this.getBhQuery({
					...row,
					user: uni.getStorageSync('userid')
				})
				this.getDetailQuery({
					...row,
					user: uni.getStorageSync('userid')
				})
			},
			//确认提交按钮
			ConfirmButton() {
				console.log(this.commitDate)
				this.loading = true
			 this.button_state = true
				getOpCode({
					opcode: this.opCode,
					user: this.userId
				}).then((res) => {
					this.$MyRequest('/SaleOut/Commit4CToERP', {
							user: uni.getStorageSync('userid'),
							shipRequestName: this.ShipRequestName,
							boxList: this.list_detail,
							commitDate: this.commitDate,
							opcode: this.opCode
						})
						.then((res) => {
							this.loading = false
							this.loading_d = false
							this.button_state = false
							if (res.data.success) {
								this.opCode = "";
								this.list_d = [];
								this.list = [];
								this.list_detail = [];
								this.$showMessage(res.data.message)
								Vue.prototype.$playSuccess()
							} else {
								console.log(res)
								this.$showMessage(res.data.message)
								Vue.prototype.$playFail()
							}

							resetQuery()
						})
						.catch((error) => {
							this.$showMessage(error)
							this.button_state = false
						})
				})

			},
			detailToggleAllSelection(e, selection) {
				console.log('调用了1', selection)
				this.detailChoose = selection
			},
			toggleAllSelection(e, selection) {
				console.log('调用了', selection)
				this.stockChoose = selection
			},
			detailSelectionChange(e, selection) {
				console.log('调用了2', selection)
				this.detailChoose = selection
			},
			//选择备货
			stockSelectionChange(e, selection) {
				console.log('调用了', selection)
				this.stockChoose = selection
			},
			// 设置是否审核的颜色状态
			cellStyleFn({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				return {
					backgroundColor: row.ISCHECK == 'Y' ? 'yellowgreen' : 'white'
				}
			},
			// 上拉刷新
			pullUp(done) {
				if (this.flag) {
					// this.moreStatus = 'loading' //加载中时的状态 转圈
					this.serachMaterialList()
					done('')
					this.moreStatus = 'more'
				} else {
					this.moreStatus = 'no-more'
					done('ok')
				}
			},
			pullUpLoading() {
				// this.$refs.zbTable.pullUpCompleteLoading('ok')	
			},
			selShipRequestName(e) {
				this.ShipRequestName = e[0].value;
				this.handleQuery();
			},
			serachMaterialList() {
				this.$MyRequest('/invoice/getShipReservedBoxInfo', {
					ShipRequestName: this.ShipRequestName,
					pageSize: this.pageSize,
					pageNum: this.pageNum
				}).then(res => {
					// 开始
					this.flag = true
					if (res.data.success) {
						const result = res.data.resultObj.list || [];
						const totalAll = res.data.resultObj.total;
						this.BoxInfoList = this.BoxInfoList.concat(result);
						if (result.length == 0 && this.pageNum == 1) {
							this.flag = false
						} else {
							this.pageNum += 1
							this.total = result ? result.length : 0
							console.log(this.total, this.pageSize)
							if (this.total < this.pageSize) {
								this.flag = false
							}
						}
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						});
					}
					this.focusBarCode = true
					this.focusShipRequest = false
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			tableRowStyleName({
				row
			}) {
				if (row.ISCHECK == 'Y') {
					return 'background-color: yellowgreen;';
				}
			},
			selectShipRequestName() {
				this.dlist = [];
				this.$MyRequest('/invoice/getShipList', {
					ShipRequestName: this.ShipRequestName,
					shipRequestType: "4C"
				}).then(res => {
					if (res.data.success) {
						for (var i = 0; i < res.data.resultObj.length; i++) {
							// console.log(res.data.resultObj[i].SHIPREQUESTNAME)
							this.dlist.push({
								id: res.data.resultObj[i].SHIPREQUESTNAME,
								label: res.data.resultObj[i].SHIPREQUESTNAME
							});

						}
						this.dlistShow = true;
					} else {
						this.$showMessage(res.data.message)
					}

				}).catch(err => {
					this.$showMessage(err)
				})
			},
			confirmBarcode() {
				if (list_detail == null || list_detail.length < 1) {
					try {
						Vue.prototype.$playFail()
					} catch (e) {}
					this.$showMessage("无需要提交信息")
					return
				}
				let list = this.BoxInfoList;
				console.log(list)
				var errcount = 0;
				var LbarCode = this.barCode;
				this.focusBarCode = false;
				for (var i = 0; i < list.length; ++i) {
					console.log(this.BoxInfoList[i]['MATERIALPACKINGNAME'] + "***" + LbarCode)
					if (this.BoxInfoList[i]['MATERIALPACKINGNAME'] == LbarCode) {
						this.BoxInfoList[i]['ISCHECK'] = "Y"
						//this.barCode = ""
						//this.set(this.barCode,"")
						this.$nextTick(() => {
							this.barCode = ""
						})
					} else {
						this.barCode = ""
						this.$nextTick(() => {
							this.barCode = ""
						})
						console.log(this.BoxInfoList[i]['MATERIALPACKINGNAME'] + "****" + LbarCode)
						errcount++
					}
					this.bqts = 0
					this.bqkcs = 0
					for (let i = 0; i < this.BoxInfoList.length; i++) {
						if (this.BoxInfoList[i]['ISCHECK'] == "Y") {
							this.bqts++
							this.bqkcs = this.bqkcs + parseFloat(this.BoxInfoList[i]['MATERIALQUANTITY'])
						}
					}
				}
				if (errcount == list.length) {
					this.barCode = ""
					this.$nextTick(() => {
						this.barCode = ""
					})
					this.$showMessage("标签不在发货范围内")
					try {
						Vue.prototype.$playFail()
					} catch (e) {}
				}

				this.$nextTick(() => {
					this.focusBarCode = true
					this.focusShipRequest = false
				})


			},


		}
	}
</script>
<style>
	.tabbar_bottom_1 {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 99999;
		margin-bottom: 20rpx;

	}

	.single-out {
		pointerEvents: "none"
	}

	/* 	.btn-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		left: 0;
	} */
</style>
