<!-- 收货任务详情 -->
<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<view class="top_card">
			<com-job-scan-detail :jobContent="receiptJob" :allCount="allCount" :scanCount="scanCount">
			</com-job-scan-detail>
		</view>

		<scroll-view scroll-y="true" class="scroll-detail" style="margin-top: 20rpx;">
			<view class="detail-list" v-for="(item, index) in receiptJob.details" :key="item.id"
				style="margin-top: 4rpx;">
				<view class="detail-content common_card">
					<view class="choose_main">
						<view class="ljh_box">
							<view class="ljh_info">
								<view class="tit_ljh">{{ item.itemCode }}</view>
								<view class="label_xm font_sm fr">{{ item.recommendPackingCode }}</view>
							</view>
							<view class="desc_card uni-flex space-between">
								<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>
						<view class="list_form">
							<view class="uni-container">
								<uni-table style="overflow-x: hidden;">
									<uni-tr>
										<uni-th width="100"></uni-th>
										<uni-th width="100" align="center">整包</uni-th>
										<uni-th width="100" align="center">实际</uni-th>
									</uni-tr>
									<uni-tr>
										<uni-th width="100">数量({{item.recommendUom}})</uni-th>
										<uni-th width="100" align="center">
											<text class="text_black"
												style="font-size: 1rem;">{{item.recommendQty}}</text>
										</uni-th>
										<uni-th width="100" align="center">
											<text class="text_black" style="font-size: 1rem;">{{item.handledQty}}</text>
										</uni-th>
									</uni-tr>
								</uni-table>
							</view>
						</view>
						<view class="photo_btn fr" style="margin:0 20rpx 20rpx;"
							v-if="item.purchaseReceiptInspectStatus>1" @click="takePhoto(item)">
							<image class="icon_normal fl" src="@/static/icons_ui/icon_take_photo.svg"></image>
							<text class="fl">拍照</text>
						</view>
					</view>
					<view v-if="item.purchaseReceiptInspectStatus>1"
						:class="item.purchaseReceiptInspectStatus==2?'choose_marked':'choose_marked_faild'">
						<image v-if='item.purchaseReceiptInspectStatus==2' src="@/static/icons_ui/icon_passed.svg">
						</image>
						<image v-else-if="item.purchaseReceiptInspectStatus==3"
							src="@/static/icons_ui/icon_notpass.svg"></image>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="pop_btn ">
			<view class="new_btn_bot uni-flex uni-row space-between btn_unusual">
				<button class="new_clear_btn btn_triple" @click="clear()">清空</button>
				<button class="new_save_btn btn_triple" @click="unInspectToQualified()">待检合格</button>
				<button class="new_save_btn btn_triple" @click="inspectResult()">检验结果</button>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult'></win-scan-by-pack>
		<receipt-check ref='receiptCheck' :dataContent='selectedItem' :disabled='false'
			@getReceiptResult='getPhotoResult'>
		</receipt-check>
		<com-message ref="comMessage" @afterCloseCommitMessage='closeCommitMessage()' @afterCloseScanMessage='closeScanMessage'></com-message>
	</view>
</template>

<script>
	import {
		purchaseReceipts,
		takeReceiptJob,
		cancelTakeReceiptJob,
		finishReceiptJob,
		getFileByCode,
		unInspectToQualified,
		saveReceiptResult,
		resetReceiptResult
	} from '@/api/index.js';
	import {
		getJobStatuStyle,
		getJobStatuDesc,
		showConfirmMsg,
		compareDesc,
		goHome
	} from '@/common/basic.js';

	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import receiptCheck from '@/pages/task/receipt_check.vue'
	import comJobScanDetail from '@/mycomponents/comjob/comJobScanDetail.vue'

	export default {
		name: 'receipt_detail',
		components: {
			comMessage,
			winScanButton,
			winScanByPack,
			receiptCheck,
			comJobScanDetail
		},
		data() {
			return {
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				currentItem: {},
				id: '',
				receiptJob: {},
				ispending: false,
				inputQty: "",
				listfocus: false,
				finshed: false,
				received: false,
				allCount: 0,
				scanCount: 0,
				isCheckAll: false,
				selectedItem: {},
				loadingType: ""
			};
		},
		onLoad(option) {
			if (option.id != undefined) {
				this.id = option.id;
				//新建的任务自动接收
				if (option.jobStatus == 1) {
					this.receive((callback => {
						this.received = true;
						this.getDetail();
					}));
				} else {
					this.getDetail();
				}
			}
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (this.received) {
				//取消承接任务	
				cancelTakeReceiptJob(this.id)
					.then(res => {})
					.catch(err => {
						this.showMessage(err.message);
					});
			}
		},

		onPullDownRefresh() {
			this.getDetail();
			uni.stopPullDownRefresh();
		},

		filters: {
			statusStyle: function(val) {
				return getJobStatuStyle(val);
			},
			statusColor: function(val) {
				return getJobStatuDesc(val);
			},
		},
		mounted() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: "#5A7CF3 !important"
			})
		},
		methods: {
			//接收
			receive(callback) {
				if (this.id != null) {
					takeReceiptJob(this.id)
						.then(res => {
							callback();
						})
						.catch(err => {
							this.showMessage(err.message);
						});
				}
			},

			getDetail() {
				let that = this;
				that.getJoDetail(callBack => {
					that.ispending = that.receiptJob.jobStatus === 2;
					if (that.receiptJob.details != null) {
						that.allCount = that.receiptJob.details.length;
						that.calcScanCount();
						this.$nextTick();
					}
				});
			},

			calcScanCount() {
				let items = this.receiptJob.details.filter(r => {
					return r.purchaseReceiptInspectStatus > 1
				})
				this.scanCount = items != null ? items.length : 0;
				this.closeScanPopup();
			},

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

			getJoDetail(callBack) {
				let that = this;
				purchaseReceipts(that.id)
					.then(res => {
						res.details.sort(compareDesc('purchaseReceiptInspectStatus')); //按扫描信息排序
						that.receiptJob = res;
						callBack();
					})
					.catch(err => {
						this.showMessage(err.message);
					});
			},

			afterPurchase() {
				let that = this;
				//查询任务明细
				that.getJoDetail(() => {
					this.calcScanCount();
				})
			},

			//处理扫描解析的返回值
			getScanResult(result) {
				if (result.data.code == '')
					return;
				let code = result.data.code;
				let datas = this.receiptJob.details.filter(function(r) {
					if (
						r.recommendPackingCode === code) {
						return r;
					}
				});

				if (datas.length === 0) {
					this.showScanMessage('在收货任务详情中,未找到箱码【' + code + '】');
				} else {
					if (datas.length === 1) {
						let data = datas[0];
						if (data.purchaseReceiptInspectStatus > 1) {
							this.showScanMessage('箱码【' + data.recommendPackingCode + '】已经扫描,请扫描下一箱零件');
						} else {
							this.toQualified(data);
						}
					} else {
						datas.forEach(r => {
							this.toQualified(r);
						});
					}
				}
			},

			//转合格
			toQualified(detail) {
				uni.showLoading({
					title: '扫描中...',
					mask: true
				})
				let item = {
					id: this.id,
					detailId: detail.id,
					failedReason: '',
					massDefect: '',
					purchaseReceiptInspectStatus: 2,
					fileList: []
				};
				let param = JSON.stringify(item);
				//保存目检
				saveReceiptResult(this.id, param).then(res => {
					if (res != null) {
						this.afterPurchase();
					}
					this.scanPopupGetFocus();
					uni.hideLoading();
				}).catch(err => {
					this.showMessage(err.message)
					uni.hideLoading();
				})
			},

			takePhoto(item) {
				let that = this;
				that.selectedItem = item;
				that.$refs.receiptCheck.openReceiptCheckPopup(item.inspectPhotoJson);
			},

			getPhotoResult(files) {
				this.afterPurchase();
			},

			getFileBlob(file, callBack) {
				// let fileParam = [];
				let filePath = file.path;
				let fileName = file.name;
				let rd = new FileReader(); // 创建文件读取对象
				this.objectURLToBlob((filePath), (blob) => {
					const file = new window.File([blob], fileName, {
						type: blob.type
					});

					rd.readAsDataURL(file)
					rd.onloadend = function() {
						var arrayBuffer = rd.result
						let file = {
							fileName: fileName,
							bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1, arrayBuffer
								.length)
						}
						// fileParam.push(file);
						callBack(file);
					}
				})

			},

			// 生产检验结果
			inspectResult() {
				let that = this;
				let uncheckitems = that.receiptJob.details.filter(r => {
					return (r.purchaseReceiptInspectStatus <= 1)
				});
				if (uncheckitems.length > 0) {
					let msg = '还有未扫描的零件,是否要生成检验结果?';
					showConfirmMsg(msg, confirm => {
						if (confirm) {
							that.gotoInspectResult();
						}
					})
				} else {
					that.gotoInspectResult();
				}
			},

			gotoInspectResult() {
				let param = JSON.stringify(this.receiptJob);
				uni.navigateTo({
					url: './receipt_result?id=' + this.id 
				});
			},

			//待检转合格
			unInspectToQualified() {
				let items = this.receiptJob.details.filter(r => {
					return (r.purchaseReceiptInspectStatus <= 1)
				})

				if (items.length == 0) {
					this.showMessage('没有需要待检转合格的零件')
					return;
				}

				uni.showLoading({
					title: '处理中...',
					mask: true
				})
				unInspectToQualified(this.id).then(r => {
					if (r != null) {
						items.forEach(r => {
							r.purchaseReceiptInspectStatus = 2; //待检转为合格
							r.handledQty = r.recommendQty;
						})
						uni.hideLoading();
					}
				}).catch(err => {
					this.showMessage(err.message);
					uni.hideLoading();
				});
			},

			clear() {
				showConfirmMsg('是否要清空已扫描及已目检的信息?', confirm => {
					if (confirm) {
						let that = this;
						let details = [];
						this.receiptJob.details.forEach(r => {
							details.push(r.id);
						})
						let param = JSON.stringify(details);
						resetReceiptResult(that.id, param).then(res => {
							if (res != null) {
								that.getJoDetail(() => {
									that.scanCount = 0;
								});
							}
						}).catch(err => {
							that.showMessage(err.message)
							uni.hideLoading();
						});
					}
				});
			},

			openScanPopup() {
				this.$refs.scanPopup.openScanPopup();
			},

			scanPopupGetFocus() {
				this.$refs.scanPopup.getfocus();
			},

			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},

			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},

			showAutoCloseMessge(message) {
				this.$refs.comMessage.showAutoCloseMessge(message);
			},

			closeScanMessage() {
				this.$refs.scanPopup.getfocus();
			},
			upper: function(e) {
				// console.log(e)
			},

			lower: function(e) {
				// console.log(e)
			},

			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.receiptJob.scrollTop;
			},

			readImageBuffer(files) {
				let fileParam = [];
				let rd = new FileReader(); // 创建文件读取对象
				for (var i = 0; i < files.length; i++) {
					let filePath = files[i].path;
					let fileName = files[i].name;
					this.objectURLToBlob((filePath), (blob) => {
						const file = new window.File([blob], fileName, {
							type: blob.type
						});

						rd.readAsDataURL(file)
						rd.onloadend = function() {
							var arrayBuffer = rd.result
							let params = {
								fileName: fileName,
								bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1, arrayBuffer
									.length)
							}
							fileParam.push(params);
						}
					})
				}
			},

			/**
			 * BlobUrl转blob数据  
			 * @param {Object} url blob URL
			 * @param {Object} callback 回调函数
			 */
			objectURLToBlob(url, callback) {
				const http = new XMLHttpRequest();
				http.open("GET", url, true);
				http.responseType = "blob";
				http.onload = function(e) {
					if (this.status == 200 || this.status === 0) {
						callback(this.response);
					}
				};
				http.send();
			},
		}
	}
</script>

<style scoped lang="scss">
	@import '../../common/pdabasic.css';
</style>
