<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header-view">
				<view class="header_job_top">
					<job-top :dataContent="jobContent"></job-top>
					<view class="" style="margin-left: 10rpx; margin-top: 10rpx;margin-bottom: 10rpx;">
						<text style=" font-size: 32rpx; color: #6750F1">库位代码 </text>
						<text style="font-size: 35rpx; font-weight: bold;">{{locationCode}}</text>
					</view>

					<view class="" style="margin-left: 10rpx; margin-top: 10rpx;margin-bottom: 10rpx;">
						<text style=" font-size: 32rpx; color: #6750F1">管理精度 </text>
						<text style="font-size: 35rpx; font-weight: bold;">{{getManageMode(manageMode)}}</text>
					</view>
				</view>
			</view>

		</view>
		<view class="page-main" style="margin-bottom: 100rpx;background-color: #F3F4F5">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<view class="" style="background-color: #F3F4F5" v-for="(item, index) in dataList" :key="item.id">
					<uni-swipe-action ref="swipeAction">
						<uni-swipe-action-item>
							<view class="uni-flex uni-row "
								style="align-items: center; margin: 10rpx; border-radius: 10rpx   ;">
								<comCountDetailcards :ref="'countDetail_'+index" :dataContent="item" :index="index"
									@editItem="editItem" :settingParam="jobContent" @remove="updateData"
									@summCount="summCount" @currentCount="currentCount" @updateData="updateData">
								</comCountDetailcards>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</scroll-view>

		</view>

		<view class="page-footer">
			<view class="uni-flex u-col-center space-between padding_10"
				style="background-color:ghostwhite; width: 100%; ">
				<view class="">
				</view>
				<view class=" uni-flex uni-row">
					<button class="btn_single_commit" hover-class="btn_commit_after" @click="submitJob">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<win-scan-pack-and-location :allowModifyLocation="false" ref="scanPopup" :noShowBalanceMessage="true"
			:pdaCountBalanceQuery="true" :isShowHistory="false" @getCountScanResult='getCountScanResult'>
		</win-scan-pack-and-location>
		<detail-info-popup ref="detailInfoPopup"></detail-info-popup>
		<count-qty-edit ref="countQtyEdit" @confirm="editConfirm" @close="editClose" :isShowStatus="true"
			:allowEditStatus="true" :isShowBalance="true">
		</count-qty-edit>
		<comwinHint ref="comHint"></comwinHint>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getCountJobDetail,
		countJobSubmit
	} from '@/api/request2.js';
	import {
		calc
	} from '@/common/calc.js';

	import {
		Decimal
	} from 'decimal.js'; //引入

	import {
		goHome,
		navigateBack,
		getPackingNumberAndBatch,
		compare,
		deepCopyData
	} from '@/common/basic.js';
	import {
		getCountStageName
	} from '@/common/directory.js';

	import {
		getDetailOption,
		getDetailEditRemoveOption,
		getClearOption
	} from '@/common/array.js';

	import {
		getManagementPrecisions,
	} from '@/common/balance.js';


	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import comCountDetailcards from '@/pages/count/coms/comCountDetailcards.vue'
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import countQtyEdit from '@/mycomponents/qty/countQtyEdit.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import detailInfoPopup from '@/pages/count/coms/detailInfoPopup.vue'
	import comwinHint from '@/pages/count/coms/comwinHint.vue'


	export default {
		name: 'receipt_detail',
		components: {
			winScanButton,
			winScanPack,
			comCountDetailcards,
			winScanPackAndLocation,
			countQtyEdit,
			jobTop,
			detailInfoPopup,
			comwinHint
		},
		data() {
			return {
				id: '',
				locationCode: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				balance: {}, //库存余额
				currentEditItem: {},
				mainItem: {},
				jobStatus: "",
				scanCount: 0,
				index: 0,
				dataList: [],
				managementList: [],
				isOpen: false,
				manageMode: ""

			};
		},
		onLoad(option) {
			this.id = option.id;
			if (this.id) {
				this.getDetail();
			}
			uni.$on('refreshData', (data) => {
				// 调用刷新数据的方法
				this.refreshData(data);
			});
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from === 'backbutton') {
				uni.navigateBack();
				return true;
			}
		},


		mounted() {

		},

		computed() {},
		methods: {
			getManageMode(value) {
				var manageMode = ""
				if (value == 'BY_BATCH') {
					manageMode = "按批次"
				} else if (value == 'BY_QUANTITY') {
					manageMode = "按数量"
				}
				return manageMode
			},
			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getCountJobDetail(that.id).then(async res => {
					uni.hideLoading();
					if (res.data == null) {
						that.showMessage('未获取到详情');
					} else {
						that.jobContent = res.data;
						that.jobContent.status = "2";
						that.manageMode = that.jobContent.manageMode
						that.locationCode = that.jobContent.locationCode;

						that.dataList = res.data.subList;
						that.dataList.forEach(res => {
							res.scaned = false;
						})

						that.updateList(false)
					}

				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			refreshData(returnData) {
				//记录的数据刷新列表
				//列表中删除了已经扫描的数据
				if (returnData.recordList.length == 0) {
					if (this.manageMode == "BY_BATCH") {
						var mainItem = this.dataList.find(r =>
							r.itemCode == returnData.itemCode &&
							r.batch == returnData.batch &&
							r.inventoryStatus == returnData.inventoryStatus)
						if (mainItem) {
							mainItem.recordList = []
						} else if (this.manageMode == "BY_QUANTITY") {
							var mainItem = this.dataList.find(r =>
								r.itemCode == returnData.itemCode &&
								r.inventoryStatus == returnData.inventoryStatus)

							if (mainItem) {
								mainItem.recordList = []
							}
						}
					}
				} else {
					var addList = []
					returnData.recordList.forEach(subItem => {

						if (this.manageMode == "BY_BATCH") {
							let mainItem = this.dataList.find(r =>
								r.itemCode == subItem.itemCode &&
								r.batch == subItem.batch &&
								r.inventoryStatus == subItem.inventoryStatus)
							//主列表存在数据
							if (mainItem) {
								mainItem.scaned = true;
								mainItem.recordList = []
								mainItem.recordList.push(subItem)
							} else {
								//主列表不存在数据，添加到主列表
								var detail = this.createBackAddDetailInfo(subItem)

								if (!detail.recordList) {
									detail.recordList = []
								}
								var recordItem = {
									scaned: true,
									isNewJobDetail: "true",
									itemCode: subItem.itemCode,
									itemName: subItem.itemName,
									itemDesc1: subItem.itemDesc1,
									itemDesc2: subItem.itemDesc2,
									packingNumber: subItem.packingNumber,
									toPackingNumber: subItem.toPackingNumber,
									toBatch: subItem.toBatch,
									batch: subItem.batch,
									inventoryStatus: subItem.inventoryStatus,
									qty: subItem.qty,
									handleQty: subItem.handleQty,
									uom: subItem.uom,
									packUnit: subItem.packUnit,
									packQty: subItem.packQty,
									balanceQty: subItem.balanceQty,
									locationCode: subItem.locationCode
								}
								detail.recordList.push(recordItem)
								addList.push(detail)
							}
						} else if (this.manageMode == "BY_QUANTITY") {
							var mainItem = this.dataList.find(r =>
								r.itemCode == subItem.itemCode &&
								r.inventoryStatus == subItem.inventoryStatus)
							//主列表存在数据
							if (mainItem) {
								mainItem.scaned = true;
								mainItem.recordList = []
								mainItem.recordList.push(subItem)
							} else {
								//主列表不存在数据，添加到主列表
								var detail = this.createBackAddDetailInfo(subItem)

								if (!detail.recordList) {
									detail.recordList = []
								}
								var recordItem = {
									scaned: true,
									isNewJobDetail: "true",
									itemCode: subItem.itemCode,
									itemName: subItem.itemName,
									itemDesc1: subItem.itemDesc1,
									itemDesc2: subItem.itemDesc2,
									packingNumber: subItem.packingNumber,
									toPackingNumber: subItem.toPackingNumber,
									toBatch: subItem.toBatch,
									batch: subItem.batch,
									inventoryStatus: subItem.inventoryStatus,
									qty: subItem.qty,
									handleQty: subItem.handleQty,
									uom: subItem.uom,
									packUnit: subItem.packUnit,
									packQty: subItem.packQty,
									balanceQty: subItem.balanceQty,
									locationCode: subItem.locationCode
								}
								detail.recordList.push(recordItem)
								addList.push(detail)
							}
						}

					})
					if (addList.length > 0) {
						this.dataList = this.dataList.concat(addList)
					}
				}

				this.updateList(false);

			},


			swipeClick(e, item) {
				if (e.content.text == "详情") {
					this.detail(item)
				} else if (e.content.text == "编辑") {
					this.editItem(item)
				}
			},

			summCount(countAllRecordList) {
				if (countAllRecordList) {
					this.$refs.comHint.openScanPopup(countAllRecordList)
				} else {
					this.showMessage("累计盘点数为0")
				}
			},

			currentCount(recordList) {
				if (recordList) {
					uni.navigateTo({
						url: `/pages/count/job/countRecord?data=${encodeURIComponent(JSON.stringify(recordList))}`
					})
				} else {
					this.showMessage("请先扫描箱码")
				}
			},


			updateData() {},

			openScanPopup() {
				var fromlocationList = [];
				fromlocationList.push(this.locationCode)
				this.$refs.scanPopup.openScanPopupForJob(this.locationCode, fromlocationList, this.jobContent);
			},

			closeScanPopup() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.closeScanPopup();
				}
			},

			scanPopupGetFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.packGetFocus();
				}
			},

			scanPopupLoseFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.packLoseFocus();
				}
			},

			getCountScanResult(result, managementPrecision) {
				var itemCode = result.label.itemCode
				var packingNumber = result.label.packingNumber
				var pack = result.package
				var batch = result.label.batch
				var inventoryStatus = result.balance ? result.balance.inventoryStatus : "OK"
				var qty = result.balance ? result.balance.qty : 0;
				var handleQty = result.label.qty

				var uom = pack.uom
				var locationCode = this.locationCode

				var recordItem = {
					scaned: true,
					isNewJobDetail: "false",
					itemCode: itemCode,
					itemName: pack.itemName,
					itemDesc1: pack.itemDesc1,
					itemDesc2: pack.itemDesc2,
					packingNumber: packingNumber,
					batch: batch,
					toPackingNumber: packingNumber,
					toBatch: batch,
					inventoryStatus: inventoryStatus,
					qty: qty,
					handleQty: handleQty,
					uom: uom,
					packUnit: pack.packUnit,
					packQty: pack.packQty,
					balanceQty: qty,
					locationCode: locationCode
				}
				this.currentEditItem = recordItem;
				this.isOpen = true
				this.$refs.countQtyEdit.openEditPopupShowSeconds(recordItem,
					null);

			},

			setData(scanItem) {
				if (this.isOpen) {
					this.isOpen = false
					//按批次管理
					if (this.manageMode == 'BY_BATCH') {
						//按物料、箱码、批次、状态匹配
						let mainItem = this.dataList.find(r =>
							r.itemCode == scanItem.itemCode &&
							r.locationCode == scanItem.locationCode &&
							r.batch == scanItem.batch &&
							r.inventoryStatus == scanItem.inventoryStatus)

						//在任务列表中,添加到对应的recordList
						if (mainItem) {
							if (!mainItem.recordList) {
								mainItem.recordList = []
							}
							mainItem.scaned = true;
							var subItem = mainItem.recordList.find(res =>
								res.itemCode == scanItem.itemCode &&
								res.locationCode == scanItem.locationCode &&
								res.packingNumber == scanItem.packingNumber &&
								res.batch == scanItem.batch &&
								res.inventoryStatus == scanItem.inventoryStatus
							)
							scanItem.toPackingNumber = ""

							//已经存在，数量累加
							if (subItem) {
								subItem.handleQty = calc.add(Number(subItem.handleQty), Number(scanItem.handleQty))
							} else {
								mainItem.recordList.unshift(scanItem)
							}
						} else {
							//不在任务列表中,添加到列表中
							var detail = this.createAddDetailInfo(scanItem)
							scanItem.isNewJobDetail = "true"

							if (!detail.recordList) {
								detail.recordList = []
							}

							var subItem = detail.recordList.find(res =>
								res.itemCode == scanItem.itemCode &&
								res.locationCode == scanItem.locationCode &&
								res.packingNumber == scanItem.packingNumber &&
								res.batch == scanItem.batch &&
								res.inventoryStatus == scanItem.inventoryStatus
							)
							scanItem.toPackingNumber = ""

							//已经存在，数量累加
							if (subItem) {
								subItem.handleQty = calc.add(Number(subItem.handleQty), Number(scanItem.handleQty))
							} else {
								detail.recordList.unshift(scanItem)
							}

							this.dataList.unshift(detail)
						}

					} else if (this.manageMode == 'BY_QUANTITY') {
						let item = this.dataList.find(r =>
							r.itemCode == scanItem.itemCode &&
							r.locationCode == scanItem.locationCode &&
							r.inventoryStatus == scanItem.inventoryStatus)
						//在任务列表中,添加到对应的recordList
						if (item) {
							if (!item.recordList) {
								item.recordList = []
							}
							item.scaned = true;
							var subItem = item.recordList.find(res =>
								res.itemCode == scanItem.itemCode &&
								res.packingNumber == scanItem.packingNumber &&
								res.batch == scanItem.batch &&
								res.locatioCode == scanItem.locatioCode &&
								res.inventoryStatus == scanItem.inventoryStatus
							)

							//已经存在，数量累加
							if (subItem) {
								subItem.toPackingNumber = "",
									subItem.toBatch = ""
								subItem.handleQty = calc.add(Number(subItem.handleQty), Number(scanItem.handleQty))
							} else {
								item.recordList.unshift(scanItem)
							}


						} else {
							//不在任务列表中,添加到列表中
							var detail = this.createAddDetailInfo(scanItem)

							if (!detail.recordList) {
								detail.recordList = []
							}
							var subItem = detail.recordList.find(res =>
								res.itemCode == scanItem.itemCode &&
								res.packingNumber == scanItem.packingNumber &&
								res.batch == scanItem.batch &&
								res.inventoryStatus == scanItem.inventoryStatus
							)

							//已经存在，数量累加
							if (subItem) {
								subItem.toPackingNumber = "",
									subItem.toBatch = ""
								subItem.handleQty = calc.add(Number(subItem.handleQty), Number(scanItem.handleQty))
							} else {
								detail.recordList.unshift(scanItem)
							}

							this.currentEditItem = scanItem;
						}
					}
					this.updateList(true);
				}

			},

			updateList(isGetFocus) {
				this.calcScanCount()
				this.calcQtyAndUpdateSatus()
				this.sortList();
				this.$forceUpdate()
				if (isGetFocus) {
					this.scanPopupLoseFocus()
				}

			},
			editConfirm(qty, inventoryStatus, mode) {
				//需要考虑，是否修改状态，修改状态直接添加到列表，不修改，只修改数量
				this.currentEditItem.handleQty = qty;
				this.currentEditItem.inventoryStatus = inventoryStatus;
				this.setData(this.currentEditItem);
				console.log("editConfirm")

			},

			calcQtyAndUpdateSatus() {
				this.dataList.forEach(item => {
					if (Number(item.currentQty) == 0) {
						if (Number(item.totalRecordCountQty) >= Number(item.qty)) {
							item.countStatus = "finish"
						} else {
							item.countStatus = "wait"
						}
					} else if (Number(item.currentQty) > 0) {
						item.countStatus = "doing"
					}
				})
			},

			sortList() {
				const statusOrder = {
					'wait': 1,
					'doing': 2,
					'finish': 3
				};

				this.dataList.sort((a, b) => {
					return statusOrder[a.countStatus] - statusOrder[b.countStatus];
				});

			},


			calcScanCount() {
				this.dataList.forEach(main => {
					var handleQty = 0;
					if (main.recordList) {
						main.recordList.forEach(item => {
							handleQty = calc.add(handleQty, Number(item.handleQty))
						})
					}
					main.currentQty = handleQty
				})

			},

			editClose() {
				this.setData(this.currentEditItem);
			},


			//创建盘盈的明细
			createAddDetailInfo(scanImte) {
				var detail = {
					scaned: true,
					isNewJobDetail: "true",
					batch: scanImte.batch,
					countAllRecordList: [],
					currentQty: 0,
					id: "",
					inventoryStatus: scanImte.inventoryStatus,
					itemCode: scanImte.itemCode,
					itemName: scanImte.itemName,
					itemDesc1: scanImte.itemDesc1,
					itemDesc2: scanImte.itemDesc2,
					packingNumber: scanImte.packingNumber,
					qty: 0,
					totalRecordCountQty: 0,
					uom: scanImte.uom,
					locationCode: scanImte.locationCode,

				}
				return detail;
			},

			//创建盘盈的明细
			createBackAddDetailInfo(subItem) {
				var detail = {
					scaned: true,
					isNewJobDetail: "true",
					batch: subItem.batch,
					countAllRecordList: [],
					currentQty: 0,
					id: "",
					inventoryStatus: subItem.inventoryStatus,
					itemCode: subItem.itemCode,
					itemName: subItem.itemName,
					itemDesc1: subItem.itemDesc1,
					itemDesc2: subItem.itemDesc2,
					packingNumber: subItem.packingNumber,
					qty: 0,
					totalRecordCountQty: 0,
					uom: subItem.uom,
					locationCode: subItem.locationCode
				}
				return detail;
			},

			submitJob() {

				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				var params = this.setParams()
				countJobSubmit(params).then(res => {
					uni.hideLoading()
					const str = res.data || ''
					this.showCommitSuccessMessage("提交成功\n生成盘点记录\n" + str)
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			checkData() {
				var isCheck = false;
				this.dataList.forEach(item => {
					if (item.scaned) {
						isCheck = true
					}
				})
				return isCheck;
			},

			setParams() {
				var submitData = {
					number: this.jobContent.number,
					locationCode: this.locationCode,
					recordList: []
				}
				this.dataList.forEach(item => {
					if (item.scaned && item.recordList && item.recordList.length > 0) {
						submitData.recordList = submitData.recordList.concat(item.recordList)

					}

				})
				return submitData;
			},


			showMessage(message) {
				this.$refs.comMessage.showMessage(message, res => {
					if (res) {
						this.afterCloseMessage()
					}
				});
			},
			showErrorMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {
						this.afterCloseMessage()
					}
				});
			},

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

			afterCloseMessage() {
				this.scanPopupGetFocus();
			},

			closeScanMessage() {
				this.scanPopupGetFocus();
			},

			editItem(item) {
				this.currentEditItem = item;
				this.$refs.countQtyEdit.openEditPopup(this.currentEditItem,
					null);
			},

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					navigateBack(1);
				})
			},
			getCountStageName(value) {
				return getCountStageName(value)
			},

		}

	}
</script>

<style scoped lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	.page-wraper {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	.header {
		position: fixed;
		/* #ifdef H5 */
		top: 88rpx;
		/* #endif */
		left: 0;
		width: 100%;
		background-color: #fff;
		z-index: 10;
		padding: 10rpx;
		/* 确保头部在内容之上 */
	}

	.page-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}


	.page-main {
		flex: 1;
		position: relative;
	}

	.page-main-scroll {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}

	.page-main-list {
		/*  height: 80rpx;
	    line-height: 80rpx; */
		text-align: center;
		background: #e0e0e0;

	}

	.item {
		background-color: #fff;
	}

	.item_scaned {
		background-color: antiquewhite;
	}
</style>