<!-- 盘点任务详情 -->
<template>
	<page-meta root-font-size="18px" :page-style="'overflow:'+(isShowScanPopup?'hidden':'visible')"></page-meta>
	<view class="" style="display:flex;flex-direction: column;">
		<view class="top_card">
			<com-count-scan-detail :jobContent="datacontent" :allCount="allCount" :scanCount="scanCount"
				:newCount="newCount" :location="location">
			</com-count-scan-detail>
		</view>
		<scroll-view scroll-y="true" style="margin-bottom: 50rpx;">
			<view v-for="(item ,index) in showList" :key="index">
				<view class="detail-content common_card">
					<view class="choose_main">
						<view class="ljh_box">
							<view class="ljh_info">
								<view class="tit_ljh">{{index+1+'.'+item.itemCode }}</view>
								<view class="label_xm font_sm fr">{{ item.packingCode }}</view>
							</view>
							<view class="desc_card uni-flex space-between">
								<view class="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" style="padding-bottom: 0rpx;">
							<view>
								<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.uom}})</uni-th>
										<uni-th width="100" align="center">
											<text class="text_black">{{item.inventoryQty}}</text>
										</uni-th>
										<uni-th width="100" align="center">
											<com-number-box v-if="item.packingCode" v-model="item.countQty" :max="99999"
												:min="0" @change="qtyChanged($event,item)"
												style='margin-right: 10px;padding: 2px;'>
											</com-number-box>
											<view class="flex" style="align-items: center;justify-content: center;"
												v-if="item.packingCode==''">
												<text class="text_black">{{item.countQty}} </text>
												<view class="photo_btn_blue fr" @click="openEditCount(item)">
													<text class="fl font_xs">修改</text>
												</view>
											</view>

											<!-- <text class="text_black" v-if="item.packingCode"
															style="font-size: 1rem;">{{item.countQty}}</text> -->
											<!-- <com-number-box v-else v-model="item.countQty"
															:max="99999" :min="0"
															style='margin-right: 10px;padding: 2px;'>
														</com-number-box> -->

										</uni-th>
									</uni-tr>
								</uni-table>
							</view>
						</view>
						<view style="margin:0 20rpx 20rpx;">
							<view class="uni-flex uni-row bot_card">
								<view class="bot_card_item">
									<label class="icon_bg icon_bg_kw" style="text-align: center;">
										<text
											style=" display: block;   color: white;text-align: center;font-size: 28rpx;">库</text>
										<!-- <image class="icon_normal"
														src="@/static/icons_ui/icon_kw.svg"> -->
										</image>
									</label>
									<text>{{ item.locationCode }}</text>
								</view>
								<view class="bot_card_item">
									<label class="icon_bg icon_bg_pc">
										<text
											style=" display: block;   color: white;text-align: center;font-size: 28rpx;">批</text>
										<!-- <image class="icon_normal"
														src="@/static/icons_ui/icon_pc.svg">
													</image> -->
									</label>
									<text>{{item.lot}}</text>
								</view>
								<view class="bot_card_item" style="width: 25%;">
									<view class="uni-flex" v-if="item.isNew ">
										<!-- picker的index默认是0 -->
										<picker @change="bindPickerChange($event,item)" :value="item.status-1"
											:range="statusArray">
											<view class="uni-flex " style="padding:5px 0px;">
												<text class="state_point"
													:class="item.status | statusStyle">{{statusArray[item.status-1]}}</text>
												<image class="icon_normal" src="@/static/icons_ui/icon_down.svg">
												</image>
											</view>
										</picker>
									</view>
									<text v-else class="state_point" :class="item.status | statusStyle">
										{{ item.status | statusColor}}
									</text>
								</view>
							</view>
						</view>

					</view>

					<view class="uni-flex space-between" style="margin:0 20rpx 20rpx;" v-if="item.packingCode">
						<view class="">
							<text class="font_xs"
								style="padding: 5px 2px; text-overflow: ellipsis; overflow: hidden;">{{item.countDescription}}</text>
						</view>

						<view class="uni-flex uni-row">
							<view class="photo_btn_blue" @click="openEditCountDesc(item)">
								<text class="font_xs" style="width:65px;">盘点描述</text>
							</view>
							<view class="photo_btn_blue " style="margin-left: 10rpx;" @click="removeData(item,index)">
								<text class=" font_xs" style="width:65px;">移除</text>
							</view>
						</view>

					</view>
					<view class=""></view>
					<view class="" style="width: 100%; background-color: gray;height: 2rpx;">
					</view>

				</view>
			</view>

		</scroll-view>
		<uni-load-more :status="loadingType" v-if="showList.length>0" />

		<view class="new_btn_bot">
			<button class="new_save_btn" @click="submit()">提交</button>
		</view>
		<!-- <com-count-items ref='comcountItems' @selectedItem='selectedCountItem'> </com-count-items> -->
		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult' @close='closeScanPopup()'></win-scan-by-pack>
		<com-easy-input ref="descPopup" @confirm='closeEditCountDesc'></com-easy-input>
		<com-easy-input-count ref="countPopup" @confirm='closeEditCount'></com-easy-input-count>
		<win-inventory-status ref="statusPopup"></win-inventory-status>
		<!-- com-message必须放在最下层 -->
		<com-message ref="comMessage" @afterCloseCommitMessage='closeCommitMessage()'></com-message>
		<!-- <uni-load-more :status="loadingType" v-if="details.length>0"></uni-load-more> -->
	</view>
</template>

<script>
	import {
		getCountJobDetail,
		takeCountJob,
		cancelTakeCountJob,
		finishCountJob,
		getBalancesByFilterAsync,
		getitems,
		locationsAsync,
	} from '@/api/index.js';

	import {
		simulationReqGetList,
		getDataList
	} from "./mock.js"

	import {
		getJobStatuStyle,
		getJobStatuDesc,
		getCountStageDesc,
		getCheckTypeDesc,
		getCountMethodDesc,
		getInventoryStatusDesc,
		getInventoryTypeStyle,
		showConfirmMsg,
		goHome,
		getISODateTime,
		compare,
		getRemoveOption,
		getCurrDateTime,
		navigateBack
	} from '@/common/basic.js';

	import {
		getInventoryStatusArray
	} from '@/common/array.js'

	//import comCountItems from '@/mycomponents/coms/task/comCountItems.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue';
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue';
	import comJobScanDetail from '@/mycomponents/comjob/comJobScanDetail.vue'
	import comCountScanDetail from '@/mycomponents/coms/task/comCountScanDetail.vue';
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';
	import comEasyInput from '@/mycomponents/common/comEasyInput.vue';
	import comEasyInputCount from '@/mycomponents/common/comEasyInputCount.vue';
	import winInventoryStatus from '@/mycomponents/wincom/winInventoryStatus.vue';


	export default {
		components: {
			// comCountItems,
			comMessage,
			winScanButton,
			winScanByPack,
			comCountScanDetail,
			comNumberBox,
			comEasyInput,
			comEasyInputCount,
			winInventoryStatus
		},
		data() {
			return {
				type: '',
				id: '',
				datacontent: {},
				details: [],
				originalDetails: [], //所以的明细
				scanAllDetails: [],
				currentItem: {},
				editDescItem: {},
				editCountItem: {},
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				scanResult: {},
				allCount: 0,
				newCount: 0,
				scanCount: 0,
				options: [],
				location: null,
				topItem: '',
				isShowScanPopup: false,
				statusArray: [],
				allStatusArray: [],
				ipage: 1,
				iSize: 20,
				testList: [],
				isload: true,
				loadingType: "",
				currentPage: 0,
				pageSize: 20,
				jobStatus: "",
				index: 0,
				showList: []
			}
		},
		props: {},
		onLoad: function(param) {
			this.id = param.id;
			if (param.jobStatus == 1) {
				this.receive((callback => {
					this.getDetail();
				}));
			} else {
				this.getDetail();
			}
		},
		onPullDownRefresh() {
			this.initList();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			} else if (e.index === 1) {
				window.location.reload();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from == 'backbutton') {
				if (this.jobStatus == 2) {
					//取消承接任务	
					cancelTakeCountJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}
				return true;
			}
		},
		onReachBottom() {
			console.log("onReachBottom")
			//避免多次触发
			if (this.loadingType == 'nomore') {
				return;
			}
			this.index++;
			var list = this.getDataPage(this.index, this.pageSize)
			if (list.length > 0) {
				// this.showList=list
				this.showList = this.showList.concat(list)
			} else {
				//没有更多了
				this.loadingType = "nomore";
			}

		},


		filters: {
			statusStyle: function(val) {
				return getJobStatuStyle(val);
			},
			// statusColor: function(val) {
			// 	return getJobStatuDesc(val);
			// },
			statusStyle: function(val) {
				return getInventoryTypeStyle(val);
			},
			statusColor: function(val) {
				return getInventoryStatusDesc(val);
			},
			countStageDesc: function(val) {
				return getCountStageDesc(val);
			},
			checkTypeDesc: function(val) {
				return getCheckTypeDesc(val);
			},
			countMethodDesc: function(val) {
				return getCountMethodDesc(val);
			},
		},
		mounted() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: "#5A7CF3 !important"
			})
			this.options = getRemoveOption();
			this.allStatusArray = getInventoryStatusArray();
			this.allStatusArray.forEach(r => {
				this.statusArray.push(r.text)
			})
		},
		methods: {
			initList() {
				this.index = 1;
				this.showList = []
				this.loadingType = "";
				this.showList = this.getDataPage(this.index, this.pageSize)
			},
			getDetail() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let that = this;
				let params = {
					id: that.id,
				};
				getCountJobDetail(params)
					.then(async res => {
						that.datacontent = res;
						that.jobStatus = res.jobStatus;
						that.originalDetails = res.details;
						that.allCount = res.details.length

						that.scanAllDetails = res.depDetails;
						that.scanCount = res.depDetails.length
						
						that.scanAllDetails.forEach(res=>{
							res.IsDelete = false;
							res.modified=false;
						})

						this.initList()

						//查询库位信息
						let locationCode = that.datacontent.locationCode;
						let location = await locationsAsync(locationCode);
						if (location == '') {
							that.showMessage('未查找到库位信息【' + locationCode + '】');
						} else {
							that.location = location;
						}
					});
				uni.hideLoading();
			},

			getDataPage(pageNo, pageSize) {
				//计算总页数
				var totalPages = Math.ceil(this.scanCount / pageSize);
				//当前页起始索引
				const start = (pageNo - 1) * pageSize;
				const end = start + pageSize; //当前页结束索引
				var list =this.scanAllDetails.filter((r=>r.IsDelete==false))
				return list.slice(start, end)

			},

			getScanResult(result) {

				let itemCode = result.data.itemCode;
				let packingCode = result.data.code === null ? '' : result.data.code;
				var itemScan = this.scanAllDetails.filter(r =>
					r.packingCode == packingCode&&r.inventoryStage==this.datacontent.inventoryStage)
				if (itemScan.length > 0) {
					setTimeout(res => {
						showConfirmMsg("箱码【" + packingCode + "】已经扫描,是否覆盖已经扫描的信息", res => {
							if (res) {
								this.setQty(itemScan[0], itemScan[0].inventoryQty, false);
							}
						})
					}, 100)

					return;

				}

				let items = this.originalDetails.filter(r =>
					r.packingCode === packingCode&&r.inventoryStage==this.datacontent.inventoryStage)
				//不在任务列表中，查询库存赋值
				if (items.length == 0) {
					this.addNewDetail(result)
				} else if (items.length == 1) {
					var item = items[0];
					this.setQty(item, item.inventoryQty, true);
				} else {
					this.showMessage('盘点数量异常,箱码【' + packingCode + '】的出现多条数据');
				}
			},


			async addNewDetail(result) {
				if (this.location == null) {
					this.showMessage('未查找到库位信息,不可以添加为任务明细');
					return;
				}
				let balanceItem = await this.getBalanceAsync(result);
				let detail = this.creatDetail(result);
				if (balanceItem == null || balanceItem == undefined) {
					setTimeout(res => {
						showConfirmMsg('扫描的库存在任务中不存在,是否要添加为任务明细?', async confirm => {
							if (confirm) {
								this.setDetailNoBalance(detail, result)
								this.scanAllDetails.unshift(detail);
								this.initList()
								this.calcScanCount();
								this.$forceUpdate();
							} else {
								this.scanPopupGetfocus();
							}
						});
					}, 100)

				} else {
					if (balanceItem.locationCode != this.location.code) {
						this.showMessage("箱码【" + result.data.code + "】在库位【" + balanceItem.locationCode + "】不在库位【" +
							this.location.code + "】不可以添加为任务明细");
					} else {
						setTimeout(res => {
							showConfirmMsg('扫描的库存在任务中不存在,是否要添加为任务明细?', async confirm => {
								if (confirm) {
									this.setDetailByBalance(detail, balanceItem);
									this.scanAllDetails.unshift(detail);
									this.initList()
									this.calcScanCount();
									this.$forceUpdate();
								} else {
									this.scanPopupGetfocus();
								}
							});
						}, 100)
					}
				}
			},

			async getBalanceAsync(result) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let that = this;
				//按照零件号和箱码去查询库存
				let params = {
					pageSize: 100,
					pageIndex: 1,
					itemCode: result.data.itemCode,
					packingCode: result.data.packingCode
				};
				let balanceRes = await getBalancesByFilterAsync(params);
				uni.hideLoading();
				if (balanceRes.totalCount === 0) {
					// this.showMessage('箱码【' + result.data.packingCode + '】在未查询到库存信息,不可以进行盘点')
					return null;
				} else {
					let balanceItem = balanceRes.items[0];
					return balanceItem;
				}
			},

			creatDetail(result, balanceItem) {
				let detail = {
					isNew: true,
					IsDelete:false,
					modified:true,
					countTime: new Date(),
					masterID: this.id,
					countLabel: "",
					number: this.datacontent.number,
					inventoryStage:this.datacontent.inventoryStage,

					inventoryQty: 0,
					uom: result.data.uom,

					packingCode: result.data.packingCode,
					lot: result.data.lot,

					itemCode: result.data.itemCode,
					itemName: result.data.itemName,
					itemDesc1: result.data.itemDesc1,
					itemDesc2: result.data.itemDesc2,

					locationCode: this.location.code,
					locationGroup: this.location.locationGroupCode,
					locationArea: this.location.areaCode,
					locationErpCode: this.location.erpLocationCode,

					countOperator: localStorage.userId,
					warehouseCode: localStorage.warehouseCode,

					supplierBatch: result.data.supplierBatch,
					arriveDate: result.data.arriveDate,
					produceDate: result.data.produceDate,
					expireDate: result.data.expireDate,
					stdPackQty: result.data.stdPackQty,
					stdPackUom: result.data.stdPackUom,
				};
				return detail;
			},

			setDetailByBalance(detail, balanceItem) {
				detail.InventoryLocationCode = balanceItem.locationCode;
				detail.inventoryQty = balanceItem.qty;
				detail.countQty = balanceItem.qty;
				detail.status = balanceItem.status;
			
				return detail;
			},

			setDetailNoBalance(detail, result) {
				detail.InventoryLocationCode = "";
				detail.inventoryQty = 0;
				detail.countQty = result.data.qty;
				detail.status = 2;
				return detail;
			},

			setQty(item, qty, isAdd) {
				item.countQty = Number(qty);
				item.countTime = new Date();
				item.IsDelete  =false;
				item.modified =true;
				item.countOperator = localStorage.userId;
				if (isAdd) {
					this.scanAllDetails.unshift(item)
				}else {
					item.countDescription=""
				}
				this.initList();
				this.scanPopupGetfocus();
				this.calcScanCount();
				this.$forceUpdate();
			},
			removeData(item, index) {
				uni.showModal({
					title: '提示',
					content: '是否移除选择的行?',
					success: res => {
						if (res.confirm) {
							item.IsDelete = true;
							item.modified =true;
							// this.scanAllDetails.splice(index, 1);
							this.initList();
							this.scanPopupGetfocus();
							this.calcScanCount();
							this.$forceUpdate();
						}
					}
				});
			},

			receive(callback) {
				console.log('receive');
				let params = {
					id: this.id,
				};
				takeCountJob(params)
					.then(res => {
						callback();
					})
					.catch(err => {
						this.showMessage(err.message)
					});
			},

			submit() {
				
				if (this.scanAllDetails.length == 0) {
					this.showMessage("盘点数量为0,请先扫描")
					return;
				}
				var commitList=this.scanAllDetails.filter(r=>r.modified==true)
				if (commitList.length == 0) {
					this.showMessage("没有修改的数据,请先扫描")
					return;
				}
				
				
				var temp="";
				for (var i = 0; i < this.scanAllDetails.length; i++) {
					   if(this.scanAllDetails[i].countQty==0){
						   temp=this.scanAllDetails[i];
						   break;
					   }
				}
				
				if(temp!=""){
					this.showMessage("箱码:["+temp.packingCode+"]盘点数量为0,请输入盘点数量")
					return;
				}
				
				
				
				this.finishJob();
			},

			finishJob() {
				let that = this;
				uni.showLoading({
					title: "提交中...",
					mask: true
				});
				this.datacontent.depDetails = this.scanAllDetails.filter(r=>r.modified==true);
				this.datacontent.details =[];
				that.datacontent.completeUserId = localStorage.getItem('userId')
				that.datacontent.completeUserName = localStorage.getItem('userName_CN')
				that.datacontent.completeTime = getCurrDateTime()
				let params = JSON.stringify(this.datacontent);
				console.log("提交参数",params)
				finishCountJob(this.id, params)
					.then(res => {
						uni.hideLoading();
						if (!res) {
							that.showCommitSuccessMessage();
						}
					})
					.catch(err => {
						this.showMessage(err.message);
						uni.hideLoading();
					});
			},

			qtyChanged(value, item) {
				if (value > 0) {
					item.countTime = new Date();
					item.countOperator = localStorage.userId;
					this.calcScanCount();
					if(value==item.countQty){
						item.modified=false
					}else {
						item.modified=true
					}
				}else {
					this.showMessage("盘点数量必须大于0")
				}
			},


			calcScanCount() {
				this.scanCount = this.scanAllDetails.length;
			},

			bindPickerChange(e, item) {
				let index = e.detail.value;
				let text = this.statusArray[index];
				//根据选择的状态返回allStatusArray中的状态
				let status = this.allStatusArray.find(r => {
					return r.text == text
				})
				item.status = status.value;
				this.$forceUpdate();
			},

			openScanPopup() {
				setTimeout(r => {
					this.isShowScanPopup = true;
					this.$refs.scanPopup.openScanPopup();
				}, 0)
			},

			closeScanPopup() {
				this.isShowScanPopup = false;
			},

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

			openEditCountDesc(item) {
				this.editDescItem = item;
				this.$refs.descPopup.openPopup(item.countDescription);
			},

			closeEditCountDesc(content) {
				this.editDescItem.countDescription = content;
				this.$forceUpdate();
			},
			openEditCount(item) {
				this.editCountItem = item;
				this.$refs.countPopup.openPopup(item.countQty);
			},

			closeEditCount(content) {
				this.editCountItem.countQty = content;
				this.$forceUpdate();
			},


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

			closeCommitMessage() {
				navigateBack(1)
			},

			openStatusPopup() {
				this.$refs.statusPopup.openPopup('');
			},

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

			scrollToTop() {
				let that = this;
				// 解决view层不同步的问题
				that.scrollTop = that.old.scrollTop
				this.$nextTick(function() {
					that.scrollTop = 0
				});
			},

			upper(e) {
				console.log(e)
			},
			lower(e) {
				console.log(e)
			},
			scroll(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},

		},
	}
</script>

<style scoped lang="scss">
	.flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.popup-content {
		// .flex;
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: 50px;
		background-color: #fff;
	}

	.scroll-Y {
		height: 300rpx;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.scroll-view-item {
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.scroll-view-item_H {
		display: inline-block;
		width: 100%;
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.padding3 {
		padding: 3rpx;
		font-size: 30rpx;
	}

	.backGroundScan {
		background-color: #E4F8E1;
		padding: 20rpx;
	}

	.backGroundNormal {
		background-color: fff;
		padding: 20rpx;
	}

	.photo_btn_blue {
		background-color: #0089FF;
		border-radius: 5rpx;
		padding: 10rpx;
		color: #fff;
	}
</style>