<!-- 发料任务详情 -->
<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<view class="top_card">
			<comJobUnScanDetail :jobContent="datacontent" :scanCount="scanCount">
			</comJobUnScanDetail>
		</view>
		<view class="" style="margin-top: 20rpx; margin-left: 20rpx; margin-right: 20rpx;">
			<button type="primary" @click="showRecommend"> 推荐信息</button>
			<button style="margin-top: 20rpx; " type="primary" @click="queryItemCode">ERP料号查询</button>
		</view>
		<scroll-view scroll-y="true" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll"
			class="scroll-detail">
			<view class="" style="margin-bottom:120rpx">
				<view class="detail-list margin_top" v-for="(item, index) in details" :key="item.id">
					<uni-swipe-action>
						<uni-swipe-action-item :right-options="options" :auto-close="false"
							@click="swipeClick($event,item,index)" style='background-color: #ffffff;'>
							<view class="detail-content">
								<view class="choose_main">
									<view class="ljh_box">
										<view class="tit_ljh">{{ item.itemCode }}</view>
										<view class="ljh_left desc_ljh">
											<view class="font_xs text_lightblue">{{ item.itemName }}</view>
											<view class="font_xs text_lightblue">{{ item.itemDesc1 }}</view>
										</view>
									</view>
									<view class="list_form">
										<view class="uni-container">
											<uni-table style="overflow-x: hidden;" empty-text="">
												<uni-tr>
													<uni-th width="50">数量</text></uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270" align="center">
														<view
															style="display: flex;flex-direction: row;justify-content:center;align-items: center;">
															<com-number-box :ref="'comNumberBox_'+index"
																v-model="item.handledQty" :max="99999" :min="0"
																style='width: 100px;'
																@change="qtyChanged($event,item,index)">
															</com-number-box>
														</view>
													</uni-th>
												</uni-tr>
												<uni-tr>
													<uni-th width="70">来源库位</uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270">
														<view class=""
															style="display: flex; width: 100%; align-items: center;  justify-content: center;">
															<view class="text_black">
																{{ item.handledFromLocationCode }}
															</view>
															<view class="" style="margin-left: 20rpx;">
																<button size="mini" type="primary"
																	@click="showLocation(item)">扫描库位</button>
															</view>
														</view>


													</uni-th>
												</uni-tr>
											</uni-table>
										</view>
									</view>

								</view>
							</view>

						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>

		</scroll-view>
		<view class="uni-flex uni-row new_btn_bot">
			<button class="new_clear_btn btn_double" @click="clear()">清空</button>
			<button class="new_save_btn btn_double" @click="submit()">提交</button>
		</view>
		<com-balance ref='issueitems' @selectedItem='selectedBalanceItem'></com-balance>
		<win-scan-button @goScan='openScanPopup' title="单件码"></win-scan-button>
		<winScanButtonBottom @goScan='openItemScanPopup' title="ERP料号"></winScanButtonBottom>
		<!-- <winScanButtonBottom @goScan='queryItemCode' title="ERP查询"></winScanButtonBottom> -->
		<winScanByProductCode ref="scanPackPopup" title="单件码" @getScanResult='getScanResult'></winScanByProductCode>
		<winScanLocationCode ref="location" title="库位" @getLocation="getToLocation"></winScanLocationCode>
		<win-scan-by-code ref="scanPopupItem" title='ERP料号' @getScanCode='getScanCode'>
		</win-scan-by-code>
		<recommendList ref="recommendList" title="推荐信息"></recommendList>
		<com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
		<wz-select-popup ref="wzSelectPopup" @select="selectCheckbox" />
		<com-message ref="comMessage" @afterCloseCommitMessage='closeCommitMessage()'
			@afterCloseScanMessage='closeScanMessage' @afterClose="closeScanMessage"></com-message>
	</view>
</template>

<script>
	import {
		getUnProducePickDetail,
		takeUnProduceIssueJob,
		cancelTakeUnProduceIssueJob,
		finshUnProducePickJob,
		getitems,
		getItemCodeByLike
	} from '@/api/index.js';
	import {
		getJobStatuStyle,
		getJobStatuDesc,
		showConfirmMsg,
		goHome,
		compareDesc,
		compareStr,
		getCurrDateTime,
		getCurrDateTimeAndT,
		navigateBack,
		scanSuccessAudio,
		scanFailedAudio,
		guid,
		getRemoveOption
	} from '@/common/basic.js';
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanButtonTop from '@/mycomponents/wincom/winScanButtonTop.vue'
	import winScanButtonBottom from '@/mycomponents/wincom/winScanButtonBottom.vue'
	import winMulitScan from '@/mycomponents/wincom/winMulitScan.vue'
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import comJobScanDetail from '@/mycomponents/comjob/comJobScanDetail.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';
	import winScanByProductCode from '@/mycomponents/wincom/winScanByProductCode.vue'
	import winScanLocationCode from '@/mycomponents/wincom/winScanLocationCode.vue';
	import winScanByCode from '@/mycomponents/wincom/winScanByCode.vue'
	import recommendList from '@/mycomponents/popup/recommendList.vue';
	import comJobUnScanDetail from '@/mycomponents/comjob/comJobUnScanDetail.vue'
	
	
	export default {
		components: {
			comMessage,
			winScanButton,
			winScanButtonTop,
			winScanButtonBottom,
			winMulitScan,
			comBalance,
			comJobScanDetail,
			winScanByPack,
			comNumberBox,
			winScanByProductCode,
			winScanLocationCode,
			winScanByCode,
			recommendList,
			comJobUnScanDetail
		},
		data() {
			return {
				id: "",
				datacontent: {},
				details: {},
				toLocation: '',
				ispending: false,
				balancesItem: null,
				currentItem: null,
				allCount: 0,
				scanCount: 0,
				isPack: true,
				titleArray: ['箱标签'],
				userForm: {
					names: [],
					values: [],
					origin: []
				},
				options: [],
				facDetails: [],
			}
		},
		filters: {
			statusStyle: function(val) {
				return getJobStatuStyle(val);
			},
			statusColor: function(val) {
				return getJobStatuDesc(val);
			}
		},
		props: {
			itemCode: "",
		},
		onLoad(param) {
			this.id = param.id;
			this.options = getRemoveOption();
			if (param.jobStatus == 1) {
				this.receive((callback => {
					this.getDetail();
				}));
			} else {
				this.getDetail();
			}
		},
		onReady() {},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			} else if (e.index === 1) {
				window.location.reload();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//取消承接任务	
			// cancelTakeUnProduceIssueJob(this.id)
			// 	.then(res => {})
			// 	.catch(err => {
			// 		this.showMessage(err.message);
			// 	});
		},
		mounted() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: "#5A7CF3 !important"
			})
		},
		methods: {
			showLocation(item) {
				this.currentItem = item;
				this.$refs.location.openScanPopup()
			},
			getToLocation(locationInfo) {
				if (this.datacontent.fromErpLocationCode != locationInfo.erpLocationCode) {
					scanFailedAudio()
					this.showMessage("扫描库位[" + locationInfo.code + "]的ERP储位与推荐来源库位的ERP储位[" + this.datacontent
						.fromErpLocationCode + "]不一致")
					return;
				}
				scanSuccessAudio()
				this.currentItem.handledFromLocationCode = locationInfo.code;
				this.currentItem.handledFromLocationArea = locationInfo.areaCode
				this.currentItem.handledFromLocationGroup = locationInfo.locationGroupCode
				this.currentItem.handledFromLocationErpCode = locationInfo.erpLocationCode
				this.currentItem.handledFromWarehouseCode = locationInfo.warehouseCode

				this.currentItem.recommendFromLocationCode =  locationInfo.code;
				this.currentItem.recommendFromLocationArea =  locationInfo.areaCode
				this.currentItem.recommendFromLocationGroup = locationInfo.locationGroupCode
				this.currentItem.recommendFromLocationErpCode = locationInfo.erpLocationCode
				this.currentItem.recommendFromWarehouseCode = locationInfo.warehouseCode
				this.$forceUpdate()
			},
			swipeClick(e, item, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.details.splice(index, 1)
							}
						}
					});
				}
			},

			openScanPopup() {
				// if (this.allCount === this.scanCount) {
				// 	this.showMessage("零件已经全部扫描完成");
				// 	return;
				// }
				this.$refs.scanPackPopup.openScanPopup();
			},
			openItemScanPopup() {
				this.$refs.scanPopupItem.openScanPopup();
			},
			
			queryItemCode() {
				this.$refs.wzSelectPopup.open({
					mode: 'radio', //radio checkbox 单选、多选
					// dataList:[], //如果dataList传入了数组则直接使用传入的数组渲染，无需再配置proxyConfig
					selected: this.userForm.values, //已选中的数据
					proxyConfig: { //组件内部代理请求数据配置
						reqFun: this.reqGetList, //请求方法,在方法中请返回Promise.resolve([])
						localPaging: false //前端本地分页
					},
					search: {
						type: 'remote', //local本地数据搜索 | remote请求接口
					},
					fields: {
						label: 'name',
						value: 'code'
					}
				})

			},

			reqGetList(data) {

				let params = {
					pageSize: data.pageSize,
					pageIndex: data.pageIndex,
					itemCode: data.searchValue,
				};
				return getItemCodeByLike(data.searchValue, data.pageIndex, data.pageSize);
			},

			selectCheckbox(mode, result) {
				this.getScanResult(result, false)
			},

			showRecommend() {
				if(this.facDetails.length==0){
					this.showMessage("无推荐信息")
					return;
				}
				this.$refs.recommendList.openScanPopup(this.facDetails)
			},

			//加载零件信息
			getDetail() {
				let that = this;
				if (that.id == undefined) {
					return;
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let params = {
					id: that.id,
				};
				getUnProducePickDetail(params)
					.then(item => {
						uni.hideLoading();
						that.datacontent = item;
						that.facDetails = item.facDetails
						that.details = [];
					})
					.catch(err => {
						uni.hideLoading();
						this.showMessage('未查找到详细信息')
					});
			},

			getScanCode(code) {
				if (code == "") {
					this.showMessage('ERP料号不能为空')
					return;
				}
				getitems(code).then((res) => {
					uni.hideLoading();
					if (res) {
						var result = {
							itemCode: res.code,
							uom:res.basicUom
						}
						this.getScanResult(result, false)
					} else {
						scanFailedAudio()
						this.showMessage('未查找到ERP料号【' + code + '】');
					}
				}).catch((err) => {
					this.showMessage(err.message);
					uni.hideLoading();
				})

			},

			getScanResult(result, isMesCode = true) {
				if(result.itemCode==this.datacontent.itemCode){
					let scanItem = this.details.find(r => r.itemCode === result.itemCode)
					//已经存在
					if (scanItem) {
						if (isMesCode) {
							this.showMessage('单件码[' + result.scanCode + "]已经扫描")
						} else {
							this.showMessage('ERP料号[' + result.itemCode + "]已经扫描")
						}
					} else {
						scanSuccessAudio()
						var addItem = this.setItemInfo(result)
						this.details.unshift(addItem)
						this.scanCount = 0;
						this.details.forEach(res => {
							this.scanCount += res.handledQty
						})
						this.$forceUpdate()
					}
				}else {
					if (isMesCode) {
						this.showMessage('单件码【' + result.scanCode + '】所对应的ERP料号与任务中的ERP料号不一致,请重新扫描');
					} else {
						this.showMessage('没有找到ERP料号[' + result.itemCode + "]的信息,请重新扫描");
					}
				}
				

			},

			setItemInfo(result) {
				var item = {
					id: guid(),
					itemCode: this.datacontent.itemCode,
					itemName: this.datacontent.itemName,
					itemDesc1: this.datacontent.itemDesc1,
					itemDesc2: this.datacontent.itemDesc2,
					stdPackQty: this.datacontent.stdPackQty,
					masterID: this.datacontent.id,

					recommendContainerCode: "",
					recommendPackingCode: "",
					recommendSupplierBatch: "",
					recommendArriveDate: getCurrDateTimeAndT(),
					recommendProduceDate: getCurrDateTimeAndT(),
					recommendExpireDate: getCurrDateTimeAndT(),
					recommendLot: "",
					recommendQty: this.datacontent.qty,
					uom: result.uom,

					handledContainerCode: "",
					handledPackingCode: "",
					handledSupplierBatch: "",
					handledArriveDate: getCurrDateTimeAndT(),
					handledProduceDate: getCurrDateTimeAndT(),
					handledExpireDate: getCurrDateTimeAndT(),
					handledLot: "",
					handledQty: this.datacontent.qty,

					creatorId: guid(),
					creationTime: getCurrDateTimeAndT(),
					tenantId: guid(),
					lastModificationTime: getCurrDateTimeAndT(),
					lastModifierId: guid(),
					number: this.datacontent.number,
					remark: "",
					status: 2,
					reasonCode: "",
					caseCode: "",
					projCapacityCode: "",
					onceBusiCode: "",
					explain: "",
				}
				return item;
			},

			qtyChanged(value, item, index) {
				if (value<= 0) {
					this.showMessage('领料数量必须大于0')
					item.handledQty = this.datacontent.qty
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				}else if (value > this.datacontent.qty) {
					this.showMessage("实际领料数量不能大于申请数量")
					item.handledQty = this.datacontent.qty
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				}else {
					item.handledQty =value
				}
				
				this.scanCount = 0;
				this.details.forEach(res => {
					this.scanCount += res.handledQty
				})

			},

			// //接收
			receive(callback) {
				let params = {
					id: this.id
				};
				takeUnProduceIssueJob(params)
					.then(res => {
						callback(true);
					})
					.catch(err => {
						this.showMessage(err.message);
						callback(false);
					});
			},

			submit() {
				
				if (this.details.length == 0) {
					showConfirmMsg("扫描列表为0,是否提交?",res=>{
						if(res){
							this.finsh();
						}
					})
				}else {
					this.scanCount = 0;
					this.details.forEach(res => {
						this.scanCount += res.handledQty
					})
					var locationHint = ""
					this.details.forEach(res => {
						if (!res.handledFromLocationCode) {
							locationHint += "物料[" + res.itemCode + "]请扫描来源库位" 
						}
					})
					
					if(locationHint){
						this.showMessage(locationHint);
						return
					}
					
					if(this.scanCount<this.datacontent.qty){
						showConfirmMsg("提交的数量小于需求的数量,是否提交?",res=>{
							if(res){
								this.finsh();
							}
						})
					}else if(this.scanCount>this.datacontent.qty){
						this.showMessage('提交的数量大于需求的数量,不可以提交');
					}else {
						this.finsh();
					}
				}
			

			},


			finsh() {
				let that = this;
				uni.showLoading({
					title: "提交中...",
					mask: true
				});
				that.datacontent.completeUserId = localStorage.getItem('userId')
				that.datacontent.completeUserName = localStorage.getItem('userName_CN')
				that.datacontent.completeTime = getCurrDateTime();
				that.datacontent.worker = localStorage.userName_CN == "" ? localStorage.userName : localStorage
					.userName_CN;
				that.datacontent.details = that.details;
				let params = JSON.stringify(that.datacontent);
				console.log("提交", params);
				finshUnProducePickJob(that.id, params)
					.then(res => {
						uni.hideLoading();
						if (res != null) {
							that.showCommitSuccessMessage();
						}
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			//返回任务列表页
			backJobList(delay) {
				navigateBack(1)
				// setTimeout(() => {
				// 	uni.navigateTo({
				// 		url: './unProducePick'
				// 	})
				// }, 1000)
			},

			clear() {
				this.scanCount = 0;
				this.currentItem = null;
				this.getDetail();
			},
			showMessage(message) {
				this.$refs.scanPackPopup.losefocus();
				this.$refs.scanPopupItem.losefocus();
				this.$refs.comMessage.showMessage(message);
			},
			showScanMessage(message) {
				this.$refs.scanPackPopup.losefocus();
				this.$refs.scanPopupItem.losefocus();
				this.$refs.comMessage.showScanMessage(message);
			},

			closeScanMessage() {
				this.$refs.scanPackPopup.getfocus();
				this.$refs.scanPopupItem.getfocus();
			},

			showCommitSuccessMessage() {
				this.$refs.comMessage.showCommitSuccess();
			},

			closeCommitMessage() {
				this.backJobList(0); //点关闭直接返回列表
				uni.hideLoading();
			},

			closeScanPopup() {
				if (this.allCount == this.scanCount) {
					this.$refs.scanPackPopup.closeScanPopup();
					this.$refs.scanPopupItem.closeScanPopup();
				}
			},

		}
	}
</script>

<style scoped lang="scss">
</style>