<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="itemList.length==0"></win-blank-view>

		<uni-data-picker v-if="itemList.length>0" style="padding: 20rpx; background-color:#fff;" class='uni-data-picker'
			placeholder="请选择原因" popup-title="报废原因" :localdata="scrapReasonArray" v-model="scrapReason">
		</uni-data-picker>

		<scroll-view scroll-y="true" class="scroll-Y">
			<view class="detail-list margin_top" v-for="(item, index) in itemList">
				<uni-swipe-action>
					<uni-swipe-action-item :right-options="options2" :auto-close="false"
						@click="removeClick($event,index)">
						<com-balance-item :dataContent='item'></com-balance-item>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</scroll-view>

		<div class="new_bot_box" v-show="itemList.length>0">
			<win-collapse-location v-if="isScanLocation" @getLocationCode='getToLocation' @clear='clear'>
			</win-collapse-location>
			<view class="new_btn_bot bot_pos uni-flex">
				<button class="new_clear_btn btn_double" @click="cancel()">清空</button>
				<button class="new_save_btn btn_double" @click="submit()">提交</button>
			</view>
		</div>

		<win-scan-button @goScan='openScanPopup' v-if="itemList.length>0"></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult'></win-scan-by-pack>

		<com-message ref="comMessage" @afterCloseScanMessage='closeScanMessage' @afterRescanMessage='afterRescan'
			@afterCloseCommitMessage='closeCommitMessage'></com-message>
		<com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
	</view>
</template>

<script>
	import {
		getBalancesByFilter,
		scrap,
		locationByType,
		locations,
		getDictByCode
	} from '@/api/index.js';
	import {
		showConfirmMsg,
		goHome,
		getRemoveOption
	} from '@/common/basic.js';
	import VUE from 'vue'
	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import dyItemInfo from '@/mycomponents/dycom/dyItemInfo.vue';
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import comBalanceItem from '@/mycomponents/comItem/comBalanceItem.vue'
	import winCollapseLocation from '@/mycomponents/wincom/winCollapseLocation.vue'

	export default {
		name: 'scrap',
		components: {
			winBlankView,
			winScanButton,
			winScanByPack,
			comBalance,
			comMessage,
			comBalanceItem,
			winCollapseLocation
		},
		data() {
			return {
				options2: [],
				itemList: [],
				scrapReason: "",
				scrapReasonArray: [],
				toLocationCode: '',
				toLocationErpCode: '',
				isScanLocation: false,
				currentLabel: null,
			};
		},
		mounted: function() {
			this.options = getRemoveOption();
		},

		onLoad() {

		},

		onShow() {
			if (this.$isScrapScanToLocation) {
				this.isScanLocation = this.$isScrapScanToLocation;
			}
		},

		onReady() {
			this.getScarpReason();
			this.openScanPopup();
		},

		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		filters: {
			statusStyle: function(val) {
				return getJobStatuStyle(val);
			},
			statusColor: function(val) {
				return getJobStatuDesc(val);
			},

		},
		methods: {

			//扫描箱标签	
			getScanResult(result) {
				let code = result.data.code;
				if (code == '') return;
				this.currentLabel = result.data;
				let items = this.itemList.filter(r => {
					return r.packingCode === code
				})

				if (items.length > 0) {
					this.showRescanMessage('箱码【' + code + '】已经存在,是否要重新扫描?');
					// showConfirmMsg('箱码【' + code + '】已经存在,是否要重新扫描?', confirm => {
					// 	if (confirm) {
					// 		this.itemList.forEach((r, i) => {
					// 			if (r.packingCode == code) {
					// 				this.itemList.splice(i, 1);
					// 				return;
					// 			}
					// 		});
					// 		this.getBalances()
					// 	} else {
					// 		this.scanPopupGetFocus();
					// 	}
					// })
				} else {
					this.getBalances()
				}
			},

			afterRescan(confirm) {
				let that = this;
				if (confirm) {
					this.itemList.forEach((r, i) => {
						if (r.packingCode == this.currentLabel.packingCode) {
							this.itemList.splice(i, 1);
							return;
						}
					});
					this.getBalances()
				} else {
					this.scanPopupGetFocus();
				}
			},

			getBalances() {
				let that = this;
				let code = this.currentLabel.packingCode;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				let params = {
					pageSize: 1000,
					pageIndex: 1,
					packingCode: code,
					locationTypes: [2] //原材料
				};
				getBalancesByFilter(params).then(res => {
					if (res.totalCount == 0) {
						this.showScanMessage('箱码【' + code + '】在【原料库】未查询到库存信息');
					} else if (res.totalCount == 1) {
						let balanceItem = res.items[0];
						that.getLocationInfo();
						let item = this.createItem(balanceItem);
						that.itemList.unshift(item)
						that.scanPopupGetFocus();
					} else {
						this.$refs.balanceItems.openPopup(res.items);
					}
					uni.hideLoading();
				}).catch(ex => {
					uni.hideLoading();
					that.showMessage(ex.message);
				});
			},

			selectedBalanceItem(balanceItem) {
				let item = this.createItem(balanceItem);
				this.itemList.unshift(item)
				this.getLocationInfo();
			},

			createItem(item) {
				item.remark = item.remrak;
				item.itemCode = item.itemCode
				item.itemName = item.itemName;
				item.itemDesc1 = item.itemDesc1;
				item.itemDesc2 = item.itemDesc2;
				item.uom = item.uom;
				item.qty = item.qty;
				// item.stdPackUom = 
				// item.stdPackQty = 
				item.fromPackingCode = item.packingCode;
				item.toPackingCode = item.packingCode;
				item.fromContainerCode = item.containerCode;
				item.toContainerCode = item.containerCode;
				item.fromLot = item.lot;
				item.toLot = item.lot;
				item.supplierBatch = item.supplierBatch;
				item.arriveDate = item.arriveDate;
				item.produceDate = item.produceDate;
				item.expireDate = item.expireDate;
				item.fromLocationCode = item.locationCode;
				item.fromLocationGroup = item.locationGroup;
				item.fromLocationArea = item.locationArea;
				item.fromLocationErpCode = item.locationErpCode;
				item.fromWarehouseCode = localStorage.warehouseCode;
				item.toLocationCode = item.locationCode;
				item.toLocationGroup = item.locationGroup;
				item.toLocationArea = item.locationArea;
				item.toLocationErpCode = item.locationErpCode;
				item.toWarehouseCode = localStorage.warehouseCode;
				item.fromStatus = item.status;
				item.toStatus = item.status;
				item.reasonCode = this.scrapReason;
				return item;
			},

			getLocationInfo() {
				if (!this.isScanLocation) {
					let that = this;
					//扫描库位type
					var type = [6];
					locationByType(type).then(res => {
						if (res && res.length > 0) {
							that.toLocationCode = res[0].code;
							that.toLocationErpCode = res[0].erpLocationCode;
						} else {
							that.toLocationCode = '';
							that.toLocationErpCode = '';
						}
					}).catch(error => {})
				}
			},

			getToLocation(code) {
				if (code == '') {
					this.showMessage('目标库位不能为空');
					return;
				}
				uni.showLoading({
					title: "扫描中",
					mask: true
				});
				let that = this;
				locations(code).then(res => {
					if (res) {
						that.toLocationCode = res.code;
						that.toLocationErpCode = res.erpLocationCode;
					} else {
						that.toLocationCode = '';
						that.toLocationErpCode = '';
						that.showMessage('目标库位不存在');
					}
					uni.hideLoading();
				}).catch(err => {
					that.toLocationCode = '';
					that.toLocationErpCode = '';
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

			clear() {
				this.toLocationCode = '';
				this.toLocationErpCode = "";
			},

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

			qtyInput(value, item) {
				if (value == '') {
					// setTimeout(() => {
					// 	item.qty = 0;
					// }, 10)
				} else {
					let qtyValue = Number(value);
					if (qtyValue < 0) {
						this.showMessage('数量不能小于0');
						setTimeout(() => {
							item.qty = 0;
						}, 10)
					} else if (value > item.defaultQty) {
						this.showMessage('数量不能大于[' + item.defaultQty + ']');
						setTimeout(() => {
							item.qty = item.defaultQty;
						}, 10)
					}
				}
			},

			//提交
			submit() {
				if (this.itemList.length == 0) {
					this.showMessage('请扫描箱标签')
				}
				if (this.isScanLocation && this.toLocationCode === '') {
					this.showMessage('请扫描目标库位');
					return;
				}
				if (!this.scrapReason) {
					this.showMessage('请选择报废原因');
					return;
				}

				showConfirmMsg('确认对以上物品进行报废?', confirm => {
					if (confirm) {
						this.scrapFunc();
					}
				});
			},

			scrapFunc() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				let that = this;
				let item = {
					worker: localStorage.userName,
					warehouseCode: localStorage.warehouseCode,
					company: localStorage.company,
					jobNumber: "",
					number: "",
					scrapRequestNumber: "",
					type: "Scrap_Manual",
					details: []
				}

				that.itemList.forEach(r => {
					r.toLocationCode = that.toLocationCode
					r.toLocationErpCode = that.toLocationErpCode
					r.worker = localStorage.userName
					r.reasonCode = this.scrapReason
					item.details.push(r);
				})

				let params = JSON.stringify(item);
				console.log('params', params);
				scrap(params)
					.then(res => {
						that.showCommitSuccess();
						that.clearAll();
						uni.hideLoading();
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			cancel() {
				let that = this;
				showConfirmMsg('是否要清空已扫描的零件信息?', confirm => {
					if (confirm) {
						that.clearAll();
					}
				})
			},

			clearAll() {
				this.itemList = [];
				this.toLocationCode = '';
				this.toLocationErpCode = "";
			},

			getScarpReason() {
				let that = this;
				let scrapReason = VUE.prototype.$scrapReason;
				if (!scrapReason) {
					that.showMessage("请在配置文件中配置报废原因[scrapReason]");
				} else {
					uni.showLoading({
						title: "加载中....",
						mask: true
					});
					getDictByCode(scrapReason).then(res => {
						uni.hideLoading();
						if (res && res.items && res.items.length > 0) {
							res.items.forEach(res => {
								res.text = res.name;
								res.value = res.code;
							})
							that.scrapReasonArray = res.items;
						} else {
							that.scrapReasonArray = [];
							that.showMessage('报废原因为空,请在字典中添加字典编号为[scrapReason]的报废原因');
						}
					}).catch(error => {
						uni.hideLoading();
						that.showMessage(error.message);
					});
				}
			},

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

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

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

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

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

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

			closeCommitMessage() {
				this.openScanPopup();
			}
		},
	}
</script>

<style scoped lang="scss">
</style>
