<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<scroll-view scroll-y="true" class="scrollView">
			<win-blank-view @goScan='openScanPopup' v-if="putawayjobList.length==0"></win-blank-view>
			<view hover-class="uni-list-cell-hover" v-for="(item, index) in putawayjobList" :key="item.id">
				<uni-swipe-action>
					<uni-swipe-action-item :right-options="options" :auto-close="false"
						@click="swipeClick($event,index)">
						<com-putawayjob :datacontent="item">
						</com-putawayjob>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</scroll-view>
		<view class="new_btn_bot" v-if="putawayjobList.length>0">
			<button class="new_save_btn" type="primary" @click="take()" v-if="putawayjobList.length>0">提交</button>
		</view>
		<comMessage ref="comMessage"></comMessage>
		<com-balance ref="balanceItems" @selectedItem='getSelectedBalance'></com-balance>
		<win-scan-button @goScan='openScanPopup' v-if="putawayjobList.length>0"></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult'></win-scan-by-pack>
	</view>
</template>

<script>
	import {
		getBalancesByFilter,
		byContainercode,
		byPackingcode,
		checkjobbypacking,
		checkjobbycontainer
	} from '@/api/index.js';
	import {
		maxPageSize,
		showConfirmMsg,
		getInventoryStatusDesc,
		getLocationTypeDesc,
		goHome,
		getRemoveOption
	} from '@/common/basic.js';
	import {
		printPutawayLabel
	} from '@/common/print.js'
	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import comPutawayjob from '@/mycomponents/coms/task/comPutawayjob.vue';
	import comMessage from '@/mycomponents/common/comMessage.vue'

	export default {
		name: 'putawayjob',
		components: {
			winBlankView,
			comPutawayjob,
			comMessage,
			comBalance,
			winScanButton,
			winScanByPack
		},
		data() {
			return {
				options: [],
				putawayjobList: [],
				status: '',
				pageSize: 1000,
				pageIndex: 1,
				scanType: null, //null未扫描,箱,托
				stype: null,
				submitting: false,
				enableLocationType: '无',
				enableStatus: '无',
				paramLocationType: [],
				paramInventoryStatus: []
			};
		},
		props: {
			datacontent: {
				type: Object,
				value: null
			}
		},
		filters: {
			getInventoryStatus(val) {
				return getInventoryStatusDesc(val);
			}
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}else if(e.index === 1){
				window.location.reload();
			}
		},
		onLoad() {
			//this.chekConfig();
		},
		mounted() {
			this.options = getRemoveOption();
			this.chekConfig();
		},

		methods: {
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup();
			},
			chekConfig() {
				this.paramLocationType = [];
				this.paramInventoryStatus = [];
				if (this.$putawayLocationTypes === undefined || this.$putawayLocationTypes === '') {
					this.enableLocationType = '无';
					this.showMessage('请在配置文件中配置允许上架的库位类型');
					return false;
				} else {
					let types = this.$putawayLocationTypes.split(',');
					this.enableLocationType = '';
					for (var i = 0; i < types.length; i++) {
						let itype = Number(types[i]);
						this.paramLocationType.push(itype);
						let stype = getLocationTypeDesc(itype);
						if (i < types.length - 1) {
							this.enableLocationType += stype + ','
						} else {
							this.enableLocationType += stype
						}
					}

					let status = this.$putawayInventoryStatus.split(',');
					this.enableStatus = '';
					for (var i = 0; i < status.length; i++) {
						let istatu = Number(status[i]);
						this.paramInventoryStatus.push(istatu);
						let sstatu = getInventoryStatusDesc(istatu);
						if (i < status.length - 1) {
							this.enableStatus += sstatu + ','
						} else {
							this.enableStatus += sstatu
						}
					}
				}
				return true;
			},

			getScanResult(result) {
				let that = this;
				let configed = this.chekConfig();
				if (!configed) {
					return
				}
				if (result.data.isPack) {
					if (result.data.itemCode === undefined || result.data.itemCode === '') {
						this.showMessage('扫描的标签中不包含零件号,请重新扫描');
						return;
					}
				}
				//第一次扫描
				if (this.scanType === null || this.scanType === "") {
					this.scanType = result.data.isPack === null ? '' : result.data.isPack ? '箱' : '托';
				} else {
					//与之前的扫描类型不一致
					if ((result.data.isPack && this.scanType != '箱') || (!result.data.isPack && this
							.scanType !=
							'托')) {
						this.showMessage('应该扫描' + this.scanType);
						return;
					}
				}

				let param = {
					pageSize: this.pageSize,
					pageInde: this.pageIndex
				};

				//1.检验是否有任务
				if (that.scanType === '箱') {
					param.packingCode = result.data.packingCode;
					param.itemCode = result.data.itemCode;

					checkjobbypacking(param)
						.then(res => {
							if (res.length === 0) {
								that.handle(result);
							} else {
								this.showMessage(that.scanType + ':' + result.data.packingCode +
									'\n已经有上架任务');
								that.resetScanType();
								return;
							}
						})
						.catch(err => {
							this.showMessage(err.message);
						});
				} else if (that.scanType === '托') {
					param.containerCode = result.data.containerCode;
					// param.itemCode = result.data.itemCode;
					checkjobbycontainer(param)
						.then(res => {
							if (res.length === 0) {
								that.handle(result);
							} else {
								this.showMessage(that.scanType + ':' + result.data.containerCode +
									'\n已经有上架任务');
								that.resetScanType();
								return;
							}
						})
						.catch(err => {
							console.log('list err', err);
						});
				} else {
					this.showMessage('请扫描箱标签');
				}
			},

			swipeClick(e, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.putawayjobList.splice(index, 1);
							}
						}
					});
				}
			},

			handle(result) {
				//2.获取参数
				let that = this;
				let param = that.getParam(result);
				if (param === null) return;
				if (param.packingCode === null && param.containerCode === null) {
					this.showMessage('未获取到正确的参数');
					return;
				}

				//3.判断零件是已经扫描过
				let items = that.checkScanResult(result);
				if (items.length > 0) {
					let code = param.packingCode != undefined ? param.packingCode : param
						.containerCode;
					let msg = this.scanType + '[' + code + ']已经扫描过,是否要重新扫描';
					showConfirmMsg(msg, confirm => {
						if (confirm) {
							this.putawayjobList.forEach((r, i) => {
								if (result.data.isPack) { //箱码
									if (r.packingCode === result.data.packingCode && r
										.itemCode === result.data.itemCode) {
										this.putawayjobList.splice(i, 1);
										return;
									}
								} else {
									if (r.containerCode === result.data.containerCode) {
										this.putawayjobList.splice(i, 1);
									}
								}
							});
							//删除后重新查询
							that.getBalances(param, result);
						}
					});
				} else {
					that.getBalances(param, result);
				}
			},

			//获取箱和托的参数
			getParam(result) {
				if (result.data.scanType === 'qrcode') {
					let param = {
						pageSize: this.pageSize,
						pageIndex: this.pageIndex,
					};
					if (result.data.isPack) { //箱
						if (result.data.packingCode != null) {
							param.packingCode = result.data.packingCode;
							param.itemCode = result.data.itemCode;
						} else {
							this.showMessage('未解析到箱码');
						}
					} else //托
					{
						if (result.data.containerCode != null) {
							param.containerCode = result.data.containerCode;
						} else {
							this.showMessage('未解析到托码');
						}
					}
					return param;
				} else {
					this.showMessage('未解析到条码');
				}
			},

			//检验是否是第二次扫描
			checkScanResult(result) {
				let items = {};
				if (result.data.isPack) { //箱码
					items = this.putawayjobList.filter(r => {
						return r.packingCode === result.data.packingCode && r.itemCode === result.data.itemCode
					})

				} else {
					items = this.putawayjobList.filter(r => {
						return r.containerCode === result.data.containerCode
					})
				}
				return items;
			},

			//获取零件库存
			getBalances(param, result) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});

				if (this.$putawayLocationTypes === undefined || this.$putawayLocationTypes === '') {
					this.showMessage('请在配置文件中配置允许上架的库位类型');
					return;
				}

				//根据配置获取LocationType，
				//天津是从待检库位，状态为待检或者合格，直接上架到原料库位
				//杭州是待检库位，状态为合格，直接上架到原料库位
				param.locationTypes = this.paramLocationType;
				param.inventoryStatus = this.paramInventoryStatus;
				getBalancesByFilter(param)
					.then(res => {
						if (res.totalCount === 0) {
							this.showMessage('在' + this.enableLocationType + '中未找到可上架的库存余额');
						} else {
							if (result.data.isPack) {
								if (res.totalCount > 1) {
									this.$refs.balanceItems.openPopup(res.items);
								} else {
									this.putawayjobList.push(res.items[0])
								}
							} else {
								this.putawayjobList = [...this.putawayjobList, ...res.items];
							}
						}
						uni.hideLoading();
					})
					.catch(err => {
						this.showMessage(err.message);
						uni.hideLoading();
					});
			},

			getSelectedBalance(balanceItem) {
				if (balanceItem.qty.qty <= 0) {
					this.showMessage('库存数量为' + balanceItem.qty.qty + ',不可以上架');
				} else {
					this.putawayjobList.push(balanceItem);
				}
			},

			take() {
				if (this.putawayjobList.length === 0) {
					this.showMessage('请先扫描标签');
				} else {
					let strItemCode = '';
					this.putawayjobList.forEach((item, i) => {
						if (item.qty.qty <= 0) {
							strItemCode += item.itemCode + ','
						}
					});

					if (strItemCode != '') {
						showConfirmMsg(strItemCode + '的库存数量为0,不能创建上架任务,是否要为其它零件创建上架任务?', confirm => {
							if (confirm) {
								this.submit();
							}
						});
					} else {
						this.submit();
					}
				}
			},

			submit() {
				this.submitting = true;
				uni.showLoading({
					title: "提交中..."
				});

				let datas = [];
				this.putawayjobList.forEach((item, i) => {
					if (item.qty.qty > 0) {
						let data = {
							containerCode: item.containerCode,
							packingCode: item.packingCode,
							itemCode: item.itemCode,
							locationCode: item.locationCode,
							inventoryStatus: item.status
						};
						datas.push(data)
					}
				})
				if (datas.length == 0) {
					this.showMessage('没有符合条件的零件')
					this.hideLoading();
					return;
				}

				let params = {
					inventories: datas
				};

				let jsonParams = JSON.stringify(params);
				console.log('params', jsonParams)
				if (this.scanType === '托') {
					byContainercode(jsonParams)
						.then(res => {
							this.afterSubmit(res);
						})
						.catch(err => {
							this.showMessage(err.message);
							this.deleteItem();
							this.hideLoading();
						});

				} else if (this.scanType === '箱') {
					byPackingcode(jsonParams)
						.then(res => {
							this.afterSubmit(res);
						})
						.catch(err => {
							this.showMessage(err.message);
							this.deleteItem();
							this.hideLoading();
						});
				}
			},

			afterSubmit(res) {
				if (res != null && res.length > 0) {
					this.showTakePutawayJob(res);
					this.hideLoading();
				} else {
					this.showMessage('任务创建失败');
					this.hideLoading();
				}
			},

			//要增加异步方法
			showPrintLabel() {
				printPutawayLabel();
			},

			showTakePutawayJob(res) {
				showConfirmMsg('任务创建成功,是否要执行任务?', confirm => {
					//打开执行任务详情页面
					if (confirm) {
						let isPack = this.scanType === '箱' ? true : false;
						uni.navigateTo({
							url: './putaway_detail?id=' + res[0].id +
								'&jobStatus=' + res[0].jobStatus + '&isPack=' +
								isPack
						})
					} else {
						this.deleteItem();
					}
				});
			},

			hideLoading() {
				this.submitting = false;
				uni.hideLoading();
			},

			//清空
			clear() {
				showConfirmMsg('是否要清空已经扫描的零件?', confirm => {
					if (confirm) {
						this.deleteItem();
					}
				});
			},

			deleteItem() {
				this.scanType = null;
				this.putawayjobList = [];
			},

			setScanType(result) {
				if (this.scanType === null || this.scanType === "") {
					this.scanType = result.data.isPack === null ? '' : result.data.isPack ? '箱' : '托';
				}
			},

			resetScanType() {
				if (this.putawayjobList.length === 0) {
					this.scanType = null;
				}
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
		}
	}
</script>

<style>
	.scanType {
		padding: 5rpx 30rpx;
		font-size: 16px;
		color: gray;
	}
</style>
