<template>
	<view class="replenishment-manualPrint-wrap">
		<view class="replenishment-manualPrint-body">
			<view class="part-list">
				<!-- 补货产品 -->
				<partList :list="partList" title="补货产品" model="checkbox" fromPage="manualPrint" ref="partList" noDataText="暂无产品" @allChecked="allCheckedCallback"></partList>
			</view>
		</view>
		<view class="replenishment-manualPrint-footer">
			<view>
				<u-checkbox size="40" @change="allCheckeChange" v-model="allChecked" shape="circle">{{allChecked?'取消全选':'全选'}}</u-checkbox>
			</view>
			<view>
				<kk-printer @closeConnect="closeConnect" ref="kkprinter" defaultText="开始打印" @startPrint="startPrint"></kk-printer>
			</view>
		</view>
	</view>
</template>

<script>
	import { clzConfirm, numberToFixed } from '@/libs/tools';
	import kkPrinter from '@/components/kk-printer/index.vue';
	import { shelfReplenishDetail, shelfReplenishDetailList, shelfReplenishPrintSign } from '@/api/shelfReplenish'
	import partList from '@/pages/common/partList.vue'
	import {printTempl,printCpclTempl} from '@/libs/printTools.js'
	export default {
		components: { partList, kkPrinter },
		data() {
			return {
				show: false,
				replenishBillSn: '',
				basicInfoData:null,
				partList: [],
				allChecked: false,
				printIndex: 0,
				isParinting: false
			}
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.$config('primaryColor')
			})
		},
		onLoad(option) {
			this.replenishBillSn = option.sn
			this.getDetail()
			this.getPartList()
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
		},
		onUnload() {
			// this.$refs.kkprinter.closeConnect()
			// 保持屏幕常亮
			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: {
			// 查询详情
			getDetail(){
				shelfReplenishDetail({ sn: this.replenishBillSn }).then(res => {
					if(res.status == 200){
						this.basicInfoData = res.data || null
					}else{
						this.basicInfoData = null
					}
				})
			},
			// 查询列表
			getPartList(){
				const _this = this
				shelfReplenishDetailList({ replenishBillSn: this.replenishBillSn }).then(res => {
					if(res.status == 200 && res.data){
						res.data.map(item =>{
							if(item.billState == 'FINISH'){
								item.confirmQty = item.putQty ? Number(item.putQty) : 0
								item.printQty = item.confirmQty ? Number(item.confirmQty) : 0
							}else{
								item.confirmQty = item.confirmQty ? Number(item.confirmQty) : 0
								item.printQty = item.confirmQty ? Number(item.confirmQty) : 0
							}
						})
						this.partList = res.data || []
						this.$nextTick(()=>{
							this.allCheckeChange({value:true})
							this.allChecked = true
						})
					}else{
						this.partList = []
					}
				})
			},
			// 全选
			allCheckeChange(e){
				this.$refs.partList.allSelect(e.value)
			},
			allCheckedCallback(val){
				this.allChecked = val
			},
			printOnce(opt,cmd,blesdk,data){
				const _this = this
				// 60*40 打印模板
				const dealer = this.$store.state.vuex_userData
				const paramsData = {
						dealerName: dealer.orgName,
						shelfName: this.basicInfoData.shelfInfo.shelfName || '',
						productCode: data.productCode || '',
						productName: data.product.name || '',
						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}`
						// barCode: `dealerSn=${dealer.orgSn}&shelfSn=${data.shelfSn}&productSn=${data.productSn}&productCode=${data.productCode}&shelfPlaceCode=${data.shelfPlaceCode}&shelfPlaceSn=${data.shelfPlaceSn}`
					}
				
				// 打印成功后函数
				const onPrintSuccess = function(){
					const result =_this.$refs.partList.getAllChecked()
					_this.printIndex = _this.printIndex + 1
					if(_this.printIndex < result.length){
						_this.printOnce(opt,cmd,blesdk,result[_this.printIndex])
					}else{
						_this.printIndex = 0
						_this.$refs.kkprinter.onPrintSuccess()
						_this.isParinting = false
						uni.hideLoading()
						clzConfirm({
						  title: '提示',
						  content: '打印已经结束，是否返回上页！',
						  success (ret) {
							if (ret.confirm || ret.index == 0) {
								uni.navigateBack()
							} 
						  }
						})
					}
				}
				// tsc 指令
				console.log(cmd,cmd.type)
				if(cmd.type&&cmd.type=='tsc'){
					const command = printTempl(cmd,paramsData)
					// 开始批量打印
					blesdk.senBlData(opt.deviceId, opt.serviceId, opt.writeId, command.getData(), onPrintSuccess, this.onPrintError);
				}else{
					const resultData = printCpclTempl(cmd,paramsData)
					blesdk.sendDataToDevice({
						deviceId: opt.deviceId, 
						serviceId: opt.serviceId, 
						characteristicId: opt.writeId,
						value: resultData,
						lasterSuccess: onPrintSuccess,
						lasterError: this.onPrintError
					});
				}
				
			},
			closeConnect(){
				this.isParinting = false
				uni.hideLoading()
			},
			onPrintError(){
				this.$refs.kkprinter.onPrintFail()
				this.isParinting = false
				this.show = false
				uni.showToast({
					title: '打印失败，请重试！'
				})
			},
			// 批量打印 
			startPrint(opt,cmd,blesdk){
				const result =this.$refs.partList.getAllChecked()
				if(result.length){
					 if(this.isParinting){
					 	return
					 }
					 this.isParinting = true
					 uni.showLoading({
					 	mask: true,
					 	title: '正在打印中,请勿息屏或退出应用!'
					 })
					 this.printOnce(opt,cmd,blesdk,result[this.printIndex])
				}else{
					this.toashMsg("请选择产品！")
					this.$refs.kkprinter.onPrintFail()
				}
			},
		}
	}
</script>

<style lang="less">
.replenishment-manualPrint-wrap{
	position: relative;
	width: 100%;
	height: 100%;
	overflow: hidden;
	padding-bottom: 102upx;
	.replenishment-manualPrint-body{
		.part-list{
			padding: 10rpx 25rpx;
			background-color: #fff;
			margin-bottom: 20rpx;
			border-radius: 25rpx;
			box-shadow: 2rpx 3rpx 5rpx #eee;
		}
	}
	.replenishment-manualPrint-footer{
		padding: 10upx 32upx 12upx;
		background-color: #fff;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		box-shadow: 3px 1px 7px #eee;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
}
</style>
