<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="itemList.length==0"></win-blank-view>
		<view class="top_wrap" v-if="itemList.length>0">
			<view class="top_card">
				<view class="uni-flex space-between top_lines_info">
					<view class="font_sm">
						生产线:
						<text class="text_bold">{{prodLine}}</text>
					</view>
				</view>
			</view>
		</view>

		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-detail" @scrolltoupper="upper"
			@scrolltolower="lower" @scroll="scroll">
			<view class="detail-list margin_top" v-for="(item, index) in itemList" :key="item.id"
				@click="checkItem(item)">
				<view class="detail-content">
					<uni-swipe-action>
						<uni-swipe-action-item :right-options="options" :auto-close="false"
							@click="swipeClick($event,index)">
							<com-product-item :dataContent="item"></com-product-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>
		</scroll-view>
		<view class="new_btn_bot" v-if="itemList.length>0">
			<button class="new_save_btn" @click="submit()">提交</button>
		</view>
		<win-scan-button @goScan='openScanPopup' v-if="itemList.length>0"></win-scan-button>
		<win-scan-by-product ref="scanPopup" @getScanResult='getScanResult'></win-scan-by-product>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getitems,
		getprodlineitem,
		productreceipt,
		PrintServices
	} from '@/api/index.js';
	import {
		showConfirmMsg,
		goHome,
		getRemoveOption,
		getCurrDateTime
	} from '@/common/basic.js';

	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByProduct from '@/mycomponents/wincom/winScanByProduct.vue'
	import comProductItem from '@/mycomponents/coms/comProductItem.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import moment from 'moment'
	export default {
		name: 'receiptbyjob',
		components: {
			winBlankView,
			winScanButton,
			winScanByProduct,
			comProductItem,
			comMessage,
		},
		data() {
			return {
				options: [],
				itemList: [],
				currentItem: {},
				prodLine: '',
				showscanprodLine: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				sacnmsg: '请扫描生产线',
				pageSize: 100,
				pageIndex: 1,
			};
		},
		props: {
			datacontent: {
				type: Object,
				value: null
			}
		},
		mounted() {
			this.options = getRemoveOption();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}else if(e.index === 1){
				window.location.reload();
			}
		},
		methods: {
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup();
			},

			//提示是否移除选择的行?
			swipeClick(e, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.itemList.splice(index, 1);
							}
						}
					});
				}
			},
			print() {
				let params =
					'{"Palletlabel":[{"asnNumber":"AVN202205250002","number":"AVN202205250002","supplierCode":"02053835","supplierName":"埃驰汽车零部件（常熟）有限公司","arriveTime":"2022/05/25","packingCode":"undefined","containerCode":"T0000591","itemCode":"1765049LAA","qty":"200","totalQty":1},{"asnNumber":"AVN202205250002","number":"AVN202205250002","supplierCode":"02053835","supplierName":"埃驰汽车零部件（常熟）有限公司","arriveTime":"2022/05/25","packingCode":"undefined","containerCode":"T0000592","itemCode":"1765049LAA","qty":"200","totalQty":1},{"asnNumber":"AVN202205250002","number":"AVN202205250002","supplierCode":"02053835","supplierName":"埃驰汽车零部件（常熟）有限公司","arriveTime":"2022/05/25","packingCode":"undefined/B0001513/B0001511","containerCode":"T0000591","itemCode":"1765049LAA","qty":"200/200/200","totalQty":3}]}'

				let data = {
					reportName: 'tuopan.rdlx',
					dataUrl: 'ccc',
					jsonData: params
				};
				// data.jsonData = JSON.stringify(data.jsonData)
				PrintServices(data)
					.then(res => {
						window.open('http://dev.cd-top.com:9097' + '/' + res)
					})
					.catch(err => {});

			},

			//处理扫描解析的返回值
			getScanResult(result) {
				let that = this;
				if (result.data.produceDate == null) {
					this.showMessage('无效的日期');
					return;
				}
				if (result.data.prodLine === null || result.data.prodLine === '') {
					this.showMessage('未解析到生产线');
					return;
				}
				let datas = {};
				if (result.data != null) {
					if (this.itemList.length > 0) {

						if (that.prodLine && that.prodLine.length > 0) {
							if (that.prodLine !== result.data.prodLine) {
								this.showMessage('与第一次扫描的生产线不一致,请重新扫描');
								return;
							}
						}

						//按照ERP料号+箱码+批次去重
						let datas = that.itemList.filter(r => {
							return (r.itemCode === result.data.itemCode &&
								r.lot === result.data.lot &&
								r.packingCode === result.data.packingCode)
						});

						if (datas.length > 0) {
							//列表中已经存在
							showConfirmMsg('零件已经存在,是否要重新扫描?', confirm => {
								if (confirm) {
									that.itemList.forEach((r, i) => {
										if (r.itemCode === result.data.itemCode &&
											r.lot === result.data.lot &&
											r.packingCode === result.data.packingCode) {
											that.itemList.splice(i, 1);
											return;
										}
									});
									that.getreceiptitem(result.data);
								}
							});
						} else {
							that.getreceiptitem(result.data);
						}
					} else {
						that.getreceiptitem(result.data);
					}
				} else {
					this.showMessage('标签格式不正确,请重新扫描');
				}
			},

			getreceiptitem(data) {
				let that = this;
				let itemcode = data.itemCode;
				that.getitem(itemcode, item => {
					if (item != null) {
						if (!item.canMake) {
							this.showMessage('零件不是制作件,不能进行完工收货');
						} else {
							let receiptitem = that.createreceiptitem(data, item);
							if (data.prodLine) {
								that.getprodcutline(data.prodLine, lineitem => {
									if (lineitem != null) {
										receiptitem.locationCode = lineitem.locationCode;
										receiptitem.rawLocation = lineitem.rawLocation;

										that.prodLine = data.prodLine;
										that.itemList.push(receiptitem);
									}
								});
							} else //扫描的标签没有生产线
							{
								this.showMessage('扫描的标签没有生产线');
							}
						}
					}
				});
			},

			//创建收货item
			createreceiptitem(data, item) {
				let producedate = moment(data.produceDate).format("YYYY-MM-DD");
				let receiptitem = {
					itemCode: data.itemCode,
					prodLine: data.prodLine,
					lot: data.lot,
					batch: {
						supplierBatch: '',
						produceDate: producedate + "T00:00:00",
					},
					//data.produceDate
					packingCode: data.packingCode,
					containerCode: '',
					warehouseCode: localStorage.warehouseCode,
					qty: {
						uom: data.uom,
						qty: data.qty
					},
					shift: data.shift,
					bomVersion: ''
				};
				let itemcode = data.itemCode;
				receiptitem.item = {
					id: item.id,
					name: item.name,
					desc1: item.desc1,
					desc2: item.desc2
				};
				return receiptitem;
			},

			//获取零件库存
			getitem(itemCode, callback) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				if (itemCode != null) {
					getitems(itemCode)
						.then(res => {
							if (res === null) {
								this.showMessage('未查找到零件');
							} else {
								callback(res);
							}
							uni.hideLoading();
						})
						.catch(err => {
							this.showMessage('未查找到零件');
							uni.hideLoading();
							callback(null);
						});
				}
			},

			getprodcutline(code, callback) {
				if (code != null) {
					getprodlineitem(code)
						.then(res => {
							if (res === null) {
								this.showMessage('未查找到生产线');
							} else {
								let prodcutLine = {
									locationCode: res.productLocation,
									rawLocation: res.rawLocation
								};
								callback(prodcutLine);
							}
							uni.hideLoading();
						})
						.catch(err => {
							this.showMessage('未查找到生产线');
							uni.hideLoading();
							callback(null);
						});
				}
			},

			checkItem(item) {
				item.checked = !item.checked;
			},

			deleteItem() {
				let that = this;
				if (that.itemList.length === 0) {
					this.showMessage('没有要删除的数据')
				} else {
					let checkItems = that.itemList.filter(r => {
						return r.checked;
					})
					if (checkItems.length === 0) {
						this.showMessage('请选择要删除的数据')
					} else {
						showConfirmMsg('是否要将选择的行删除?', confirm => {
							if (confirm) {
								for (var i = that.itemList.length - 1; i >= 0; i--) {
									let item = that.itemList[i];
									if (item.checked) {
										that.itemList.splice(i, 1);
									}
								}
							}
						})
					}
				}
			},

			getQty(value) {
				let qtyValue = Number(value);
				let item = this.currentItem;
				if (qtyValue < 0) {
					this.showMessage('收货数量不能小于');
				} else {
					if (qtyValue > Number(item.qty.qty)) {
						this.showMessage('收货数量 ' + qtyValue + '不能大于库存数量 ' + item.qty.qty);
					} else {
						this.currentItem.handledQty = {
							qty: qtyValue
						}
					}
				}
			},

			//获取生产线
			getProdLineResult(result) {
				let prodLine = '';
				if (result.scanType === 'qrcode') {
					prodLine = result.data.prodLine;
				} else {
					prodLine = result.data.code;
				}
				that.finsh(prodLine);
			},

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					this.showMessage('请先扫描箱标签');
					return;
				}
				if (that.prodLine == "" || that.prodLine.length == null) {
					this.showMessage('扫描的标签没有生产线');
				} else {
					that.finsh(that.prodLine);
				}
			},


			finsh(prodLine) {
				let that = this;
				uni.showLoading({
					title: "提交中..."
				});

				let receiptItem = {
					worker: localStorage.userName_CN ==""?localStorage.userName:localStorage.userName_CN,
					warehouseCode: localStorage.warehouseCode,
					number: "",
					productionPlanNumber: "",
					jobNumber: "",
					completeTime: getCurrDateTime(),
					Company: localStorage.company,
					WorkShop: 'Assemble', //车间
					details: [] //子表
				};
				for (var i = 0; i < that.itemList.length; i++) {
					let r = that.itemList[i];
					let detail = {
						itemCode: r.itemCode,
						item: r.item,
						lot: r.lot,
						batch: r.batch,
						packingCode: r.packingCode,
						containerCode: r.containerCode,
						warehouseCode: localStorage.warehouseCode,
						qty: {
							qty: Number(r.qty.qty),
							uom: r.qty.uom
						},
						locationCode: r.locationCode,
						rawLocation: r.rawLocation,
						shift: r.shift,
						prodLine: r.prodLine,
						status: 2,
						worker: localStorage.userName_CN ==""?localStorage.userName:localStorage.userName_CN,
						// bomVersion: r.bomVersion
					};
					receiptItem.details[i] = detail;
				}

				let params = JSON.stringify(receiptItem);
				console.log('param', params);
				productreceipt(params)
					.then(res => {
						this.showMessage('提交成功')
						that.clearItems();
						that.hideLoading();
					})
					.catch(err => {
						this.showMessage(err.message)
						that.hideLoading();
					});
			},
			hideLoading() {
				uni.hideLoading();
			},
			clearItems() {
				let that = this;
				that.itemList = [];
				that.prodLine = '';
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},

			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				// console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop;
			},
		}
	};
</script>

<style scoped lang="scss">
	@import '../../common/pdabasic.css';
</style>
