<template>
	<view class="batchPrint-manualPrint-wrap" :style="{'padding-top':type=='search'?'100rpx':'0'}">
		<view v-if="type=='search'" class="productList-search">
			<view class="search flex align_center">
				<view class="input">
					<u-search 
					v-model="queryWord" 
					@input="$u.debounce(searchList, 800)"
					@custom="$u.debounce(searchList, 500)" 
					@search="$u.debounce(searchList, 500)" 
					@clear="clearSearch" 
					bg-color="#fff" 
					:show-action="false"
					placeholder="请输入产品编码查询"></u-search>
				</view>
			</view>
		</view>
		<view class="batchPrint-manualPrint-body">
			<view class="part-list">
				<!-- 产品 -->
				<productList :list="partList" title="产品列表" ref="productList" noDataText="暂无产品" @allChecked="allCheckedCallback"></productList>
			</view>
		</view>
		<view class="batchPrint-manualPrint-footer">
			<view>
				<u-checkbox size="40" @change="allCheckeChange" v-model="allChecked" shape="circle">{{allChecked?'取消全选':'全选'}}</u-checkbox>
			</view>
			<view>
			</view>
			<view>
				<kk-printer ref="kkprinter" defaultText="开始打印" @closeConnect="closeConnect" @startPrint="startPrint"></kk-printer>
			</view>
		</view>
	</view>
</template>

<script>
	import { clzConfirm, numberToFixed } from '@/libs/tools';
	import kkPrinter from '@/components/kk-printer/index.vue';
	import productList from './productList.vue'
	import {printTempl,printCpclTempl} from '@/libs/printTools.js'
	export default {
		components: { productList, kkPrinter },
		data() {
			return {
				show: false,
				basicInfoData:null,
				partList: [],
				allList:[],
				allChecked: false,
				printIndex: 0,
				isParinting: false,
				type: '',
				queryWord: ''
			}
		},
		onReady() {
			if(this.type == 'manual'){
				uni.showLoading({
					title: '正在加载...'
				})
				this.$refs.productList.setData(this.partList)
				setTimeout(()=>{
					uni.hideLoading()
					this.allCheckeChange({value:true})
					this.allChecked = true
				},3000)
			}
		},
		onLoad(option) {
			this.basicInfoData = JSON.parse(decodeURIComponent(option.data));
			this.type = option.type
			// 批量打印
			if(this.type == 'manual'){
				this.partList = this.$store.state.vuex_tempPrintList
			}else{
				this.allList = this.$store.state.vuex_tempPrintList
			}
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.$config('primaryColor')
			})
			uni.setNavigationBarTitle({
				title: this.type == 'search' ? '按编码搜索打印' : '批量打印—'+this.basicInfoData.layer+'层'
			})
		},
		onUnload() {
			this.partList = []
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: false
			});
			this.$store.state.vuex_tempPrintList = []
		},
		onBackPress(event){
			if(event.from == 'backbutton'){
				if(this.isParinting){
					uni.showToast({
						icon:'none',
						title: '正在打印中...'
					})
				}else{
					uni.navigateBack({delta: 1})
				}
				return true  // 阻止默认返回行为(会导致无限循环)
			}
		},
		methods: {
			searchList(e){
				if(this.queryWord == ''){
					this.clearSearch()
					return
				}
				
				uni.showLoading({
					mask: true,
					title: "正在搜索..."
				})
				this.partList = []
				// 搜索
				for(let key in this.allList){
					const item = this.allList[key]
					const ret = item.filter(a => a.productCode.indexOf(this.queryWord)>=0)
					this.partList = this.partList.concat(ret)
				}
				this.$refs.productList.setData(this.partList)
				
				setTimeout(()=>{
					uni.hideLoading()
				},1000)
			},
			clearSearch(){
				this.partList = []
				this.$refs.productList.setData(this.partList)
			},
			// 全选
			allCheckeChange(e){
				this.$refs.productList.allSelect(e.value)
			},
			allCheckedCallback(val){
				this.allChecked = val
			},
			printOnce(opt,cmd,blesdk,data){
				const _this = this
				const dealer = this.$store.state.vuex_userData
				const paramsData = {
					dealerName: dealer.orgName,
					shelfName: this.basicInfoData.shelfName || '',
					productCode: data.productCode || '',
					productName: data.product.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}`
				}
				// 打印成功后函数
				const onPrintSuccess = function(){
					const result =_this.$refs.productList.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 指令 // 60*40 打印模板
				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.productList.getAllChecked()
				console.log(result,result.length)
				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">
.batchPrint-manualPrint-wrap{
	width: 100%;
	height: 100%;
	overflow: hidden;
	padding-bottom: 102upx;
	.productList-search{
		padding: 20rpx 30rpx;
		background-color: #fff;
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		display: flex;
		z-index: 100;
		.search{
			padding: 0.1rem;
			border-radius: 50rpx;
			border:1rpx solid #eee;
			width: 100%;
			.input{
				flex-grow: 1;
				padding: 4rpx;
			}
			.icon{
				width: 13%;
				text-align: center;
				font-size: 46rpx;
				color: #999;
			}
		}
	}
	.batchPrint-manualPrint-body{
		.part-list{
			padding: 10rpx 25rpx;
			background-color: #fff;
			margin-bottom: 20rpx;
			border-radius: 25rpx;
			box-shadow: 2rpx 3rpx 5rpx #eee;
		}
	}
	.batchPrint-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;
		z-index: 1000;
	}
}
</style>
