<!-- 检验结果 -->
<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<!-- <view class="device-detail">
			<view class="uni-flex space-between">
				<view class="text-number">任务编号:{{itemDetail.number}}</view>
				<view class="state-style" :class="summaryDetail.inspectType | inspectTypeStyle">
					{{summaryDetail.inspectType | inspectTypeDesc}}
				</view>
			</view>
			<view>ASN:{{itemDetail.asnNumber}} </view>
			<view>到货单号:{{itemDetail.arriveNoticeNumber}} </view>
		</view> -->
		<view class="top_card inspect_card">
			<view class="ljh_box">
				<view class="tit_ljh">
					<text class="state-style" :class="summaryDetail.inspectType | inspectTypeStyle">
						{{summaryDetail.inspectType | inspectTypeDesc}}
					</text>
					<text>{{summaryDetail.itemCode}}</text>
				</view>
				<view class="cell_box uni-flex uni-row margin_top">
					<view class="cell_info" style="margin-bottom: 0;">
						<view class="text_lightblue">收货数量</view>
						<input class="display-input" type="text" :disabled="true"
							v-model="summaryDetail.receiveQty === undefined ? 0 :summaryDetail.receiveQty.qty" />
					</view>
					<view class="cell_info" style="margin-bottom: 0;">
						<view class="text_lightblue">检验数量</view>
						<input class="display-input" type="text" :disabled="true" v-model="summaryDetail.inspectQty" />
					</view>
					<view class="cell_info" style="margin-bottom: 0;">
						<view class="text_lightblue">批次</view>
						<input class="display-input" type="text" :disabled="true" v-model="summaryDetail.recommendLot" />
					</view>
					<view class="cell_info" style="margin-bottom: 0;">
						<view class="text_lightblue">单位</view>
						<input class="display-input" type="text" :disabled="true"
							v-model="summaryDetail.receiveQty === undefined ? '' :summaryDetail.receiveQty.uom" />
					</view>
				</view>
			</view>
		</view>
		<view class="list_locode">
			<uni-collapse style='font-size: 20px;border-radius: 16rpx;overflow: hidden; '>
				<uni-collapse-item title="库位列表" style='font-size: 18px;' :open='true'>
					<view style="background-color: white;">
						<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-detail">
							<view class="detail-list" v-for="(item, index) in locations" :key="item.id">
								<view class="detail-content inspect_list_locode">
									<view class="uni-flex">
										<view class="font_sm margin_right">{{index+1}}</view>
										<view class="font_sm margin_right text_darkblue">
											<image class="icon_normal" src="@/static/icons_ui/icon_xm_blue.svg"></image>
											{{item.packingCode}}
										</view>
										<view class="font_sm text_darkblue">
											<image class="icon_normal" src="@/static/icons_ui/icon_kw_blue.svg"></image>
											{{item.locationCode}}
										</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		<view class="padding" style="padding-top: 0;">
			<view class="pda-list inspect_form">
				<!-- <view class="pda-list-cell">
					<view class="pda-list-cell-db">
						<view class="uni-flex space-between">
							<input class="display-input" type="text" :disabled="true" v-model="" />
						</view>
					</view>
				</view> -->
				<view class="pda-list-cell">
					<view class="pda-list-cell-left">
						<view class="uni-label">不合格数量</view>
					</view>
					<view class="pda-list-cell-db">
						<uni-easyinput :inputBorder="true" type="number" placeholder="请输入数字"
							v-model="summaryDetail.failedQty" @blur="failedQtyConfirm" class="count-input" placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-easyinput>
					</view>
				</view>

				<view class="pda-list-cell">
					<view class="pda-list-cell-left">
						<view class="uni-label">不合格原因</view>
					</view>
					<view class="pda-list-cell-db">
						<uni-data-picker class='uni-data-picker' placeholder="请选择原因" popup-title="不合格原因"
							:localdata="failedReasonArray" v-model="summaryDetail.failedReason" placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-data-picker>
					</view>
				</view>

				<view class="pda-list-cell">
					<view class="pda-list-cell-left">
						<view class="uni-label">报废数量</view>
					</view>
					<view class="pda-list-cell-db">
						<uni-easyinput placeholder="请输入数字" type="number" v-model="summaryDetail.crackQty"
							@blur="crackQtyConfirm" class="count-input"  placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-easyinput>
					</view>
				</view>

				<view class="pda-list-cell" v-if="inspectType==='抽检'">
					<view class="pda-list-cell-left">
						<view class="uni-label">下一步动作</view>
					</view>
					<view class="pda-list-cell-db">
						<uni-data-picker class='uni-data-picker' placeholder="请选择下一步动作" popup-title="下一步动作"
							@change="nextStepChange" :localdata="nextStepArray" placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-data-picker>
					</view>
				</view>

				<view class="pda-list-cell" style="display: inherit;align-items: inherit;flex-direction: inherit;">
					<view class="pda-list-cell-left">
						<view class="uni-label">备注</view>
					</view>
					<view class="pda-list-cell-db" style="clear: both;">
						<uni-easyinput placeholder="请输入备注" autoHeight v-model="summaryDetail.remark"
							class="count-input" placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-easyinput>
					</view>
				</view>
				
				<view class="pda-list-cell">
					<view class="pda-list-cell-left">
						<view class="uni-label">最终不合格</view>
					</view>
					<view class="pda-list-cell-db">
						<uni-easyinput placeholder="此项自动计算" type="number" :disabled="true" v-model="summaryDetail.notPassedQty"
							class="count-input"  placeholderStyle="font-size:0.875rem;color:#999;">
						</uni-easyinput>
					</view>
				</view>
			</view>
		</view>
		<view class="new_btn_bot count_shadow">
			<button :disabled="submitting" type="primary" class="new_save_btn" @click="submit">提交</button>
		</view>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getInspectDetail,
		takeInspectJob,
		finshInspectJob,
		cancelTakeInspectJob,
		balances,
	} from '@/api/index.js';
	import {
		getInspectTypeStyle,
		getInspectTypeDesc,
		goHome
	} from '@/common/basic.js';
	import {
		getNextStepArray
	} from '@/common/array.js'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	export default {
		components: {
			comMessage
		},
		data() {
			return {
				id: '',
				itemDetail: {},
				summaryDetail: {},
				inspectType: '', //免检 全检 抽检 挑选
				failedReasonIndex: 0,
				failedReasonArray: [],
				nextStep: '',
				nextStepIndex: 3, //
				nextStepArray: [],
				nextStepEnable: false,
				submitting: false,
				received: false,
				locations: [],
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				value: ['0'],
			}
		},
		props: {
			itemCode: "",
		},
		filters: {
			inspectTypeStyle: function(val) {
				return getInspectTypeStyle(val);
			},
			inspectTypeDesc: function(val) {
				return getInspectTypeDesc(val);
			}
		},

		mounted: function() {
			this.nextStepArray = getNextStepArray()
		},

		onLoad: function(param) {
			if (param.id !== undefined) {
				this.id = param.id;
				//新建的任务自动接收
				if (param.jobStatus == 1) {
					this.receive((callback => {
						this.received = true;
						this.getDetail();
					}));
				} else {
					this.getDetail();
				}
			}
		},
		created() {

		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}else if(e.index === 1){
				window.location.reload();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (this.received) {
				//取消承接任务	
				cancelTakeInspectJob(this.id)
					.then(res => {})
					.catch(err => {
						this.showMessage(err.message);
					});
			}
		},
		methods: {
			getDetail() {
				let that = this;
				let params = {
					id: that.id,
				};
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getInspectDetail(params)
					.then(res => {
						that.itemDetail = res;
						if (res.summaryDetails != null && res.summaryDetails[0] != null) {
							that.summaryDetail = res.summaryDetails[0];
							that.inspectType = getInspectTypeDesc(that.summaryDetail.inspectType);

							//获取库位
							that.getLocations();
						}
						uni.hideLoading();
					});
			},

			//查询库位
			getLocations() {
				let that = this;
				// let packingCodes = [];
				// that.itemDetail.details.forEach(r => {
				// 	packingCodes.push(r.recommendPackingCode);
				// })

				//查询所在库位
				let locationParams = {
					pageSize: 1000,
					pageIndex: 1,
					itemCode: that.summaryDetail.itemCode, //按库位查询库存列
					inventoryStatus: 1
				};

				that.locations = [];
				balances(locationParams).then(res => {
						if (res.items != null && res.items.length > 0) {
							res.items.forEach(l => {
								let itemdetail = that.itemDetail.details.find(r =>
									r.recommendPackingCode === l.packingCode &&
									r.receiveQty.qty === l.qty.qty &&
									r.recommendLot === l.lot
								)
								if (itemdetail != null || itemdetail != undefined) {
									that.locations.push(l)
									itemdetail.handledLocationCode = l.locationCode;
								}
							})
							that.summaryDetail.handledLocationCode = res.items[0].locationCode;
						} else {
							this.showMessage('零件' + that.summaryDetail.itemCode + '未匹配到库位信息')
						}
						if (that.locations.length === 0) {
							this.showMessage('零件' + that.summaryDetail.itemCode + '未查找到库位信息')
						}
					}
					// res.items.forEach(l => {
					// 	let index = packingCodes.indexOf(l.packingCode);
					// 	if (index > -1) {
					// 		that.locations.push(l)
					// 	}
					// })
				);
			},

			initInspectInfo() {
				let that = this;
				if (that.inspectType == '挑选') {
					that.summaryDetail.notPassedQty = that.summaryDetail.receiveQty.qty;
				}
			},

			receive(callback) {
				console.log('receive');
				let params = {
					id: this.id,
				};
				uni.showLoading({
					title: "正在接收任务...."
				});
				takeInspectJob(params)
					.then(res => {
						uni.hideLoading();
						callback();
					})
					.catch(err => {
						this.showMessage(err.message);
					});
			},
			//不合格原因
			failedReasonChange: function(e) {
				// console.log('picker发送选择改变，携带值为：' + e.detail.value)
				// this.failedReasonIndex = e.detail.value
				// this.itemDetail.failedReason = this.failedReasonArray[this.failedReasonIndex].name;
			},
			//不合格数量确认事件
			failedQtyConfirm() {
				let that = this;
				if (that.inspectType === '全检' || that.inspectType === '挑选') //全检
				{
					that.summaryDetail.notPassedQty = that.summaryDetail.failedQty;
				} else if (that.inspectType === '抽检') {
					if (that.nextStep != '') {
						that.calcSampleFiledCount();
					}
				}
			},
			//报废数量
			crackQtyConfirm() {
				let that = this;
				if (that.inspectType === '抽检') {
					if (that.nextStep != '') {
						that.calcSampleFiledCount();
					}
				}
			},
			//切换下一步动作
			nextStepChange: function(e) {
				this.nextStep = e.detail.value[0].text;
				this.nextStepIndex = e.detail.value[0].value;
				//如果是抽检有下一步动作
				if (this.inspectType === '抽检') //全检
				{
					// console.log('picker发送选择改变，携带值为：' + e.detail.value)
					let isSucce = true;
					let qty = this.summaryDetail.receiveQty.qty //收货数量
					let crackQty = this.summaryDetail.crackQty; //报废数量
					let failedQty = this.summaryDetail.failedQty; //不合格数量

					//不合格数量
					if (failedQty < 0) {
						uni.showToast({
							title: '不合格数量不能小于0',
							icon: 'error'
						});
						isSucce = false;
					} else if (failedQty > 0) {
						if (failedQty > qty) {
							uni.showToast({
								title: '不合格数量' + failedQty + '不能大于收货数量' + qty,
								icon: 'error'
							});
							isSucce = false;
						}
					}

					//报废数量
					if (crackQty < 0) {
						uni.showToast({
							title: '报废数量不能小于0',
							icon: 'error'
						});
						isSucce = false;
					} else {
						if (crackQty > qty) {
							uni.showToast({
								title: '报废数量' + crackQty + '不能大于收货数量' + qty,
								icon: 'error'
							});
							isSucce = false;
						}
					}

					if (isSucce) {
						this.summaryDetail.nextAction = this.nextStepIndex;
						this.calcSampleFiledCount();
						// this.$emit("inspectResult", this.itemDetail);
						// this.$refs['popupResult'].close();
					}
				}
			},

			//计算最终不合格数量
			// 如果是抽检：用户填了不合格数量，如果下一步动作是挑选，最终不合格数量就是填写的不合格数量
			// 如果下一步动作是整批不合格，最终不合格数量等于 到货数量-报废数量
			// 如果下一步动作是部分合格，最终不合格数量等于 用户填写的不合格数量
			//计算抽检的不合格数量
			calcSampleFiledCount() {
				let that = this;
				//let nextStep = this.nextStepArray[this.nextStepIndex].name;
				// 如果下一步动作是挑选，最终不合格数量就是填写的不合格数量
				//如果下一步动作是整批不合格，最终不合格数量等于 到货数量-报废数量
				//如果下一步动作是部分合格，最终不合格数量等于 用户填写的不合格数量
				if (that.nextStep === "挑选" || that.nextStep === "部分合格") {
					that.summaryDetail.notPassedQty = that.summaryDetail.failedQty;
				} else if (that.nextStep === "整批不合格") {
					that.summaryDetail.notPassedQty = that.summaryDetail.receiveQty.qty - that.summaryDetail
						.crackQty;
				}
			},
			//确定
			submit() {
				let that = this;
				let qty = that.summaryDetail.receiveQty.qty
				let failedQty = Number(that.summaryDetail.failedQty);
				let crackQty = Number(that.summaryDetail.crackQty);
				let notPassedQty = Number(that.summaryDetail.notPassedQty);

				if (that.summaryDetail.notPassedQty === '') {
					this.showMessage('请输入不合格数量');
				} else if (failedQty + crackQty > qty) {
					this.showMessage('不合格数量+报废数量不应该大于收货数量');
				} else if (that.summaryDetail.notPassedQty > 0 && (that.summaryDetail.failedReason == null || that
						.summaryDetail.failedReason == '')) { // 不合格数量 为0 时，不需要填写 原因
					this.showMessage('请选择不合格原因');
				} else {
					if (that.summaryDetail.failedQty === '') {
						that.summaryDetail.crackQty = 0;
					}
					that.summaryDetail.failedQty = that.nextStep === "整批不合格" ? that.summaryDetail.notPassedQty : failedQty;
					that.summaryDetail.crackQty = crackQty;
					that.summaryDetail.notPassedQty = notPassedQty;
					that.onSubmit();
				}
			},

			onSubmit() {
				let that = this;
				//抽检任务，如果下一步动作是挑选，默认产生抽检任务
				if (that.inspectType === '抽检') {
					if (that.nextStep === "挑选") {
						that.finsh();
					} else {
						that.handleNextStep();
					}
				} else {
					that.handleNextStep();
				}
			},

			handleNextStep() {
				let that = this;
				//整批不合格，如果没有报废数量，就不显示详情
				if (that.nextStep === "整批不合格") {
					if (Number(that.summaryDetail.crackQty) > 0) {
						that.showInspectDetail();
					} else {
						that.finsh();
					}
				} else {
					if (Number(that.summaryDetail.failedQty) + Number(that.summaryDetail.crackQty) > 0) {
						that.showInspectDetail();
					} else {
						that.finsh();
					}
				}

			},

			//没有不合格数量。直接提交
			finsh() {
				let that = this;
				that.submitting = true;
				uni.showLoading({
					title: "提交中...",
					mask: true
				});

				//为summaryDetail赋值
				that.itemDetail.nextAction = that.nextStepIndex;
				//为summaryDetail赋值
				that.summaryDetail.handledContainerCode = that.summaryDetail.recommendContainerCode;
				that.summaryDetail.handledPackingCode = that.summaryDetail.recommendPackingCode;
				that.summaryDetail.handledBatch = that.summaryDetail.recommendBatch;
				that.summaryDetail.handledLot = that.summaryDetail.recommendLot;
				that.summaryDetail.handledLocationCode = that.summaryDetail.recommendLocationCode;
				that.summaryDetail.recommendQty = that.summaryDetail.receiveQty;
				that.summaryDetail.handledQty = that.summaryDetail.receiveQty;
				//如果是整批不合格,收货数量就是不合格数量和最终不合格数量
				that.summaryDetail.failedQty = that.nextStep === "整批不合格" ? that.summaryDetail.receiveQty.qty : Number(that
					.summaryDetail
					.failedQty); //不合格数量
				that.summaryDetail.crackQty = Number(that.summaryDetail.crackQty); //破坏数量
				that.summaryDetail.notPassedQty = that.nextStep === "整批不合格" ? that.summaryDetail.receiveQty.qty : Number(
					that.summaryDetail.notPassedQty); //最终不合格数量
				that.summaryDetail.goodQty = that.summaryDetail.receiveQty.qty;
				that.itemDetail.summaryDetails[0] = that.summaryDetail;

				let sumGoodQty = 0;
				that.itemDetail.details.forEach(r => {
					r.handledContainerCode = r.recommendContainerCode;
					r.handledPackingCode = r.recommendPackingCode;
					r.handledBatch = r.recommendBatch;
					r.handledLot = r.recommendLot;
					r.handledLocationCode = r.handledLocationCode === null ? r.recommendLocationCode : r
						.handledLocationCode
					// r.handledLocationCode = r.recommendLocationCode;
					r.recommendQty = r.receiveQty;
					r.handledQty = r.receiveQty;
					r.goodQty = r.receiveQty.qty;
					r.failedQty = that.nextStep === "整批不合格" ? r.receiveQty.qty : 0; //不合格数量
					r.crackQty = 0;
					r.notPassedQty = that.nextStep === "整批不合格" ? r.receiveQty.qty : 0; //最终不合格数量;
					r.nextAction = that.summaryDetail.nextAction;
					// sumGoodQty = sumGoodQty + r.receiveQty.qty;
					r.worker = localStorage.userName
				});

				// that.summaryDetail.goodQty = sumGoodQty;
				let params = JSON.stringify(this.itemDetail);
				console.log(params);
				finshInspectJob(this.id, params)
					.then(res => {
						setTimeout(() => {
							uni.navigateTo({
								url: './Inspect'
							})
						}, 1000)
						this.showMessage('提交成功')
						that.hideLoading();
					})
					.catch(err => {
						this.showMessage(err.message);
						that.hideLoading();
					});
			},
			hideLoading() {
				this.submitting = false;
				uni.hideLoading();
			},
			showInspectDetail() {
				let that = this;
				this.$router.push({
					path: './Inspect_detail',
					params: {
						id: that.id,
						item: that.itemDetail,
						// summarydetail: that.summaryDetail,
						// details: that.itemDetail.details,
						nextStep: that.nextStep,
						nextStepIndex: that.nextStepIndex,
						received: that.received
					}
				});
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop;
			},
		}
	}
</script>

<style scoped lang="scss">
	.display-input {
		padding: 5rpx 5rpx;
		line-height: 50rpx;
		background: #FFF;
		font-size: 16px;
	}


	// /deep/ .input-value {
	// 	font-size: 18px;
	// }

	/deep/ .uni-collapse-item__title-text {
		font-size: 16px;
	}
</style>
