<template>
	<view>
		<uni-popup ref="popup" @change="change" :mask-click="false">
			<view class="popup_box">
				<view class="pop_title uni-flex space-between">
					<view class="" style="font-size: 35rpx;">
						扫描{{title}}
					</view>

					<view class="">
						<image class="fr icons_scan_close" src="/static/icons/icons_scan_close.svg" @click="closeScanPopup()">
						</image>
					</view>
				</view>
				<view class="uni-flex uni-row" style="align-items: center;
					background-color: #fff; 
					margin-left: 20rpx;
					margin-right: 20rpx;
					border-radius: 8rpx;
					height: 30px;">
					<view class="uni-center" style="width: 25%; font-size: 35rpx;">
						来源库位
					</view>
					<!-- style="width: 75%;padding: 8rpx" -->
					<view class="">
						<!-- <input v-model="fromLocationCode" placeholder="请扫描来源库位" :focus="locationOnFocus"
							placeholder-style="font-size:12px" style="padding: 5px;" @confirm="scanLocation" /> -->

						<view v-if='allowModifyLocation'>
							<uni-combox :candidates="fromLocationList" v-model="fromLocationCode" placeholder="请扫描来源库位"
								@confirm="handleConfirm" style='height: 30rpx;border:1px solid #fff ;'></uni-combox>
						</view>
						<view v-else>
							<text style="padding: 5px;font-size: 40rpx;">
								{{fromLocationCode}}
							</text>
						</view>
					</view>
				</view>
				<view class="">
					<view class="">
						<win-com-scan ref="comscan" :placeholder="title" @getResult="getScanResult" :isShowHistory="isShowHistory"
							:clearResult="true" :headerType="headerType"></win-com-scan>
					</view>
				</view>
			</view>
		</uni-popup>
		<balance-select ref="balanceSelect" @onSelectItem='selectBalanceItem'></balance-select>

	</view>
	<comMessage ref="comMessage"></comMessage>
</template>

<script>
	import winComScan from '@/mycomponents/scan/winComScan.vue'
	import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'
	import {
		getBalanceByManagementPrecisionByPacking,
	} from '@/common/balance.js';

	import {
		getBasicLocationByCode,
	} from '@/api/request2.js';


	import {
		getLabelInfo
	} from '@/common/label.js';

	import {
		getListLocationAreaTypeDesc,
		checkDirectoryItemExist,
		getDirectoryItemArray,
		getLocationAreaTypeName,
		getInventoryStatusDesc
	} from '@/common/directory.js';
	export default {
		name: 'winScanPack',
		emits: ["getResult", "close", "getCountScanResult", "confirm"],
		components: {
			winComScan,
			balanceSelect
		},
		props: {
			title: {
				type: String,
				default: '箱标签'
			},
			isShowHistory: {
				type: Boolean,
				default: true
			},
			allowNullBalance: {
				type: Boolean,
				default: false
			},
			//不提示库存错误
			noShowBalanceMessage: {
				type: Boolean,
				default: false
			},
			//
			isCount: {
				type: Boolean,
				default: false
			},
			//是否允许修改库位
			allowModifyLocation: {
				type: Boolean,
				default: true
			},
			headerType: {
				type: String,
				default: "HPQ,HMQ"
			},
			queryBalance: {
				type: Boolean,
				default: true
			},
			balanceFromInventoryStatuses: { //是否传fromInventoryStatuses
				type: Boolean,
				default: true
			},
			toLocationCode: {
				type: String,
				default: ""
			},
		},
		data() {
			return {
				scanResult: {},
				show: false,
				scanList: [],
				expand: false,
				showScanResult: {},
				expendIcon: 'arrow-down',
				fromLocationCode: '',
				fromLocation: '',
				fromLocationList: [],
				fromLocationAreaTypeList: [],
				locationOnFocus: false,
				businessType: {},
				inventoryStatus: [],
				managementPrecision: '',
				fromInventoryStatuses: "",
				isCheck: false,
				chooseWhich: '1'
			}
		},
		created() {

		},
		methods: {

			handleConfirm() {
				this.$emit('confirm', this.fromLocationCode)
			},
			//直接扫描
			openScanPopupForType(fromLocationCode, businessType) {
				this.businessType = businessType;
				this.fromLocationCode = fromLocationCode;

				this.fromInventoryStatuses = getDirectoryItemArray(this.businessType.outInventoryStatuses)
				this.inventoryStatus = getDirectoryItemArray(this.businessType.outInventoryStatuses); //出库库存状态
				this.fromLocationAreaTypeList = getDirectoryItemArray(this.businessType.outAreaTypes); //出库库区
				this.$refs.popup.open('bottom')
				setTimeout(res => {
					if (fromLocationCode != '') {
						this.packGetFocus();
					} else {
						this.locationGetFocus();
					}
				}, 500)
			},

			//在任务中扫描
			openScanPopupForJob(fromLocationCode, fromLocationList, jobContent) {
				this.fromLocationCode = fromLocationCode;
				this.fromLocationList = fromLocationList;
				this.fromInventoryStatuses = getDirectoryItemArray(jobContent.outInventoryStatuses)
				this.inventoryStatus = getDirectoryItemArray(jobContent.outInventoryStatuses); //出库库存状态; //出库库存状态
				this.fromLocationAreaTypeList = getDirectoryItemArray(jobContent.fromAreaTypes); //出库库存状态
				this.$refs.popup.open('bottom')

				setTimeout(res => {
					if (this.fromLocationCode != '') {
						this.packGetFocus();
					} else {
						if (this.fromLocationList.length == 0) {
							this.locationGetFocus();
						} else {
							this.fromLocationCode = this.fromLocationList[0];
							this.packGetFocus();
						}
					}
				}, 500)

			},
			//模拟扫描
			openScanPopupForJobSimulate(fromLocationCode, fromLocationList, jobContent, scanMessage) {
				this.fromLocationCode = fromLocationCode;
				this.fromLocationList = fromLocationList;
				if (!fromLocationCode) {
					if (this.fromLocationList.length == 0) {
						// this.locationGetFocus();
						alert('没有来源库位:List')
					} else {
						this.fromLocationCode = this.fromLocationList[0];
					}
				}

				this.fromInventoryStatuses = getDirectoryItemArray(jobContent.outInventoryStatuses)
				this.inventoryStatus = getDirectoryItemArray(jobContent.outInventoryStatuses); //出库库存状态; //出库库存状态
				this.fromLocationAreaTypeList = getDirectoryItemArray(jobContent.fromAreaTypes); //出库库存状态
				uni.showLoading({
					title: "获取标签信息",
					mask: true
				})
				getLabelInfo(scanMessage, this.headerType, callback => {
					uni.hideLoading()
					if (callback.success) {
						this.getScanResult(callback);
					} else {
						this.showErrorMessage(callback.message, res => {})
					}

				})

			},

			closeScanPopup(content) {
				this.packLoseFocus()
				this.$refs.popup.close();
				this.$emit("close", '');
			},


			scanLocation(scanResult) {
				var isCheck = false;
				if (this.fromLocationCode == '') {
					this.showErrorMessage('来源库位不能为空', callback => {
						this.locationGetFocus();
					})
					return;
				}

				if (this.fromLocationList.length > 0) {
					if (!this.isInLocationList(this.fromLocationCode)) {
						this.showErrorMessage("扫描库位【" + this.fromLocationCode + '】不在任务来源库位中', callback => {
							this.locationGetFocus();
						})
						return;
					}
				}

				uni.showLoading({
					title: '扫描中...',
					mask: true
				});
				getBasicLocationByCode(this.fromLocationCode).then(res => {
					if (res.data.total > 0) {
						let result = res.data.list[0];
						if (result.code != this.fromLocationCode) {
							this.showErrorMessage('未查询到库位[' + this.fromLocationCode + ']')
							return;
						}
						var type = result.areaType;
						var available = result.available;
						if (available == "TRUE") {
							if (checkDirectoryItemExist(this.fromLocationAreaTypeList, type)) {
								this.location = result;
								// this.packGetFocus();
								this.checkPackage(scanResult);
							} else {
								uni.hideLoading();
								var hint = getListLocationAreaTypeDesc(this.fromLocationAreaTypeList);
								this.showErrorMessage("扫描库位[" + this.fromLocationCode + "]是[" +
									getLocationAreaTypeName(result.areaType) + "],需要的库区是[" + hint + "]")
							}
						} else {
							uni.hideLoading();
							this.showErrorMessage("扫描库位[" + this.fromLocationCode + "]不可用", res => {
								this.locationGetFocus();
							})
						}
					} else {
						uni.hideLoading();
						this.showErrorMessage('未查询到库位[' + this.fromLocationCode + ']', res => {
							this.locationGetFocus();
						})
					}
				}).catch(error => {
					uni.hideLoading();
					this.showErrorMessage(error, res => {
						this.locationGetFocus();
					})
				})
			},

			getScanResult(result) {
				// console.log("扫描", result)
				// if (this.fromLocationCode == '' || this.fromLocationCode == null) {
				// 	this.showMessage('请先扫描来源库位', callback => {
				// 		this.locationGetFocus();
				// 	})
				// 	return;
				// } else
				this.scanLocation(result);
				// debugger
				// if(this.isCheck){
				// 	this.checkPackage(result);
				// }
			},

			async checkPackage(result) {
				if (result.label != null) {
					this.scanResult = result;
					if (this.queryBalance == true) {
						// uni.showLoading({
						// 	title: '查询中...',
						// 	mask: true
						// })
						// 采购上架任务--大哥让去掉 fromInventoryStatuses
						// 获取精度
						await getBalanceByManagementPrecisionByPacking(result.label, result.package, this.fromLocationCode, this
							.balanceFromInventoryStatuses ? this.fromInventoryStatuses : undefined,
							res => {
								uni.hideLoading();
								if (res.success) {
									this.managementPrecision = res.managementPrecision
									if (this.managementPrecision == 'BY_BATCH') {
										res.data.list.forEach(item => {
											item.packingNumber = ''
										})
									}
									this.chooseWhich = '2'
									if (res.data && res.data.list && res.data.list.length > 1) {
										this.showBalanceSelect(res.data.list);
									} else {
										this.afterQueryBalance(res.data.list);
									}
								} else {
									this.showErrorMessage(res.message, res => {
										this.packGetFocus();
									})
								}
								// uni.hideLoading();
							});
					} else {
						uni.hideLoading();
						this.packCallBack(null);
					}
				}
			},


			afterQueryBalance(datas) {
				if (this.allowNullBalance) {
					this.allowNoneBalance(datas);
				} else if (this.noShowBalanceMessage) {
					if (this.isCount) {
						this.countCallBack(datas);
					} else {
						if (Array.isArray(datas)) {
							this.countCallBack(datas[0]);
						} else {
							this.countCallBack(datas);
						}
					}

				} else {
					this.mustHavaBalance(datas);
				}
				uni.hideLoading();
			},

			//允许无库存
			async allowNoneBalance(datas) {
				if (datas.length == 0) {
					await this.packCallBack(null);
				} else {
					this.showErrorMessage('在来源库位[' + this.fromLocationCode + '],已经查找到该包装的库存记录,请重新扫描', res => {
						this.packGetFocus();
					})
				}
			},

			//必须有库存
			mustHavaBalance(datas) {
				if (datas.length == 0) {
					this.showErrorMessage(this.getQueryCondition() + '\n未查找到库存记录', res => {
						this.packGetFocus();
					})
				} else if (datas.length == 1) {
					let balance = datas[0];
					this.packCallBack(balance);

					//因为盘点时有负库存,暂时去掉判断  2023年12月28日

					// if (balance.qty > 0) {
					// 	this.packCallBack(balance);
					// } else {
					// 	this.showErrorMessage(this.getQueryCondition() + '\n查找到库存记录数量为[' + balance.qty + "],\n不可以进行操作",
					// 		res => {
					// 			this.packGetFocus();
					// 		})
					// }
				} else {
					this.showBalanceSelect(datas);
					this.chooseWhich = '1'
				}
			},

			showBalanceSelect(items) {
				this.$refs.balanceSelect.openPopup(items);
			},

			selectBalanceItem(balance) {
				if (this.chooseWhich == 1) {
					this.packCallBack(balance);
				} else {
					this.countCallBack(balance);
				}
				// this.packCallBack(balance);
				//因为盘点时有负库存,暂时去掉判断  2023年12月28日
				// if (balance.qty > 0) {
				// 	this.packCallBack(balance);
				// } else {
				// 	this.showErrorMessage(this.getQueryCondition() + '\n查找到库存记录数量为[' + balance.qty + "],不可以进行操作",
				// 		res => {
				// 			this.packGetFocus();
				// 		})
				// }
			},

			//盘点回调
			countCallBack(datas) {
				if (this.$refs.comscan) {
					this.$refs.comscan.clear();
				}
				//返回标签信息、库存信息和管理模式
				let data = {
					label: this.scanResult.label,
					package: this.scanResult.package,
					balance: datas,
					fromLocationCode: this.fromLocationCode,
				}
				// this.packGetFocus();
				// 如果管理精度是批次或者数量,给父组件多返回一个参数
				if (this.managementPrecision == 'BY_BATCH'||this.managementPrecision == 'BY_QUANTITY') {
					this.$emit("getResult", data, this.managementPrecision);
				} else {
					this.$emit("getResult", data);
				}
				this.$emit("getCountScanResult", data);
			},

			async packCallBack(item) {
				if (this.$refs.comscan) {
					this.$refs.comscan.clear();
				}
				//返回标签信息、库存信息和管理模式
				let data = {
					label: this.scanResult.label,
					package: this.scanResult.package,
					balance: item,
					fromLocationCode: this.fromLocationCode,
				}
				this.packGetFocus();
				// 如果管理精度是批次或者数量,给父组件多返回一个参数
				if (this.managementPrecision == 'BY_BATCH'||this.managementPrecision == 'BY_QUANTITY') {
					this.$emit("getResult", data, this.managementPrecision);
				} else {
					this.$emit("getResult", data);
				}
			},

			packGetFocus() {
				if (this.$refs.comscan) {
					this.$refs.comscan.getfocus();
				}
			},

			packLoseFocus() {
				if (this.$refs.comscan) {
					this.$refs.comscan.losefocus();
				}
			},

			locationGetFocus() {
				this.fromLocationCode = '';
				this.locationOnFocus = true;
			},

			getQueryCondition() {
				let condition = '按照以下条件:\n';
				let label = this.scanResult.label;
				var isShowStatus = this.balanceFromInventoryStatuses ? this.fromInventoryStatuses : undefined
				let status = ""
				if (isShowStatus) {
					status = getInventoryStatusDesc(isShowStatus);
				}

				switch (this.managementPrecision) {
					case 'BY_PACKAGING':
						condition = condition + '物料号=[' + label.itemCode + ']\n箱码=[' + label.packingNumber +
							']\n批次=[' +
							label.batch +
							']\n库位=[' + this.fromLocationCode + ']'

						break;
					case 'BY_BATCH':
						condition = condition + '物料号=[' + label.itemCode + ']\n批次=[' +
							label.batch +
							']\n库位=[' + this.fromLocationCode + ']'
						break;
					case 'BY_QUANTITY':
						condition = condition + '物料号=[' + label.itemCode + ']\n库位=[' + this.fromLocationCode + ']'
						break;
					case 'BY_UNIQUEID':
						condition = condition + '物料号=[' + label.itemCode + ']'
						break;
				}
				if (status) {
					condition = condition + '\n库存状态=[' + status + ']'
				}
				return condition;
			},


			showMessage(message, callback) {
				setTimeout(r => {
					this.packLoseFocus();
					this.$refs.comMessage.showMessage(message, callback);
				})
			},

			showErrorMessage(message, callback) {
				setTimeout(r => {
					this.packLoseFocus();
					this.$refs.comMessage.showErrorMessage(message, callback)
				})
			},

			change(e) {
				this.show = e.show
			},
			isInLocationList(location) {

				var item = this.fromLocationList.find(res => res == location)

				if (item = undefined) {
					return false
				}
				return true
			},
			addLocationCode(code) {
				if (!this.isInLocationList(code)) {
					this.fromLocationList.push(code)
				}
			}
		}
	}
</script>

<style lang="scss">
	.scroll-view {
		overflow-y: scroll;
		height: auto;
		max-height: 300rpx;
	}
</style>