<template>
	<view>
		<view class="status_bar"><!-- 这里是状态栏 --></view>
		<uni-nav-bar title="标签打印">
			<template v-slot:right>
				<text @click="signOut" style="margin-right: 20rpx;">退出</text>
			</template>
		</uni-nav-bar>
		<view class="app-container">
			<!-- 打印机 -->
			<view class="uni-list">
				<view class="uni-list-cell">
					<view class="uni-list-cell-left">打印机</view>
					<view class="uni-list-cell-db">
						<picker
							mode="selector"
							:value="index"
							:range="printerList"
							@change="onPrinterChanged"
						>
							<view class="uni-input">{{ printerList[index] }}</view>
						</picker>
					</view>
				</view>
			</view>
			<view v-for="(item, i) in orderList" :key="item.id" class="content">
				<view class="order-list">
					<view class="order-top">
						<text style="font-weight: 500; width: 74%;" @click="clickStatus(item.id)">
							订单编号：{{ item.orderSn }}
						</text>
						<view class="botton" @click="generateSerial(item.id)">生成序列号</view>
					</view>
					<view
						v-show="qr.orderId === item.id && status"
						v-for="(qr, index) in qrcodeData"
						:key="qr.id"
					>
						<view class="order-center">
							<view>
								<text style="margin-right: 26rpx;">序列号：</text>
								<text>{{ qr.sequenceCode }}</text>
							</view>
							<view>
								<text style="margin-right: 54rpx;">密码：</text>
								<text>{{ qr.sequenceCodePassword }}</text>
							</view>
							<view>
								<text style="width: 60rpx;">创建时间：</text>
								<text>{{ qr.createTime }}</text>
							</view>
						</view>
						<view class="order-bottom">
							<view class="botton" @click="printQrcode(index)">打印二维码</view>
						</view>
					</view>
				</view>
			</view>
			<view style="width: 100%; height: 160rpx;"></view>
			<view class="footer">
				<button type="primary" size="mini" @click="openPrinter()">连接打印机</button>
				<button type="default" size="mini" @click="closePrinter()">断开打印机连接</button>
			</view>
		</view>
	</view>
</template>

<script>
const modal = uni.requireNativePlugin('modal');
import api from './lpapi-uniplugin';
export default {
	data() {
		return {
			title: '',
			printerList: [],
			index: 0,
			printerName: '',
			baseUrl: 'https://maoshanjiufang.gzmsjf.com',
			qrcodeData: [],
			orderList: [],
			noClick: true,
			status: true,
		};
	},
	async onLoad() {
		this.initOrder();
		this.printerList.splice(0);
		const list = await api.getPrinters();
		if (list.length > 0) {
			for (let item of list) {
				this.printerList.push(item.name);
			}
		} else {
			this.printerList.push('未检测到打印机');
		}
		// 自动连接打印机
		this.onPrinterChanged();
	},
	computed: {
		baseQrcodeUrl: function() {
			return this.baseUrl + '/wx/storage/fetch/';
		},
	},
	methods: {
		initOrder() {
			uni.request({
				url: this.baseUrl + '/wx/order/list',
				method: 'GET',
				header: { 'X-Litemall-Token': uni.getStorageSync('token') },
				success: res => {
					this.orderList = res.data.data.list;
				},
			});
		},
		onPrinterChanged(e) {
			this.index = e ? e.target.value : 0;
			this.printerName = this.printerList[this.index];
		},
		clickStatus(id) {
			if (this.qrcodeData.length == 0) return;
			if (id == this.qrcodeData[0].orderId) {
				this.status = !this.status;
			}
		},
		getPrinterName() {
			let name = '';
			if (this.printerList && this.printerList.length > 0) {
				name = this.printerList[0].name;
			}
			if (!name) {
				modal.toast({
					message: '未检测到打印机',
					duration: 1.5,
				});
			}
			return name;
		},
		async openPrinter() {
			console.log(this.printerName, 'this.printerName');
			if (this.printerName) {
				// 连接新的打印机
				api.openPrinter(this.printerName, value => {
					if (value) {
						modal.toast({
							message: '打印机连接成功',
							duration: 1.5,
						});
					}
				});
			}
		},
		closePrinter() {
			api.closePrinter();
			modal.toast({
				message: '打印机已断开',
				duration: 1.5,
			});
		},
		// 生成序列号
		generateSerial(id) {
			uni.showLoading({
				title: '加载中...',
			});
			uni.request({
				url: this.baseUrl + `/wx/orderSequence/createCode/${id}`,
				success: res => {
					if (res.data.erron === 0) {
						this.status = true;
						this.initOrderSequence(id);
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: res.data.errmsg,
							icon: 'none',
						});
					}
				},
				fail() {
					uni.showToast({
						title: '获取数据失败',
						icon: 'none',
					});
				},
			});
		},
		initOrderSequence(id) {
			uni.request({
				url: this.baseUrl + `/wx/orderSequence/getOrderSequence/${id}`,
				success: res => {
					if (res.data.errno == 0) this.qrcodeData = res.data.data;
				},
			});
		},
		// 打印二维码
		async printQrcode(index) {
			if (!this.qrcodeData[index])
				return uni.showToast({
					title: '请生成序列号',
					icon: 'none',
				});
			let that = this;
			if (that.noClick) {
				that.noClick = false;
				// 执行函数
				const data = that.baseQrcodeUrl + that.qrcodeData[index].qrCodeSource;
				const width = 20;
				const height = 30;
				const imgHeight = 18;
				const textHeight = 25.5;
				const lineHeight = 4;
				const lineHeight1 = 3;
				const fontSize = 3;
				const text =
					that.qrcodeData[index].sequenceCode.split('-')[1] +
					'-' +
					that.qrcodeData[index].sequenceCodePassword;
				const textCode = that.qrcodeData[index].sequenceCode;
				// const pwdText = '密码:' + this.qrcodeData[0].sequenceCodePassword;

				// 第一步，先判断打印机是否已经打开
				if (await api.isPrinterOpened()) {
					await api.startJob({ width, height });
					// 图片
					await api.drawImage({
						x: 0,
						y: 0.5,
						image: data,
						width: width,
						height: imgHeight,
					});
					// 水平居中
					await api.setItemHorizontalAlignment({ alignment: 1 });
					// 字符串
					await api.drawText({
						text: textCode,
						x: 0,
						y: 18,
						width: width,
						height: lineHeight1,
						fontHeight: fontSize,
						fontStyle: 1,
					});

					// 水平居中
					await api.setItemHorizontalAlignment({ alignment: 1 });

					// 字符串
					await api.drawText({
						text: text,
						x: 0,
						y: textHeight,
						width: width,
						height: lineHeight,
						fontHeight: fontSize,
						fontStyle: 1,
					});

					// 水平居中
					await api.setItemHorizontalAlignment({ alignment: 1 });
					await api.commitJob();
				}
				setTimeout(() => {
					that.noClick = true;
				}, 2000);
			} else {
				// 重复点击
				uni.showToast({
					title: '二维码打印中...',
					duration: 2000,
					icon: 'none',
				});
			}
			// if (this.qrcodeData[index]) {
			// } else {
			// 	uni.showToast({
			// 		icon: 'none',
			// 		title: '请生成序列号'
			// 	});
			// }
		},
		// 退出app
		signOut() {
			uni.showModal({
				content: '确认退出？',
				success(res) {
					if (res.confirm) {
						if (uni.getSystemInfoSync().platform == 'ios') {
							uni.clearStorage();
							plus.ios
								.import('UIApplication')
								.sharedApplication()
								.performSelector('exit');
						} else if (uni.getSystemInfoSync().platform == 'android') {
							uni.clearStorage();
							plus.runtime.quit();
						}
					}
				},
			});
		},
		// // 节流
		// throttle: function(fn, delay) {
		// 	let timer = true;
		// 	return function(args) {
		// 		let that = this;
		// 		let _args = arguments;
		// 		if(!timer){
		// 		   return false;
		// 		}
		// 		timer = false;
		// 		setTimeout(() => {
		// 			fn.apply(that, _args)
		// 			timer = true;
		// 		}, delay)
		// 	}
		// },
		// closesss: throttle(function() {
		// 	console.log('454');
		// },200)
	},
};
</script>

<style lang="scss" scoped>
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}
.app-container {
	margin: 20px auto;
	width: 80%;

	.uni-list {
		margin-bottom: 20rpx;
	}

	.content {
		.order-list {
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			border: 1px solid #ccc;
			border-radius: 8rpx;
			.order-top {
				box-sizing: border-box;
				width: 100%;
				height: 70rpx;
				border-bottom: 1px solid #ccc;
				padding: 10rpx 20rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.botton {
					width: 26%;
					height: 80%;
					border-radius: 28rpx;
					background-color: #007aff;
					font-size: 12px;
					text-align: center;
					line-height: 40rpx;
					margin-right: 20rpx;
					color: #fff;
				}
			}
			.order-center {
				width: 100%;
				display: flex;
				flex-direction: column;
				padding: 0 40rpx;
			}
			.order-bottom {
				box-sizing: border-box;
				width: 100%;
				height: 70rpx;
				border-top: 1px solid #ccc;
				border-bottom: 1px solid #ccc;
				padding: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				.botton {
					width: 150rpx;
					height: 80%;
					border-radius: 28rpx;
					background-color: #ee9f3a;
					font-size: 12px;
					text-align: center;
					line-height: 40rpx;
					margin-right: 20rpx;
				}
			}
			// .order-bottom:nth-last-child(1) {
			// 	border-bottom: none;
			// }
		}
	}

	.footer {
		position: fixed;
		bottom: 30rpx;
		margin: 0 auto;
		width: 80%;
		box-sizing: border-box;
		text-align: center;
		button {
			margin-right: 10px;
		}
	}
}
</style>
