<template>

	<view style="background-color:#F4F9FD;">
		<!-- style="position: fixed;top: 1000px;" -->
		<view style="position: fixed;top: 1000px;">
			<!-- 绘制内容 -->
			<view>
				<canvas :width='templateWidth*pixelRatio' :height='templateHeight*pixelRatio'
					:style="{width:templateWidth+'px',height:templateHeight+'px'}" canvas-id="Canvas"
					id="Canvas"></canvas>
			</view>
			<!-- 绘制条形码 -->
			<view>
				<canvas type="2d" :style="{width:barcodeWidth+'px',height:barcodeHeight+'px'}" class="ls-barcode-canvas"
					canvas-id="barCodels" id="barCodels"></canvas>
			</view>
			<!-- 绘制二维码 -->
			<view>
				<canvas :style="{width:qrcodeWidth+'px', height: qrcodeHeight+'px'}" canvas-id="qrCode"></canvas>
			</view>
		</view>
		<view class="connect-blue">
			<text @click="CloseBlue()">断开蓝牙</text>
		</view>
		<view class="connect-blue">
			<text @click="isConnectBlue()">当前蓝牙连接状态</text>
		</view>
		<view class="connect-blue">
			<text @click="SearchBlueList()">当前蓝牙搜索列表</text>
		</view>
		<view class="connect-blue">
			<text @click="StopSearchBlueList()">停止搜索蓝牙</text>
		</view>
		<view class="connect-blue">
			<text @click="onDoPrintTemplatePageObjectLocal()">打印本地字模</text>
		</view>
		<view class="connect-blue">
			<text @click="onDoPrintTemplatePageImageLocal">打印图片</text>
		</view>
		<view class="connect-blue">
			<text @click="onDoPrintCancel()">终止打印</text>
		</view>
		<view class="printnum-text">
			<text>打印份数：</text>
			<text>{{printNum}}</text>
		</view>
		<view class="printnum-text">
			<text>打印状态：</text>
			<text>{{printType}}</text>
		</view>
		<view class="input-text">
			<input type="number" placeholder="输入打印份数" @input="bindKeyInput" />
		</view>

		<scroll-view class="scroll-view" scroll-y>
			<view class="list-wrap" v-for="(item,index) in blueList" :key="index">
				<view class="shop-name" @click="connectDevice(item)">
					<text class="text-shop-name">蓝牙名称</text>
					<text class="text-shop-name">{{item.name}}</text>
				</view>
			</view>
		</scroll-view>

	</view>
</template>

<script>
	import bleToothManage from '../../SUPVANAPIT50PRO/BLEToothManage.js';
	import barCodeUtils from "@/SUPVANAPIT50PRO/barCodeUtils.js"
	import bleTool from '../../SUPVANAPIT50PRO/BLETool.js'
	import {
		LPAPIFactory,
		LPAPI,
		LPA_Result,
		LPAUtils
	} from "@/uni_modules/dothan-lpapi-ble/js_sdk/index.js";
	export default {
		data() {
			return {
				canvasWidth: 300,
				canvasHeight: 300,
				blueList: [], //搜索到的蓝牙列表
				connectType: false, //蓝牙连接状态
				deviceSn: '', //蓝牙序列号
				templateWidth: 560,
				templateHeight: 304,
				barcodeWidth: 194,
				barcodeHeight: 56,
				qrcodeWidth: 20,
				qrcodeHeight: 20,
				pixelRatio: 1,
				barCodeCanvas: null,
				Canvas: null,
				printCopies: 0,
				printNum: 0,
				printType: '0',
				previewPath: 'https://resource-supvan.oss-cn-qingdao.aliyuncs.com/upload/Template/System/T/34574.png',
				LPApi: null,
				//字模数据组成格式
				PageObject: [{
					"Width": 50,
					"Height": 30,
					"Rotate": "1",
					"Copies": "1",
					"Density": 4,
					"HorizontalNum": 0,
					"VerticalNum": 0,
					"PaperType": 3,
					"Gap": 3,
					"DeviceSn": "T0024B",
					"CutType": 1,
					"SavePaper": false,
					"FirstCut": 0,
					"PreviewPath": 'https://sjpt.issas.ac.cn/profile/upload/Template/202502271300003.jpg',
					"ImageWidth": 50,
					"ImageHeight": 50,
					"Margin": 2,
					"Speed": 60,
					"DrawObjects": [
						// {
						// 	"AntiColor": false,
						// 	"X": 0,
						// 	"Y": 0,
						// 	"Width": 30,
						// 	"Height": 24,
						// 	"Content": "https://resource-supvan.oss-cn-qingdao.aliyuncs.com/upload/Template/System/T/34574.png",
						// 	"FontName": "黑体",
						// 	"FontStyle": 0,
						// 	"Align": 1,
						// 	"FontSize": null,
						// 	"AutoReturn": false,
						// 	"Format": "IMAGE",
						// 	"X1": 67,
						// 	"Y1": 48,
						// 	"Orientation": 2,
						// },
						{
							"AntiColor": false,
							"X": 30,
							"Y": 0,
							"Width": 30,
							"Height": 4,
							"Content": "文本内容",
							"FontName": "黑体",
							"FontStyle": 0,
							"Align": 1,
							"FontSize": 4,
							"AutoReturn": false,
							"Format": "TEXT",
							"X1": 67,
							"Y1": 48,
							"Orientation": 0,
						},
						// {
						// 	"AntiColor": false,
						// 	"X": 5,
						// 	"Y": 10,
						// 	"Width": 30,
						// 	"Height": 30,
						// 	"Content": "二维码内容",
						// 	"FontName": "黑体",
						// 	"FontStyle": 0,
						// 	"Align": 1,
						// 	"FontSize": null,
						// 	"AutoReturn": false,
						// 	"Format": "QRCODE",
						// 	"X1": 30,
						// 	"Y1": 18,
						// 	"Orientation": 2
						// },
						{
							"AntiColor": false,
							"X": 5,
							"Y": 0,
							"Width": 30,
							"Height": 9,
							"Content": "6903244679763",
							"FontName": "黑体",
							"FontStyle": 0,
							"Align": 1,
							"FontSize": 4,
							"AutoReturn": false,
							"Format": "BARCODE",
							"Orientation": 2,
						}

					],
					"Direction": 1
				}],

				PageImageObject: [{
						"Width": 50,
						"Height": 70,
						"Rotate": 1,
						"Copies": 1,
						"Density": 6,
						"HorizontalNum": 0,
						"VerticalNum": 0,
						"PaperType": 1,
						"Gap": 3,
						"DeviceSn": 'T0100A2305163367',
						"ImageUrl": 'https://resource-supvan.oss-cn-qingdao.aliyuncs.com/upload/Template/System/T/34574.png',
						"ImageWidth": 50, //图片宽（单位mm）
						"ImageHeight": 70, //图片高（单位mm）
						"Speed": 60,
					},
					// {
					// 	"Width": 50,
					// 	"Height": 30,
					// 	"Rotate": 1,
					// 	"Copies": 1,
					// 	"Density": 4,
					// 	"HorizontalNum": 0,
					// 	"VerticalNum": 0,
					// 	"PaperType": 3,
					// 	"Gap": 8,
					// 	"DeviceSn": 'T0100A2305163367',
					// 	"ImageUrl": 'https://resource-supvan.oss-cn-qingdao.aliyuncs.com/upload/Template/System/T/34574.png',
					// 	"ImageWidth": 50, //图片宽（单位mm）
					// 	"ImageHeight": 30, //图片高（单位mm）
					// }
				],
			}
		},
		onLoad() {
			this.lpapi = LPAPIFactory.getInstance({
				// 日志信息显示级别，值为 0 - 4，0表示不显示调试信息，4表示显示所有调试信息
				showLog: 4,
				// 钉钉小程序需要备注下，UniApp无法识别钉钉小程序。
				isDingTalk: false,
				// enablePageKey: true,
				// bleAdapter: bleAdapter,
			});
			//this.LPApi = this.lpapi
			this.onBLEConnectionStateChange();
			this.pixelRatio = uni.getSystemInfoSync().pixelRatio
			this.Canvas = uni.createCanvasContext('Canvas', this)
			this.barCodeCanvas = uni.createCanvasContext('barCodels', this)

		},
		onReady() {
			this.context = this.lpapi.createDrawContext({
				// 用于进行标签绘制的画布ID
				canvasId: 'Canvas',
			});
			this.lpapi.setDrawContext(this.context);
		},
		onShow() {

		},
		methods: {
			/**
			 * 搜索蓝牙列表
			 */
			SearchBlueList() {
				const that = this
				that.blueList = []
				bleToothManage.searchBlueList(function(res) {
					console.log("res: " + JSON.stringify(res));
					that.blueList.push(res)
				})
			},
			/**
			 * 停止搜索蓝牙
			 */
			StopSearchBlueList() {
				bleToothManage.stopSearchBlueList()
			},
			/**
			 * 设备id连接蓝牙
			 */
			connectDevice(item) {
				const that = this
				this.deviceSn = item.name
				for (const objectdata of that.PageObject) {
					objectdata.DeviceSn = this.deviceSn
				}
				for (const objectdataImg of that.PageImageObject) {
					objectdataImg.DeviceSn = this.deviceSn
				}
				this.ConnectBlue(item.deviceId)
			},
			/**
			 * 连接蓝牙
			 */
			ConnectBlue(deviceId) {
				bleToothManage.connectBlue(deviceId, this.deviceSn, this.lpapi, function(connectBlueType) {
					// console.log('蓝牙是否连接成功', connectBlueType.connectBlueType);
					// console.log('蓝牙服务uuid', connectBlueType.serviceUuid);
					if (connectBlueType.connectBlueType) {
						bleTool.setBlueType(false)
						uni.showToast({
							title: '连接蓝牙成功',
							icon: 'none',
						});
					} else {
						uni.showToast({
							title: '连接蓝牙失败',
							icon: 'none',
						});
					}
				})


			},
			/**
			 * 关闭蓝牙
			 */
			CloseBlue() {
				bleToothManage.closeBlue(function(closeBlueType) {
					if (closeBlueType) {
						uni.showToast({
							title: '断开蓝牙成功',
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: '断开蓝牙失败',
							icon: 'none'
						})
					}
				})
				this.lpapi.closePrinter()
			},

			/**
			 * 蓝牙连接状态查询
			 */
			isConnectBlue() {
				uni.showToast({
					title: '当前蓝牙连接状态' + bleTool.isConnectBlueTooth(),
					icon: 'none'
				})
			},
			/**
			 * 该方法回调中可以用于处理连接意外断开等异常情况
			 */
			onBLEConnectionStateChange() {
				uni.onBLEConnectionStateChange(res => {
					if (!res.connected) {
						this.connectType = false
						uni.showToast({
							title: '机器已断开',
							icon: 'none'
						});
					} else {
						this.connectType = true
					}
					bleTool.setBlueToothType(this.connectType)

				});
			},
			/**
			 * 打印本地字模
			 */
			onDoPrintTemplatePageObjectLocal() {
				console.log('开始打印');
				const that = this
				that.printNum = 0
				that.printType = 0
				bleToothManage.print(this.Canvas, this.PageObject, this.barCodeCanvas, result => {
						console.log('当前打印状态:', result.msgType);
						console.log('当前打印份数', result.printNum);
						this.printNum = result.printNum
						this.printType = result.msgType
					})
					.then(res => {
						console.log('数据回调', res)
						that.templateWidth = res.Width
						that.templateHeight = res.Height
						that.barcodeWidth = res.barcodeWidth
						that.barcodeHeight = res.barcodeHeight
						that.qrcodeWidth = res.qrcodeWidth
						that.qrcodeHeight = res.qrcodeHeight
					}).catch(res => {})

				//that.localImagePrintTest()


			},
			localImagePrintTest() {
				// const api = this.LPApi;
				//
				const labelWidth = 40;
				const labelHeight = 20;
				const margin = 2;
				const url = "/static/logo.png";
				//

				this.lpapi.loadImage(url).then((image) => {
					console.log('image', image);
					const jobInfo = this.lpapi.startJob({
						width: labelWidth,
						height: labelHeight,
						orientation: 0,
						jobName: '',
					});
					if (!jobInfo) {
						console.warn("---------- 打印任务创建失败！----------");
						return;
					}

					// 绘制标签外边框
					this.lpapi.drawRectangle({
						width: labelWidth,
						height: labelHeight,
						lineWidth: 0.3,
					});
					// 绘制图片
					this.lpapi.drawImage({
						image: image,
						x: margin,
						y: margin,
						width: labelWidth - margin * 2,
						height: labelHeight - margin * 2,
					});
					//
					this.lpapi.commitJob({
						gapType: 1,
						printDarkness: 4,
						printSpeed: 30,
						threshold: 192,
					}).then((resp) => {
						// this.previewLabel(resp);
						console.log('resp', resp);
						return resp.statusCode === 0;
					});

				});

			},
			/**
			 * 打印图片
			 */
			onDoPrintTemplatePageImageLocal() {
				console.log('打印图片')
				const that = this
				bleTool.setBlueType(true)
				bleToothManage.printImage(this.Canvas, this.PageImageObject, result => {
					console.log('当前打印状态:', result.msgType);
					console.log('当前打印份数', result.printNum);
					that.printNum = result.printNum
					that.printType = result.msgType
				}).then(res => {
					console.log('数据回调', res)
					that.templateWidth = res.Width
					that.templateHeight = res.Height
				}).catch(res => {})
			},
			/**
			 * 终止打印
			 */
			onDoPrintCancel() {
				bleToothManage.stopPrint()
			},
			bindKeyInput(e) {
				console.log('打印份数', e.detail.value);
				this.PageObject[0].Copies = e.detail.value
				this.PageImageObject[0].Copies = e.detail.value
			},

		},
	}
</script>

<style>
	page {
		background-color: #F4F9FD;
	}

	.connect-blue {
		display: flex;
		justify-content: center;
		background-color: antiquewhite;
		margin: 20rpx 0;

	}

	.connect-blue text {
		font-size: 31rpx;
		font-weight: 500;
		color: #000000;
		padding: 20rpx 0rpx;
	}

	.list-wrap {
		width: 750rpx;
		height: 100rpx;
		background: #F7F8FA;
	}

	.shop-name {
		display: flex;
		margin: 10rpx;
		padding: 30rpx;
		background-color: antiquewhite;
	}

	.text-shop-name {
		font-size: 23rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.text-shop-name-content {
		font-size: 25rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #000000;
		margin-top: 10rpx;
	}

	.printnum-text {
		display: flex;
		justify-content: center;
		background-color: antiquewhite;
		margin: 20rpx 0;

	}

	.input-text {
		display: flex;
		align-items: center;
		height: 50rpx;
	}

	.blue-list {
		padding-bottom: 219rpx;
		overflow: auto;
	}

	.scroll-view {
		width: 100vw;
		height: 30vh;
		/* 固定高度 */
	}
</style>