<template>
	<view class="content">
		<view class="body">
			<!-- 	<view>
				<textarea class="result" v-model="returnResult"></textarea>
			</view>
			<textarea class="input" @input="inputEvent" /> -->
			<!-- <button type="primary" @tap="sendData">发送(票据可使用)</button> -->

			<view style='margin-top:4%;display: flex;flex-direction: column;'>
				<button type='primary' class="btn" @tap='receiptTest' :loading='isReceiptSend'
					:disabled='isReceiptSend'>打印出库小票</button>
					<button type='primary' class="btn" @tap='goToList'>返回列表页</button>
				<!-- <button type='primary' @tap='labelTest' :loading='isLabelSend' :disabled='isLabelSend'>标签测试</button> -->
			</view>

			<view style='margin-top:4%;display: flex;flex-direction: row;'>
				<!-- hidden='true' -->
				<canvas canvas-id='edit_area_canvas'
					:style="{width:canvasWidth+'px',height:canvasHeight+'px'}"></canvas>
			</view>

			<!-- <picker style='margin:20px' mode='selector' :range='buffSize' :value='buffIndex' @change='buffBindChange'>
				当前每次发送字节数为(点击可更换)：{{buffSize[buffIndex]}}
			</picker>
		
			<picker style='margin:20px' mode='selector' :range='printNum' :value='printNumIndex' @change='printNumBindChange'>
				当前打印份数(点击可更换)：{{printNum[printNumIndex]}}
			</picker> -->

		</view>
	</view>
</template>

<script>
	var tsc = require("../../util/ble/tsc.js");
	var esc = require("../../util/ble/esc.js");
	var encode = require("../../util/ble/encoding.js");
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				sendContent: "",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '../../static/img/abc_ic_star_black_16dp.png',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				gridList: {}
			};
		},
		computed: mapState(['sysinfo', 'Bluetooth']),
		onLoad() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			uni.notifyBLECharacteristicValueChange({
				deviceId: BLEInformation.deviceId,
				serviceId: BLEInformation.notifyServiceId,
				characteristicId: BLEInformation.notifyCharaterId,
			 state: true,
				success(res) {
					uni.onBLECharacteristicValueChange(function(r) {
						console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)
					})
				},
			 fail: function(e) {
					console.log(e)
			 },
				complete: function(e) {
					console.log(e)
				}
			})
		},
		onReady() {
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
				list[j] = i;
				j++
			}
			for (let i = 1; i < 10; i++) {
				numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onShow() {
			this.gridList = uni.getStorageSync("exWarehousing_print")
			console.log(this.gridList)
			let that = this;
			let width;
			let height;
			uni.getImageInfo({
				src: that.imageSrc,
				success(res) {
					console.log(res.width)
					console.log(res.height)
					width = res.width
					height = res.height
					that.canvasWidth = res.width;
					that.canvasHeight = res.height;
				}
			})
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			// if (app.globalData.platform == "android") {
			//   ctx.translate(width, height)
			//   ctx.rotate(180 * Math.PI / 180)
			// }
			ctx.drawImage(this.imageSrc, 0, 0, width, height);
			ctx.draw();
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// uni.closeBLEConnection({
			//      deviceId: BLEInformation.deviceId,
			//      success: function(res) {
			//        console.log("关闭蓝牙成功")
			//      },
			//    })	
		},
		methods: {
			goToList(){
				uni.navigateTo({
					url: '/pages/erp/index?companyId=1'
				})
			},
			//获取输入内容
			inputEvent(e) {
				this.sendContent = e.detail.value;
			},
			//输入框点击发送
			sendData() {
				let data = this.sendContent + "\n"
				this.looptime = 0;
				var content = new encode.TextEncoder(
					'gb18030', {
						NONSTANDARD_allowLegacyEncoding: true
					}).encode(data);

				this.prepareSend(content);
			},
			//打印票据数据
			receiptTest() {
				var that = this;
				var canvasWidth = that.canvasWidth
				var canvasHeight = that.canvasHeight
				var command = esc.jpPrinter.createNew()
				command.init()
				// 标题
				command.bold(1); //加粗
				command.setFontSize(16); //字体大小
				command.setSelectJustification(1) //居中
				// command.rowSpace(10);
				command.setText("出库检斤单");
				command.setPrint();
				command.rowSpace(60);
				command.bold(0); //取消加粗
				command.setFontSize(0); //正常字体
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("时间：" + that.gridList.updateDate);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("送货单位:" + that.gridList.seller);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("收货单位:" + that.gridList.buyer);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("货名：" + that.gridList.goodsName);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("质检员：" + that.gridList.backOffice);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("毛重（吨）" + that.gridList.grossWeight);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("皮重（吨）" + that.gridList.tare);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("净重（吨）" + that.gridList.netWeight);
				command.setPrint();
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("运输方式：" + that.gridList.outType);
				command.setPrint();
				
				if(that.gridList.outType=="集装箱船"||taht.gridList.outType=="汽运"){
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("车牌号：" + that.gridList.carNo);
					command.setPrint();
				}else if(that.gridList.outType=="火运"){
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("车号：" + that.gridList.carNo);
					command.setPrint();
				}else if(that.gridList.outType=="散船"){
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("船名：" + that.gridList.shipName);
					command.setPrint();
				}
				if (that.gridList.outType=="集装箱船"||that.gridList.outType=="汽运") {
					//箱号
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("箱号-1：" + that.gridList.boxNo);
					command.setPrint();
					//箱号
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("箱号-2：" + that.gridList.boxNoOther);
					command.setPrint();
				}else if(that.gridList.outType=="火运"){
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("车厢号-1：" + that.gridList.wingNumber);
					command.setPrint();
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("车厢号-2：" + that.gridList.wingNumberOther);
					command.setPrint();
				}else if(that.gridList.outType=="散船"){
					command.setSelectJustification(0); //居左
					command.setLeftMargin(30)
					command.setText("船次：" + that.gridList.shipNumber);
					command.setPrint();
				}

				//客户签名
				command.rowSpace(100);
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("客户签名：");
				command.setPrint();
				command.rowSpace(100);
				//收货单位签名或盖章
				command.setSelectJustification(0); //居左
				command.setLeftMargin(30)
				command.setText("收货单位签名或盖章：");
				command.setPrintAndFeed(150);
				command.setPrintAndFeedRow(8);
				that.isReceiptSend = true;
				that.prepareSend(command.getData());
			},

			//准备发送，根据每次发送字节数来处理分包数量
			prepareSend(buff) {
				console.log(buff);
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				console.log(looptime + "---" + lastData)
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//查询打印机状态
			queryStatus() {
				let command = esc.jpPrinter.Query();
				command.getRealtimeStatusTransmission(1);
			},
			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = that.Bluetooth;

				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log(res)
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {
						currentTime++
						if (currentTime <= loopTime) {
							that.currentTime = currentTime;
							that.Send(buff)
						} else {
							uni.showToast({
								title: '已打印第' + currentPrint + '张',
							})
							if (currentPrint == printNum) {
								that.looptime = 0;
								that.lastData = 0;
								that.currentTime = 1;
								that.isReceiptSend = false;
								that.isLabelSend = false;
								that.currentPrint = 1;
							} else {
								currentPrint++;
								that.currentPrint = currentPrint;
								that.currentTime = 1;
								that.Send(buff)
							}
						}
					}
				})
			},
			buffBindChange: function(res) { //更改打印字节数
				let index = res.detail.value
				let time = this.buffSize[index]
				this.buffIndex = index;
				this.oneTimeData = time;
			},
			printNumBindChange: function(res) { //更改打印份数
				let index = res.detail.value
				let num = this.printNum[index]
				this.printNumIndex = index;
				this.printerNum = num;
			},
		}
	}
</script>

<style lang="less">
	.input {
		text-align: top;
		width: 90%;
		height: 150px;
		margin-left: 4%;
		margin-right: 4%;
		margin-top: 10px;
		margin-bottom: 12px;
		border: 1px solid slategray;
	}

	.receiver_info_scroll_view {
		width: 90%;
		height: 200px;
		margin-left: 4%;
		margin-right: 4%;
		margin-top: 10px;
		margin-bottom: 25px;
		border: 1px solid black;
	}

	.result {
		width: 90%;
		height: 150px;
		border: 1px solid black;
		margin-left: 4%;
		margin-bottom: 4%;
		margin-top: 5%;
	}

	button {
		width: 90%;
		margin-left: 5%;
		margin-right: 5%;
	}

	.switch {
		float: right;
		margin-right: 20px;
		margin-bottom: 16px;
	}

	text {
		color: #fff;
		display: block;
	}

	input {
		color: gainsboro;
		float: left;
	}

	.v_net_ssid {
		width: 100%;
		background: #fff;
	}

	.v_net_passw {
		width: 100%;
		background: antiquewhite;
	}

	.swiper {
		width: 100%;
		height: 100%;
	}
	.btn{
		margin-top: 50rpx;
		background: #22C572;
	}
	uni-button[loading][type=primary] {
	    color: hsla(0,0%,100%,.6);
	    background-color: #22C572;
	}
</style>
