<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header_job_top">
				<job-top :dataContent="jobContent"></job-top>
				<uni-collapse ref="collapse">
					<uni-collapse-item :open="true">
						<template v-slot:title>
							<view class="card_itemName" style="padding: 3px 5px; font-size: 28rpx;">
								盘点范围
							</view>
						</template>
						<view v-for="(range, index) in jobContent.countRange" :key="index">
							<view class="card_view">
								<text class="card_packing_code ">{{getCountScopeName(range.type)}}</text>
								<text class="card_content ">{{range.value}}</text>
							</view>
						</view>
					</uni-collapse-item>
				</uni-collapse>
			</view>
			<view class="card_view" v-if="fromLocationCode!=''">
				<text class="card_location">盘点库位</text>
				<text class="card_content ">{{fromLocationCode}}</text>
			</view>
		</view>
		<com-blank-view @goScan='showFromLocationPopup' v-if="detailSource.length==0"></com-blank-view>
		<view class="page-main">

			<scroll-view scroll-y="true" class="page-main-scroll">
				<uni-swipe-action ref="swipeAction">
					<view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
						<uni-swipe-action-item @click="swipeClick($event,item,index)" :right-options="editRemoveOption">
							<view class="">
								<package-and-item-card :dataContent="item"></package-and-item-card>
							</view>
							<view class='split_line'></view>
						</uni-swipe-action-item>
					</view>
				</uni-swipe-action>
			</scroll-view>
		</view>

		<view class="page-footer" v-if="detailSource.length>0">
			<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="commit">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button v-if="fromLocationCode!=''" @goScan='openScanPopup'></win-scan-button>
		<win-scan-pack ref="scanPopup" @getResult='getScanResult'></win-scan-pack>
		<win-scan-location ref="scanLocationCode" title="盘点库位" @getLocation='getLocation'></win-scan-location>
		<count-qty-edit ref="countQtyEdit" @confirm="editConfirm" @close="editClose" :isShowStatus="true"
			:allowEditStatus="editInventoryStatus" :isShowBalance="jobContent.isOpenCount=='TRUE'">
		</count-qty-edit>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

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

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

	import {
		getEditRemoveOption
	} from '@/common/array.js';

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

	import {
		getCountScopeType
	} from '@/common/directory.js';


	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import comCountDetailCard from '@/pages/count/coms/comCountDetailCard.vue'
	// import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import winScanLocation from "@/mycomponents/scan/winScanLocation.vue"
	import countQtyEdit from '@/mycomponents/qty/countQtyEdit.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'
	import PackageAndItemCard from '@/mycomponents/package/PackageAndItemCard.vue'

	export default {
		name: 'fuzzycountdetail',
		components: {
			winScanButton,
			winScanPack,
			comCountDetailCard,
			// winScanPackAndLocation,
			winScanLocation,
			countQtyEdit,
			jobTop,
			comBlankView,
			PackageAndItemCard
		},
		data() {
			return {
				id: '',
				scanCount: 0,
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				balance: {}, //库存余额
				editInventoryStatus: false,
				package: {}, //包装
				label: {}, //标签
				currentEditItem: {},
				jobStatus: "",
				fromLocation: {},
				fromLocationCode: '',
				editRemoveOption: [],
				itemRangeValue: ""
			};
		},
		onLoad(option) {
			this.id = option.id;
			if (this.id != undefined) {
				//新建的任务自动接收
				if (option.status == "1") {
					this.receive((callback => {
						this.getDetail(r => {
							this.showFromLocationPopup();
						});
					}));
				} else {
					this.getDetail(r => {
						this.showFromLocationPopup();
					});
				}
			}
			this.editRemoveOption = getEditRemoveOption();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from === 'backbutton') {
				if (this.jobStatus == "2") {
					//取消承接任务	
					cancleTakeCountJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}
				return true;
			}
		},

		onPullDownRefresh() {

			// uni.stopPullDownRefresh();
		},

		mounted() {

		},
		methods: {
			//接收
			receive(callback) {
				if (this.id != null) {
					takeCountJob(this.id).then(res => {
						callback();
					}).catch(error => {
						this.showErrorMessage(error)
					})
				}
			},

			getDetail(callback) {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getFuuzyCountJobDetail(that.id).then(res => {
					uni.hideLoading();
					that.jobContent = res.data;
					that.jobStatus = res.data.status;
					let range = that.jobContent.countRange.find(r => r.type == "ITEMS_CODE");
					if (range != undefined) {
						that.itemRangeValue = range.value;
					}
					callback();

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

			showFromLocationPopup() {
				let as = '';
				// this.$refs.scanLocationCode.openScanPopup();
				this.$nextTick(() => {
					this.$refs.scanLocationCode.openScanPopup();
				})
			},

			getLocation(location, code) {
				let countRange = this.jobContent.countRange;

				if (countRange != null) {
					let range = countRange.find(r => r.type == "LOCATION_CODE");
					if (range != undefined) {
						let rangeValue = range.value;
						let index = rangeValue.indexOf(location.code)
						if (index < 0) {
							this.afterScanLocation("库位代码【" + location.code + "】,不在盘点库位范围【" + rangeValue + "】内");
							return;
						}
					} else {
						range = countRange.find(r => r.type == "LOCATIONGROUP_CODE");
						if (range != undefined) {
							let rangeValue = range.value;
							let index = rangeValue.indexOf(location.locationGroupCode)
							if (index < 0) {
								this.afterScanLocation("库位组代码【" + location.locationGroupCode + "】,不在盘点库位组范围【" +
									rangeValue +
									"】内");
								return;
							}
						} else {
							range = countRange.find(r => r.type == "AREABASIC_CODE");
							if (range != undefined) {
								let rangeValue = range.value;
								let index = rangeValue.indexOf(location.areaCode)
								if (index < 0) {
									this.afterScanLocation("库区代码【" + location.areaCode + "】,不在盘点库区范围【" +
										rangeValue + "】内");
									return;
								}
							} else {
								range = countRange.find(r => r.type == "WAREHOUSE_CODE");
								if (range != undefined) {
									let rangeValue = range.value;
									let index = rangeValue.indexOf(location.warehouseCode)
									if (index < 0) {
										this.afterScanLocation("仓库代码【" + location.warehouseCode + "】,不在盘点仓库范围【" +
											rangeValue +
											"】内");
										return;
									}
								}
							}
						}
					}
				}
				this.getFromLocationCode(location, code)
			},

			afterScanLocation(message) {
				this.showErrorMessage(message)
				this.showFromLocationPopup();
			},

			getFromLocationCode(location, code) {
				this.fromLocation = location;
				this.fromLocationCode = code;
				this.openScanPopup();
			},

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

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

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

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

			getScanResult(result) {
				let that = this;
				let packInfo = result.package;
				if (this.itemRangeValue != '') {
					let index = this.itemRangeValue.indexOf(packInfo.itemCode)
					if (index < 0) {
						this.afterScanLocation("物料代码【" + packInfo.itemCode + "】,不在盘点范围【" + this.itemRangeValue + "】内");
						return;
					} else {
						this.onScan(packInfo);
					}
				} else {
					this.onScan(packInfo);
				}
			},

			onScan(packInfo) {
				let detail = this.detailSource.find(r => r.itemCode == packInfo.itemCode && r.packingNumber == packInfo
					.number && r.batch == packInfo.batch && r.inventoryStatus == "OK");
				if (detail == undefined) {
					detail = this.createDetailInfo(packInfo);
					this.detailSource.unshift(detail)
					this.scanPopupGetFocus();
				} else {
					let index = this.detailSource.findIndex(r => r.itemCode == packInfo.itemCode && r.packingNumber ==
						packInfo
						.number && r.batch == packInfo.batch && r.inventoryStatus == "OK");
					if (index >= 0) {
						this.detailSource.unshift(this.detailSource.splice(index, 1)[0]); //置顶
						//提交
						this.$refs.comMessage.showQuestionMessage('该箱码已经扫描,是否要编辑盘点明细?', res => {
							if (res) {
								this.closeScanPopup();
								this.edit(detail);
							} else {
								this.scanPopupGetFocus();
							}
						});
					}
				}
			},

			//创建盘盈的明细
			createDetailInfo(packInfo) {
				var detail = {
					scaned: true,
					// countDetailNumber: "",
					number: this.jobContent.number,
					packingNumber: packInfo.number,
					batch: packInfo.batch,
					inventoryStatus: "OK",
					itemCode: packInfo.itemCode,
					itemName: packInfo.itemName,
					itemDesc1: packInfo.itemDesc1,
					itemDesc2: packInfo.itemDesc2,
					projectCode: "",
					qty: packInfo.qty,
					packUnit: packInfo.packUnit,
					packQty: packInfo.packQty,
					packUom: packInfo.packUom,
					uom: packInfo.uom,
					remark: "",
					locationCode: this.fromLocationCode,
					creator: this.$store.state.user.id,
					warehouseCode: this.fromLocation.warehouseCode,
					areaCode: this.fromLocation.areaCode,
					locationGroupCode: this.fromLocation.locationGroupCode,
					createTime: new Date().getTime(),
					countTime: new Date().getTime(),
					countUser: this.$store.state.user.id,
					countDescription: 'a',
					countQty: packInfo.qty
				}
				return detail;
			},

			editClose() {
				this.$refs.countQtyEdit.closeEditPopup();
			},

			swipeClick(e, item, index) {
				if (e.content.text == "编辑") {
					this.edit(item)
				} else if (e.content.text == "移除") {
					this.remove(item)
				}
			},

			//编辑盘点结果
			edit(item) {
				let that = this;
				this.currentEditItem = item;
				item.handleQty = item.qty;
				this.$refs.countQtyEdit.openEditPopup(item, null);
			},

			editConfirm(qty, inventoryStatus, mode) {
				let that = this;
				this.currentEditItem.countQty = qty;
				this.currentEditItem.qty = qty;
				this.currentEditItem.inventoryStatus = inventoryStatus;
				this.openScanPopup();
			},

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

			remove(item, index) {
				this.showQuestionMessage("是否要移除扫描信息?", res => {
					if (res) {
						this.detailSource.splice(index, 1)
					}
				});
			},



			detail(item) {
				this.showItem = item;
				this.$refs.detailInfoPopup.openPopup(item);
			},

			commit() {
				if (this.detailSource.length == 0) {
					this.$refs.comMessage.showMessage('还未扫描,是否要继续提交', res => {
						if (res) {
							this.commitJob();
						}
					});
				} else {
					this.commitJob();
				}
			},

			commitJob() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				var params = this.setParams()
				console.log("提交参数", JSON.stringify(params));
				countJobSubmit(params).then(res => {
					uni.hideLoading()
					if (res.data == null) {
						this.showCommitSuccessMessage("提交成功")
					} else {
						this.showErrorMessage("提交失败[" + res.msg + "]")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},


			setParams() {
				var creator = this.$store.state.user.id
				this.jobContent.subList = this.detailSource
				// this.jobContent.creator = creator;
				return this.jobContent;
			},


			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();
			},

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					this.fromLocationCode = '';
					this.fromLocation = {};
					this.detailSource = [];
					this.showFromLocationPopup();
				})
			},
			getCountStageName(value) {
				return getCountStageName(value)
			},
			isOpenCount(value) {
				return value == "TRUE" ? "明盘" : "盲盘"
			},

			getCountScopeName(value) {
				let item = getCountScopeType(value);
				return item.label;
			},

			showQuestionMessage(message, callback) {
				this.$refs.comMessage.showQuestionMessage(message, res => {
					callback(res);
				});
			},
		}
	}
</script>

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

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


	// .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;

	// }
</style>