<template>
	<view class="p-content">
		<view class="p-head" v-if="baseData">
			<view>
				<view>
					<text>采购单号：</text>
					<text style="color: crimson;">{{baseData.purchaseBillNo}}</text>
				</view>
				<view>
					<button :disabled="loading" size="mini" type="primary" @click="toOut"> 入库 <text class="iconfont icon-icon-test43"></text></button>
				</view>
			</view>
			<view>
				<view>
					<text>发货单号：</text>
					<text style="color: crimson;">{{baseData.sendBillNo}}</text>
				</view>
			</view>
			<view>
				<view>
					<text>条码：</text>
					<view>
						<input
						@blur="pickFun(true)"
						style="width: 100%;text-align: left;" 
						class="uni-input" 
						placeholder="扫描或输入条码" 
						border="surround" 
						v-model="code">
					</view>
				</view>
			</view>
			<view style="justify-content: flex-start;flex-wrap: wrap;"  v-if="baseData">
				<view>总款数:{{ baseData.totalPutCategory }}</view>
				<view>发货数量: {{ baseData.totalPutQty }}</view>
				<view>发货金额: {{ baseData.totalPutAmount?toThousands(baseData.totalPutAmount,2):'0.00' }}</view>
				<view>入库数量: {{ baseData && (baseData.totalRealPutQty || baseData.totalRealPutQty==0) ? baseData.totalRealPutQty : '--' }}</view>
				<view>入库金额: {{ baseData && (baseData.totalRealPutAmount || baseData.totalRealPutAmount==0) ? toThousands(baseData.totalRealPutAmount, 2) : '--' }}</view>
			</view>
		</view>
		<view class="p-body">
			<uni-table style="width: 100%;" border emptyText="暂无数据" :loading="loading" >
				<!-- 表头行 -->
				<uni-tr>
					<uni-td align="center">产品编码</uni-td>
					<uni-td align="center">仓库仓位</uni-td>
					<uni-td align="center">入库/发货数量</uni-td>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr 
				v-for="item in detailList" 
				:key="item.id" 
				:checkedRow="hasCheck(item)"
				 @click="editRow(item)"
				>
					<uni-td width="30%" align="center">
						<view>{{item.dealerProductEntity&&item.dealerProductEntity.code||'--'}}</view>
					</uni-td>
					<uni-td width="30%" align="center">
						<view>
							<view>{{item.warehouseEntity&&item.warehouseEntity.name||defWarehouseName[0]}}/</view>
							<view>{{item.warehouseLocationEntity&&item.warehouseLocationEntity.name||defWarehouseName[1]}}</view>
						</view>
					</uni-td>
					<uni-td width="40%" align="center"><text style="color: red;">{{item.realPutQty||'0'}}</text>/{{item.putQty}}</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<view class="p-footer">
			<button size="mini" type="warn" @click="pickFun(false)"> <text class="iconfont icon-reduce-btn"> 减 </text></button>
			<button size="mini" type="primary" @click="pickFun(true)"> <text class="iconfont icon-add-btn"> 加 </text></button>
		</view>
		<scanCode @onKeyDown="keyDown"></scanCode>
		 <!-- 选择仓库 -->
		<chooseWarehouse ref="chooseWarehouse" :openPick="showPick" :value="warehouseVal" @close="showPick=false" @change="confirmWarehouse"></chooseWarehouse>
		<!-- 左键扫描，修改包装数 -->
		<uni-popup ref="popup" :mask-click="false" type="dialog">
			<view style="background-color: #fff;padding: 30rpx 50rpx;border-radius: 30rpx;width: 75%;margin: 0 auto;">
				<view v-if="tempProduct">
					<view style="padding: 30rpx 0;">
						产品编码：{{tempProduct.dealerProductEntity.code}}
					</view>
					<view style="display: flex;align-items: center;">
						数量：
						<u--input
						    placeholder="请输入数量"
						    border="surround"
						    v-model="tempProduct.packQty"
							:min="0"
							type="digit"
						  ></u--input>
						  {{tempProduct.dealerProductEntity.unit}}
						  {{tempProduct.dealerProductEntity.packQtyUnit?("/"+tempProduct.dealerProductEntity.packQtyUnit):''}}
					</view>
				</view>
				<view style="display: flex;padding: 60rpx 15rpx 10rpx;justify-content: space-between;">
					<button size="mini" @click="closePop">取消</button>
					<button size="mini" type="primary" @click="okPop">确定</button>
				</view>
			</view>
		</uni-popup>
		
		<u-modal :show="showModal" :title="msg.title" :confirmText="msg.confirmText" showCancelButton :content='msg.content' @cancel="showModal=false" @confirm="confirmModal"></u-modal>
	</view>
</template>

<script>
	import scanCode from '@/libs/scan-code.vue';
	import { purchaseWriteStockIn, receivingQuery, receivingDetail, purchaseUpdateWarehouse, updateRealPutQty, receivingStockInVerify } from '@/config/api.js'
	import { playAudio, toThousands } from '@/libs/tools.js'
	import clipboard from "@/js_sdk/dc-clipboard/clipboard.js"
	import chooseWarehouse from './chooseWarehouse.vue'
	export default {
		components: { scanCode, chooseWarehouse },
		data() {
			return {
				loading: false,
				showModal: false,
				msg:{title:'提示',content:''},
				showPick: false,
				baseData: null,
				detailList:[],
				code:'',
				receivingBillSn: null,
				salesId: null,
				curProductIndex: 0,
				curProductArr: [],
				tempProduct:null,
				toThousands,
				defWarehouse: [],
				defWarehouseName:[],
				keyName: '',
				warehouseVal: []
			};
		},
		onLoad(opts) {
		  var _this = this
		  this.receivingBillSn = opts.receivingBillSn
		  this.salesId = opts.id
		  // 默认仓库仓位
		  this.defWarehouse = this.$store.state.vuex_tempData
		  
		  // 调用数据
		  this.getDetail()
		  this.getDetailList()
		  
		  uni.$on('scancodedate', function(content) {
			  console.log("扫描到的内容为:", content, _this.keyName)
			  _this.code = content||''
			  _this.curProductIndex = 0
			  if(_this.keyName == 'rightKey' || _this.keyName == 'midKey'){
				  _this.pickFun(true)
			  }
			  if(_this.keyName == 'leftKey'){
				_this.openPack()
			  }
		  })
		},
		onShow() {
			this.hideKeyborder()
			const list = this.$store.state.vuex_warehouseList
			const an =list.find(item => item.warehouseSn==this.defWarehouse[0])
			const cn = an&&an.warehouseLocationList&&an.warehouseLocationList.find(item => item.warehouseLocationSn == this.defWarehouse[1])
			this.defWarehouseName = [an&&an.name,cn&&cn.name]
			console.log(this.defWarehouseName)
		},
		onUnload() {
			uni.$off('scancodedate')
		},
		methods: {
			hideKeyborder(){
				uni.hideKeyboard()
			},
			// 复制
			copyText(text){
				clipboard.setText(text);
				uni.showToast({
					icon: 'none',
					title: '编码已复制成功'
				})
			},
			hasCheck(item){
				const curProduct = this.curProductArr[this.curProductIndex]
				return curProduct&&curProduct.id == item.id
			},
			// 获取所有可操作商品
			getCurProduct(){
				const curProduct = this.detailList.filter(item => item.dealerProductEntity&&item.dealerProductEntity.qrCode == this.code)
				this.curProductArr = curProduct || []
			},
			// 获取当前操作行
			getCurRow(){
				console.log(this.curProductArr, this.curProductIndex)
				const curProduct = this.curProductArr[this.curProductIndex]
				if(curProduct){
					curProduct.packQty = curProduct.dealerProductEntity&&curProduct.dealerProductEntity.packQty || 0
				}
				return curProduct
			},
			pickFun(flag){
				playAudio('info')
				this.getCurProduct()
				this.addQty(flag)
			},
			addQty(flag){
				const curProduct = this.getCurRow()
				// console.log(curProduct)
				if(curProduct){
					this.loading = true
					// 加
					if(flag){
						// 如果入库数量与发货数量不相等
						if(curProduct.realPutQty != curProduct.putQty){
							this.changePutQty(curProduct,(curProduct.realPutQty||0) + 1)
						}else{
							// 当前入库数量与发货数量相等时
							// 切换到下一个商品
							if(this.curProductIndex<this.curProductArr.length-1){
								this.curProductIndex = this.curProductIndex + 1
								this.pickFun(flag)
							}else{
								// 直到最后一条数据，扫描数量无上线增加
								this.changePutQty(curProduct,(curProduct.realPutQty||0) + 1)
							}
						}
					}else{
						// 减
						// 如果入库数量不是0
						if(curProduct.realPutQty != 0){
							this.changePutQty(curProduct,(curProduct.realPutQty||0) - 1)
						}else{
							// 入库数量等于0
							// 切换到上一个商品
							if(this.curProductIndex){
								this.curProductIndex = this.curProductIndex - 1
								this.pickFun(flag)
							}else{
								this.loading = false
								playAudio('warn')
							}
						}
					}
				}else{
					this.curProductIndex = 0
					if(this.code == ''){
						uni.$u.toast("请扫描条形码")
						playAudio('warn')
					}else{
						uni.$u.toast("此商品不存在")
						playAudio('error')
					}
				}
			},
			// 关闭弹框 
			closePop(){
				this.$refs.popup.close()
			},
			okPop(){
				const curProduct = this.getCurRow()
				if(curProduct.packQty){
					this.changePutQty(curProduct,Number(curProduct.realPutQty||0) + Number(curProduct.packQty))
					this.closePop()
				}else{
					uni.$u.toast("请输入数量！")
					playAudio('warn')
				}
			},
			// 修改入库数量
			changePutQty(record, realPutQty){
			  if(realPutQty>=0){
				  this.loading = true
				  updateRealPutQty({id:record.id,realPutQty:realPutQty}).then(res => {
					if(res.status == 200){
					  uni.$u.toast(res.message)
					  this.getDetail()
					  this.getDetailList()
					} 
					this.loading = false
				  })
			  }else{
				  uni.$u.toast("入库数量不能小于0")
				  playAudio('warn')
			  }
			},
			keyDown(e){
				this.keyName = e
			},
			// 确定选择仓库
			confirmWarehouse(data){
				console.log(data)
				const curProduct = this.tempProduct
				this.updateWarehouse({id:curProduct.id,warehouseSn:data[0],warehouseLocationSn:data[1]})
			},
			// 修改仓库
			editRow(item){
				this.warehouseVal = item.warehouseSn ? [item.warehouseSn,item.warehouseLocationSn] : this.defWarehouse
				this.showPick = true
				this.tempProduct = item
			},
			// 修改仓库
			updateWarehouse (row) {
			  console.log(row)
			  this.loading = true
			  purchaseUpdateWarehouse({
				id: row.id,
				warehouseSn: row.warehouseSn,
				warehouseLocationSn: row.warehouseLocationSn
			  }).then(res => {
				if (res.status == 200) {
				  this.showPick = false
				  this.getDetailList()
				}
				this.loading = false
			  })
			},
			
			// 详情
			getDetail(){
				receivingQuery({receivingBillSn: this.receivingBillSn, source : "PDA"}).then(res => {
					console.log(res,'详情')
					if(res.status == 200){
						this.baseData = res.data
					}
				})
			},
			// 产品明细列表
			getDetailList(){
				receivingDetail({pageNo:1,pageSize:1000,receivingBillSn:this.receivingBillSn}).then(res => {
					console.log(res,'明细列表')
					if(res.status == 200){
						this.detailList = res.data.list
						this.getCurRow()
					}
				})
			},
			// 打开包装数弹框
			openPack(){
				this.getCurProduct()
				const curProduct = this.getCurRow()
				this.tempProduct = curProduct
				if(curProduct.realPutQty < curProduct.putQty){
					this.$refs.popup.open()
				}else{
					// 切换到下一个商品
					if(this.curProductIndex<this.curProductArr.length-1){
						this.curProductIndex = this.curProductIndex + 1
						this.openPack()
					}else{
						// 直到最后一条数据，扫描数量无上线增加
						this.$refs.popup.open()
					}
				}
			},
			// 入库
			async toOut(){
				const isOk = await receivingStockInVerify({receivingBillSn:this.receivingBillSn})
				if(!isOk.data){
					this.submitForm()
				}else{
					this.showModal = true
					this.msg = {
						title: '提示',
						content: '有产品入库数量与发货数量不一致，确定入库？',
						confirmText: '确定'
					}
				}
			},
			confirmModal(e){
				this.submitForm()
			},
			async submitForm(){
				const a = this.defWarehouse
				const ret = await purchaseWriteStockIn({id: this.baseData.id,warehouseSn:a[0], warehouseLocationSn:a[1]})
				if(ret.status == 200){
					this.$store.state.vuex_isRefash = true
					uni.navigateBack()
				}
				this.showModal = false
			}
		},
	}
</script>

<style lang="scss">
	.p-content{
		.p-head{
			font-size: 32upx;
			color: $uni-text-color;
			>view{
				display: flex;
				align-items: center;
				padding: 10upx 20upx;
				border-bottom: 1px solid #eee;
				justify-content: space-between;
				> view{
					display: flex;
					padding: 0 10upx;
					align-items: center;
				}
			}
			.uni-input{
				border: 1px solid #eee;
				width: 150upx;
				text-align: center;
				padding: 8upx;
			}
		}
		.p-body{
			overflow: auto;
			flex-grow: 1;
			height: 50%;
		}
		.p-footer{
			padding:30upx;
			display: flex;
			> button{
				width: 40%;
			}
		}
	}
</style>
