<template>
	<view>
	<view class="p-content">
		<view class="p-head">
			<view v-if="baseData">
				<view>
					<text>散件单号：</text>
					<text style="color: crimson;">{{baseData.sparePartsPurchaseNo}}</text>
				</view>
				<view>
					<button size="mini" :disabled="loading" type="warn" @click="submitInStock"> 入库 <text class="iconfont icon-icon-test43"></text></button>
				</view>
			</view>
			<view>
				<view>
					<text>产品条码：</text>
					<view style="flex-grow: 1;display: flex;align-items: center;">
						<input 
						style="width: 150px;text-align: left;font-size: 32rpx;padding: 6rpx 0 6rpx 7rpx;" 
						class="uni-input" 
						placeholder="扫描或输入条码" 
						border="surround" 
						v-model="code">
					</view>
				</view>
				<view style="display: flex;align-items: center;">
					<button size="mini" @click="queryProduct" :style="{padding:'2px 3px',color:'#00aaff'}">查询</button>
					<button size="mini" @click="resetForm" :style="{padding:'2px 3px',color:'#aa0000',margin:'0 0 0 5px'}">重置</button>
				</view>
			</view>
			<view v-if="curProduct">
				<view>
					<text style="width:180rpx">产品名称：</text>
					<view>
						 {{curProduct.productName}}
					</view>
				</view>
			</view>
			<view v-if="curProduct">
				<view>数量：<input class="uni-input" v-model="curProduct.putQty" :min="0" @blur="updateCurr" type="digit"/></view>
				<view>成本：<input class="uni-input" v-model="curProduct.putCost" :min="0" @blur="updateCurr" type="digit"/></view>
			</view>
			<view v-if="countData" style="justify-content: flex-start;flex-wrap: wrap;">
				<view>总款数：{{countData.productTotalCategory||0}}</view>
				<view>总数量：{{countData.productTotalQty||0}}</view>
				<view>
					总成本：<u-text type="error" mode="price" :text="countData.productTotalCost" />
				</view>
			</view>
		</view>
		<view class="p-body" :style="{height: curProduct ? 'calc(100vh - 250px)':'calc(100vh - 180px)'}">
			<scroll-view :scroll-top="scrollTop" :scroll-y="true" class="scrollView">
				<uni-table 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.qrCode == item.qrCode" @click="selRow(item)">
						<uni-td width="40%" align="center">{{item.productCode}}</uni-td>
						<uni-td width="30%" align="center">{{item.putQty}}</uni-td>
						<uni-td width="30%" align="center">
							<view @click="toDetail(item)"><span :style="{ color: 'red' }">￥{{Number(item.putCost*item.putQty).toFixed(2)}}</span></view>
						</uni-td>
					</uni-tr>
				</uni-table>
			</scroll-view>
		</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>
	</view>
	<scanCode></scanCode>
	<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>
					产品编码：{{tempProduct.code}}
				</view>
				<view>
					产品名称：{{tempProduct.name}}
				</view>
				<view style="display: flex;align-items: center;">
					成本价：
					<u--input
					    placeholder="请输入成本价"
					    border="surround"
					    v-model="tempProduct.putCost"
						:min="0"
						type="digit"
					  ></u--input>
				</view>
			</view>
			<view style="display: flex;padding: 30rpx 15rpx;justify-content: space-between;">
				<button @click="closePop">取消</button>
				<button type="primary" @click="okPop">确定</button>
			</view>
		</view>
	</uni-popup>
	</view>
</template>

<script>
	import {
		sparePartsPurDetail, 
		dealerProductQueryForSparePartsPur,
		sparePartsPurDetailList, 
		sparePartsQueryCount,
		sparePartsPurDetailSave,
		sparePartsPurDetailDel, 
		sparePartsPurDetailDelAll, 
		sparePartsPurSubmitPut,
	} from '@/config/api.js'
    import scanCode from '@/libs/scan-code.vue';
	import { playAudio } from '@/libs/tools.js'
	export default {
		components: { scanCode },
		data() {
			return {
				loading: false,
				baseData: null,
				detailList:[],
				countData:null,
				code:'',
				sparePartsPurchaseSn: '',
				sparePartsPurchaseId: '',
				curProduct: null,
				defaultWarehouseCascade: [] ,// 默认仓库仓位
				tempProduct: null,
				scrollTop: 0
			};
		},
		onLoad(opts) {
		  var _this = this
		  this.sparePartsPurchaseSn = opts.sn
		  this.sparePartsPurchaseId = opts.id
		  this.getWarehouseCascade()
		  this.getDetail()
		  this.pageInit()
		  
		  uni.$on('scancodedate', function(content) {
			  console.log("扫描到的内容为:", content)
			  _this.code = content||''
			  _this.queryProduct()
		  })
		  
		},
		onShow() {
			this.pageInit()
			this.hideKeyborder()
		},
		onUnload() {
			uni.$off('scancodedate')
		},
		onNavigationBarButtonTap(e){
			if(e.index == 0){
				uni.navigateTo({
					url: "/pages/stockIn/list"
				})
			}
		},
		methods: {
			closePop(){
				this.$refs.popup.close()
			},
			okPop(){
				if(this.tempProduct.putCost || this.tempProduct.putCost === 0){
					this.closePop()
					this.addDetailProduct(this.tempProduct, false)
				}else{
					uni.$u.toast("请输入成本价！")
				}
			},
			pageInit(){
				this.getTotal()
				this.getDetailList()
			},
			//  仓库仓位  级联  列表
			getWarehouseCascade () {
			  const _this = this
			  const warehouseList = this.$store.state.vuex_warehouseList
			  warehouseList.filter(item => {
				// 过滤默认仓库
				if (item.defaultFlag == 1 && item.wasteFlag == 0) { //  defaultFlag为1,且不是废品仓
				  _this.defaultWarehouseCascade[0] = item.warehouseSn
				  // 过滤默认仓位
				  item.warehouseLocationList.filter(subItem => {
					if (subItem.defaultFlag == 1 && subItem.wasteFlag == 0) {
					  _this.defaultWarehouseCascade[1] = subItem.warehouseLocationSn
					}
				  })
				}
			  })
			},
			hideKeyborder(){
				uni.hideKeyboard()
			},
			// 修改数量和成本
			updateCurr(){
				if(this.curProduct.putQty>0){
					if(this.curProduct.putCost>0){
						this.addDetailProduct(this.curProduct, true)
					}else{
						uni.$u.toast("成本必须大于0！")
						this.curProduct.putCost = this.curProduct.putCostBackups
					}
				}else{
					// 删除
					this.delDetailProduct(this.curProduct)
				}
			},
			// 加减数量
			addQty(type){
				playAudio('info')
				const hasProduct = this.detailList.find(item => item.qrCode == this.code)
				if(hasProduct){
				  hasProduct.putQty = hasProduct.putQty + (type ? 1 : -1)
				  if(hasProduct.putQty>0){
					  this.addDetailProduct(hasProduct, true)
				  }else{
					  // 删除
					  this.delDetailProduct(hasProduct)
				  }
				}
			},
			// 删除
			delDetailProduct(item) {
			   sparePartsPurDetailDel({ sn: item.id }).then(res => {
				 if (res.status == 200) {
				   uni.$u.toast(res.message)
				   this.pageInit()
				 }
			   })
			},
			// 查询产品
			queryProduct(){
				if(!this.code){
					uni.$u.toast("请扫码或输入条形码！")
					return
				}
				// 如果已添加产品，则累加数量
				const hasProduct = this.detailList.find(item => item.qrCode == this.code)
				console.log(hasProduct)
				if(!!hasProduct){
				  this.addQty(true)
				  return
				}
				if(this.code==''){
				  uni.$u.toast("未识别到条形码！")
				  playAudio('error')
				  return
				}
				const params = { 
					supplierSn: this.baseData.supplierSn, 
					qrCode: this.code, 
					pageNo:1, 
					pageSize:1 ,
				}
				console.log(params)
				dealerProductQueryForSparePartsPur(params).then(res => {
					console.log(res)
					if(res.status == 200){
						const curProduct = res.data && res.data.list[0] || null
						console.log(curProduct)
						if(curProduct){
							curProduct.putCost = curProduct.purchasePrice
							curProduct.putQty = curProduct.putQty || 1
							if (this.defaultWarehouseCascade.length > 0) {
							  curProduct.warehouseSn = this.defaultWarehouseCascade[0]
							  curProduct.warehouseLocationSn = this.defaultWarehouseCascade[1]
							} else {
							  curProduct.warehouseSn = undefined
							  curProduct.warehouseLocationSn = undefined
							}
							// 添加产品
							this.addDetailProduct(curProduct, false)
						}else{
							 uni.$u.toast("此商品不存在！")
							 playAudio('error')
						}
					}
				})
			},
			// 添加明细
			addDetailProduct(row, isEdit){
				const params = {
				  id: isEdit ? row.id : undefined,
				  sparePartsPurchaseSn: this.sparePartsPurchaseSn,
				  putCost: row.putCost,
				  putQty: row.putQty,
				  productCode: isEdit ? row.productCode : row.code,
				  productOrigCode: (isEdit ? row.productOrigCode : row.origCode) || undefined,
				  productSn: row.productSn,
				  productTypeSn1: row.productTypeSn1,
				  productTypeSn2: row.productTypeSn2,
				  productTypeSn3: row.productTypeSn3,
				  brandSn: isEdit ? row.brandSn : row.productBrandSn,
				  warehouseLocationSn: row.warehouseLocationSn,
				  warehouseSn: row.warehouseSn
				}
				if (isEdit) { // 编辑
				  // 清空成本价或数量时,值应保持未清空前的值，因成本价和数量都不可为空
				  if (!(row.putCost || row.putCost == 0)) {
				    row.putCost = row.putCostBackups
				    return
				  }
				  if (!row.putQty) {
				    row.putQty = row.putQtyBackups
				    return
				  }
				}
				console.log(params)
				this.loading = true
				sparePartsPurDetailSave(params).then(res => {
				  console.log(res,'添加')
				  if (res.status == 200) {
				    this.loading = false
					this.pageInit()
				  } else {
				    this.loading = false
					if(res.message == '采购成本价不能为空;'){
						this.$refs.popup.open()
						this.tempProduct = row
					}
				  }
				})
			},
			// 详情
			getDetail(){
				sparePartsPurDetail({sn: this.sparePartsPurchaseSn}).then(res => {
					if(res.status == 200){
						this.baseData = res.data
					}
				})
			},
			selRow(item){
				this.curProduct = item
				this.code = item.qrCode
			},
			resetForm(){
				this.curProduct = null
				this.code = ''
				this.scrollTop = 0
			},
			// 已添加产品列表
			getDetailList(){
				sparePartsPurDetailList({pageNo:1,pageSize:1000,sparePartsPurchaseSn:this.sparePartsPurchaseSn}).then(res => {
					console.log(res,'已添加产品列表')
					if(res.status == 200){
						this.detailList = res.data.list
						this.detailList.map(item => {
							 item.putCostBackups = item.putCost
							 item.putQtyBackups = item.putQty
						})
						const curProduct = this.detailList.find(item => item.qrCode == this.code)
						this.curProduct = curProduct || null
						this.scrollToRow(this.curProduct)
					}
				})
			},
			// 滚动到指定行
			scrollToRow(cur){
				const idx = this.detailList.findIndex(item => item.id == cur.id)
				this.scrollTop = idx * 30
			},
			getTotal(){
				sparePartsQueryCount({sparePartsPurchaseSn:this.sparePartsPurchaseSn}).then(res => {
					console.log(res,'getTotal')
					this.countData = res.data
				})
			},
			toDetail(item) {
				this.$store.state.vuex_tempData = item
				uni.navigateTo({
					url:"/pages/stockIn/detail?state="+this.baseData.state
				})
			},
			submitInStock(){
				sparePartsPurSubmitPut({id: this.sparePartsPurchaseId}).then(res => {
					if(res.status == 200){
						uni.$emit("refashList")
						uni.navigateBack()
					}
				})
			}
		},
	}
</script>

<style lang="scss">
	.p-content{
		button{
			line-height: 1.7;
		}
		.p-head{
			font-size: 32upx;
			color: $uni-text-color;
			>view{
				display: flex;
				align-items: center;
				padding: 15upx 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;
			}
		}
		.p-body{
			flex-grow: 1;
			height: calc(100vh - 180px);
			.scrollView{
				height: 100%;
			}
		}
		.p-footer{
			padding: 20upx;
			display: flex;
			> button{
				width: 40%;
				padding: 3px 0;
			}
		}
	}
</style>
