<template>
	<view class="content flex flex_column">
		<view class="head-info">
			<view class="p-title flex align_center">
				<text></text>
				<view class="shelfName flex align_center">
					<view>
						{{basicInfoData.shelfName}}
					</view>
				</view>
			</view>
			<view>系统检测到以下产品缺货，请选择需要补货的产品</view>
		</view>
		<view class="partlist">
			<quickProductList :list="partList" ref="productList" noDataText="暂无产品" @allChecked="allCheckedCallback"></quickProductList>
		</view>
		<view class="part-footer flex align_item justify_between">
			<view>
				<u-checkbox size="40" @change="allCheckeChange" v-model="allChecked" shape="circle">{{allChecked?'取消全选':'全选'}}</u-checkbox>
			</view>
			<view class="btns flex align_item justify_end">
				<view>
					<kk-printer ref="kkprinter" printBtnStyle="default-mid" defaultText="打印贴签" @startPrint="startPrint"></kk-printer>
				</view>
				<view style="padding: 0 10rpx;"></view>
				<view>
					<u-button class="handle-btn" :loading="loading" shape="circle" size="medium" hover-class="none" :custom-style="customBtnStyle" @click="replenish">快速补货</u-button>
				</view>
			</view>
		</view>
		<!-- 选择配送方式弹框 -->
		<choose-type-modal v-if="chooseModal" :openModal="chooseModal" @confirm="modalChooseType" @close="chooseModal = false" />
		<!-- 库存不足 弹框 -->
		<stock-modal v-if="stockModal" :openModal="stockModal" :list="stockList" :params="temParams" @confirm="modalStock" @close="stockModal=false" />
	</view>
</template>

<script>
	import quickProductList from './quickProductList.vue'
	import kkPrinter from '@/components/kk-printer/index.vue';
	import chooseTypeModal from './chooseTypeModal.vue'
	import stockModal from '@/pages/replenishmentManage/stockModal.vue'
	import {printTempl} from '@/libs/printTools.js'
	import {saveReplenishBill} from '@/api/shelfReplenish.js'
	export default {
		components: { quickProductList, kkPrinter, chooseTypeModal, stockModal },
		data() {
			return {
				loading: false,
				chooseModal: false,
				basicInfoData:null,
				partList: [],
				allChecked: false,
				printIndex: 0,
				isParinting: false,
				stockModal: false,
				stockList: [],
				temParams:null,
				customBtnStyle: {  //  自定义按钮样式
					borderColor: this.$config('primaryColor'),
					backgroundColor: this.$config('primaryColor'),
					color: '#fff'
				},
			}
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.$config('primaryColor')
			})
			this.$refs.productList.setData(this.partList)
			this.allCheckeChange({value:true})
			this.allChecked = true
		},
		onLoad(option) {
			this.basicInfoData = JSON.parse(decodeURIComponent(option.data));
			this.partList = this.basicInfoData.list
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
		},
		onUnload() {
			this.partList = []
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: false
			});
		},
		onBackPress(event){
			if(event.from == 'backbutton'){
				if(this.isParinting){
					uni.showToast({
						icon:'none',
						title: '正在打印中...'
					})
				}else{
					uni.navigateBack({delta: 1})
				}
				return true  // 阻止默认返回行为(会导致无限循环)
			}
		},
		methods: {
			// 全选
			allCheckeChange(e){
				this.$refs.productList.allSelect(e.value)
			},
			allCheckedCallback(val){
				this.allChecked = val
			},
			// 补货
			replenish(){
				const result =this.$refs.productList.getAllChecked()
				console.log(result,result.length)
				if(result.length){
					this.chooseModal = true
				}else{
					this.toashMsg("请选择产品！")
				}
			},
			modalChooseType(data,confirm){
				const result =this.$refs.productList.getAllChecked()
				const arr = []
				result.map((item, index) => {
				  arr.push({
				    productSn: item.productSn,
					productCode: item.productCode,
				    qty: item.printQty,
					shelfSn: this.basicInfoData.shelfSn,
				    shelfPlaceCode: item.shelfPlaceCode,
					shelfPlaceSn: item.shelfPlaceSn
				  })
				})
				const params = {
				  detailList: arr,
				  dispatchType: data.dispatchType,
				  remarks: data.remarks,
				  shelfSn:this.basicInfoData.shelfSn,
				  confirm: confirm
				}
				console.log(params)
				uni.showLoading({
					title: "正在提交..."
				})
				this.loading = true
				saveReplenishBill(params).then(res => {
					console.log(res)
					if(res.status == 200){
						// 库存不足
						if(res.data&&res.data.length){
							this.temParams = params
							this.stockList = res.data
							this.stockModal = true
						}else{
							uni.navigateBack()
							this.toashMsg(res.message)
						}
					}
					this.loading = false
					this.chooseModal = false
					uni.hideLoading()
				})
			},
			// 继续补货
			modalStock(params){
				this.modalChooseType(params,1)
				this.stockModal = false
			},
			printOnce(opt,tsc,blesdk,data){
				const _this = this
				const dealer = this.$store.state.vuex_userData
				// 60*40 打印模板
				const command = printTempl(tsc,{
					dealerName: dealer.orgName,
					shelfName: data.shelfName || '',
					productCode: data.productCode || '',
					productName: data.productName || '',
					shelfPlaceCode: data.shelfPlaceCode || '',
					currentInven: data.printQty,
					printDate: this.$u.timeFormat(this.timestamp, 'yyyy-mm-dd hh:MM'),
					printUser: dealer.userNameCN,
					barCode: `${data.shelfSn}&${data.productCode}&${data.productSn}&${data.shelfPlaceSn}`
				})
				// 开始批量打印 
				blesdk.senBlData(
				opt.deviceId, 
				opt.serviceId, 
				opt.writeId, 
				command.getData(), 
				function(){
					const result =_this.$refs.productList.getAllChecked()
					_this.printIndex = _this.printIndex + 1
					if(_this.printIndex < result.length){
						_this.printOnce(opt,tsc,blesdk,result[_this.printIndex])
					}else{
						_this.printIndex = 0
						_this.$refs.kkprinter.onPrintSuccess()
						_this.isParinting = false
					}
				});
			},
			// 批量打印 
			startPrint(opt,tsc,blesdk){
				const _this = this
				const result =_this.$refs.productList.getAllChecked()
				console.log(result,result.length)
				if(result.length){
					 if(_this.isParinting){
					 	return
					 }
					 clzConfirm({
					   title: '提示',
					   content: '开始打印后，无法撤回，系统将默认按照每个产品的补货数量批量打印',
					   success (ret) {
					 	if (ret.confirm || ret.index == 0) {
					 		_this.isParinting = true
					 		_this.printOnce(opt,tsc,blesdk,result[_this.printIndex])
					 	}
					   }
					 })
				}else{
					_this.toashMsg("请选择产品！")
					_this.$refs.kkprinter.onPrintFail()
				}
			},
		}
	}
</script>

<style lang="less">
	.content{
		width: 100%;
		height: 100vh;
		background: #fff;
		.head-info{
			padding: 20rpx 20rpx 0;
			border-bottom: 2rpx solid #eee;
			> view{
				padding: 10rpx;
				color: darkorange;
			}
			.p-title{
				padding: 0 10rpx;
				display: flex;
				align-items: center;
				color: #222;
				font-size: 30rpx;
				> text{
						display: block;
						height: 30rpx;
						width: 6rpx;
						background: #0485F6;
						margin-right: 10rpx;
						border-radius: 10rpx;
					}
				.shelfName{
					flex-grow: 1;
					font-weight: bold;
					width: 80%;
					> view{
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
			}
		}
		.partlist{
			flex-grow: 1;
			padding: 0 30rpx;
			overflow: auto;
		}
		.part-footer{
			padding: 20rpx 30rpx;
			border-top: 2rpx solid #eee;
			> view{
				&:first-child{
					width: 30%;
					text-align: left;
					padding-top: 10rpx;
				}
				text-align: right;
			}
			.btns{
				flex-grow: 1;
				button{
					width: 200rpx;
				}
			}
		}
	}
</style>
