<template>
	<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 
						:focus="true"
						style="width: 150px;text-align: left;font-size: 32rpx;padding: 6rpx 0 6rpx 7rpx;" 
						class="uni-input" 
						placeholder="扫描或输入条码" 
						border="surround" 
						v-model="code">
						<button size="mini" @click="queryProduct" :style="{padding:'2px 10px',color:'#00aaff'}">查询</button>
					</view>
				</view>
				<view></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">
			<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="toDetail(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">
						<span :style="{ color: 'red' }">￥{{Number(item.putCost*item.putQty).toFixed(2)}}</span>
					</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></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
			};
		},
		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')
		},
		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
					}
				})
			},
			// 已添加产品列表
			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
					}
				})
			},
			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{
			overflow: auto;
			flex-grow: 1;
			height: 50%;
		}
		.p-footer{
			padding:20upx 30upx;
			display: flex;
			> button{
				width: 30%;
			}
		}
	}
</style>
