<template>
	<view class="p-content">
		<view class="p-head" v-if="baseData">
			<view>
				<view>
					<text>采购单号：</text>
					<text style="color: crimson;">{{baseData[0].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[0].sendBillNo}}</text>
				</view>
			</view>
			<view>
				<view>
					<text>条码：</text>
					<view>
						<input
						@blur="addQty(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-for="(item,bindex) in baseData" :key="item.id">
				<view>总款数:{{ item.totalPutCategory }}</view>
				<view>发货数量: {{ item.totalPutQty }}</view>
				<view>发货金额: {{ item.totalPutAmount?toThousands(item.totalPutAmount,2):'0.00' }}</view>
				<view>入库数量: {{ item && (item.totalRealPutQty || item.totalRealPutQty==0) ? item.totalRealPutQty : '--' }}</view>
				<view>入库金额: {{ item && (item.totalRealPutAmount || item.totalRealPutAmount==0) ? toThousands(item.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="curProduct&&curProduct.dealerProductEntity&&curProduct.dealerProductEntity.code == item.dealerProductEntity.code"
				 @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="addQty(false)"> <text class="iconfont icon-reduce-btn"> 减 </text></button>
			<button size="mini" type="primary" @click="addQty(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="curProduct">
					<view style="padding: 30rpx 0;">
						产品编码：{{curProduct.dealerProductEntity.code}}
					</view>
					<view style="display: flex;align-items: center;">
						数量：
						<u--input
						    placeholder="请输入数量"
						    border="surround"
						    v-model="curProduct.packQty"
							:min="0"
							type="digit"
						  ></u--input>
						  {{curProduct.dealerProductEntity.unit}}
						  {{curProduct.dealerProductEntity.packQtyUnit?("/"+curProduct.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,
				curProduct: 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||''
			  if(_this.keyName == 'rightKey' || _this.keyName == 'midKey'){
				  _this.addQty(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: '编码已复制成功'
				})
			},
			closePop(){
				this.$refs.popup.close()
			},
			okPop(){
				if(this.curProduct.packQty){
					this.changePutQty(this.curProduct,Number(this.curProduct.realPutQty||0) + Number(this.curProduct.packQty))
					this.closePop()
				}else{
					uni.$u.toast("请输入数量！")
					playAudio('warn')
				}
			},
			keyDown(e){
				this.keyName = e
			},
			// 确定选择仓库
			confirmWarehouse(data){
				console.log(data)
				this.updateWarehouse({id:this.curProduct.id,warehouseSn:data[0],warehouseLocationSn:data[1]})
			},
			// 修改仓库
			editRow(item){
				this.warehouseVal = item.warehouseSn ? [item.warehouseSn,item.warehouseLocationSn] : this.defWarehouse
				this.showPick = true
				this.curProduct = item
			},
			// 获取当前操作行
			getCurRow(){
				const curProduct = this.detailList.find(item => item.dealerProductEntity&&item.dealerProductEntity.qrCode == this.code)
				this.curProduct = curProduct || null
				if(curProduct){
					this.curProduct.packQty = this.curProduct.dealerProductEntity&&this.curProduct.dealerProductEntity.packQty || 0
				}
				return curProduct
			},
			// 修改仓库
			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
			  })
			},
			// 修改入库数量
			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')
			  }
			},
			//拣货
			addQty(flag){
				if(this.code==''){
					uni.$u.toast("请扫描或输入条形码")
					playAudio('warn')
					return
				}
				const row = this.getCurRow()
				if(row){
					this.changePutQty(row,(row.realPutQty||0) + (flag?1:-1))
				}else{
					uni.$u.toast("此商品不存在")
					playAudio('error')
				}
			},
			// 详情
			getDetail(){
				receivingQuery({receivingBillSn: this.receivingBillSn}).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(){
				const curProduct = this.getCurRow()
				if(curProduct){
					this.$refs.popup.open()
				}else{
					uni.$u.toast("此商品不存在")
					playAudio('error')
				}
			},
			// 入库
			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[0].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>
