import {
	defineStore
} from 'pinia';
import {
	getBaseUrl
} from "../API/api";
import jpPrinter from '../components/gprint/esc';

const backgroundAudioManager = uni.getBackgroundAudioManager();

export const websocketStore = defineStore('websocket', {
	state: () => {
		return {
			isWebSocketConnected: false,
			message: [],
			orderId: '',
			isPrinting: false,
			requestQueue: new Array(),
			isAlreadyPrinting: false
		}
	},
	actions: {
		async senBlData(deviceId, serviceId, characteristicId, uint8Array) {
			let uint8Buf = Array.from(uint8Array);

			function split_array(datas, size) {
				let result = {};
				let j = 0
				for (let i = 0; i < datas.length; i += size) {
					result[j] = datas.slice(i, i + size)
					j++
				}
				return result
			}
			let sendloop = split_array(uint8Buf, 20);
			// console.log(sendloop.length)
			async function realWriteData(sendloop, i,retryCount = 3) {
				if (retryCount === 0) {
				    console.error('打印失败');
				    return;
				  }
				let data = sendloop[i]
				if (typeof(data) == "undefined") {
					return
				}
				let buffer = new ArrayBuffer(data.length)
				let dataView = new DataView(buffer)
				for (let j = 0; j < data.length; j++) {
					dataView.setUint8(j, data[j]);
				}
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId,
					value: buffer,
					success: res => {
						realWriteData(sendloop, i + 1,);
					},
					fail:err=>{
						 console.error(err);
						 realWriteData(sendloop, i, retryCount - 1); // 递减重试次数并重试
					}
				})
			}
			let i = 0;
			realWriteData(sendloop, i);
		},
		async onPrint(data) {
			console.log(data);

			this.message = data
			let command = jpPrinter.createNew()
			let deviceId = uni.getStorageSync('deviceId')
			let serviceId = uni.getStorageSync('serviceId')
			let characteristicId = uni.getStorageSync('characteristicId')
			command.init(); //初始化打印机

			command.setSelectJustification(1); //居中

			command.setCharacterSize(17); //设置倍高倍宽
			command.setText("结账单");
			command.setPrint(); //打印并换行
			command.setPrint();

			command.setCharacterSize(14); //设置倍高倍宽
			command.setText(`HD${data[0].pickupCode}`);
			command.setPrint(); //打印并换行
			command.setPrint();
			command.setCharacterSize(0); //设置正常大小

			


			command.setSelectJustification(0);
			command.setText("菜品信息:");
			command.setPrint();
			command.setText("--------------------------------");
			command.setPrint();
			command.setText('名称')
			command.setAbsolutePrintPosition(112);
			command.setText('数量');
			command.setAbsolutePrintPosition(224);
			command.setText('价格');
			command.setAbsolutePrintPosition(336);
			command.setText('规格');
			command.setPrint();
			command.setPrint();
			data[0].orderDetailsVOList.map(item => {
				command.setText(item.dishesVO.dishesName)
				command.setAbsolutePrintPosition(112);
				command.setText('x' + item.quantity);
				command.setAbsolutePrintPosition(224);
				command.setText(item.price);
				command.setAbsolutePrintPosition(336);
				command.setText(item.dishesVO.isSpecification === 1 ? item.attributeNames : '暂无');
				command.setPrint();
			})
			command.init(); //初始化打印机
			if (data[0].pickupMethod === 1) {
				command.setText("--------------------------------");
				command.setPrint();
				command.setText('打包费:')
				command.setAbsolutePrintPosition(224);
				command.setText((data[0].orderDetailsVOList.reduce((a, c) => a + c.dishesVO.packPrice, 0))
					.toFixed(2))
				command.setPrint();
				command.setText("--------------------------------");
				command.setPrint();
				command.setText('合计:')
				command.setAbsolutePrintPosition(112);
				command.setText('x' + data[0].orderDetailsVOList.reduce((a, c) => a + c.quantity, 0));
				command.setAbsolutePrintPosition(224);
				command.setText((data[0].orderDetailsVOList.reduce((a, c) => a + c.subtotal, 0) + data[0]
					.orderDetailsVOList.reduce((a, c) => a + c.dishesVO.packPrice, 0)).toFixed(2));
				command.setPrint();
				command.setPrint();
			} else {
				command.setText("--------------------------------");
				command.setPrint();
				command.setText('合计:')
				command.setAbsolutePrintPosition(112);
				command.setText('x' + data[0].orderDetailsVOList.reduce((a, c) => a + c.quantity, 0));
				command.setAbsolutePrintPosition(224);
				command.setText((data[0].orderDetailsVOList.reduce((a, c) => a + c.subtotal, 0)).toFixed(
					2));
				command.setPrint();
				command.setPrint();
			}
			command.setPrint();
			command.setPrint();
			command.setSelectJustification(0); //设置居左
			if(data[0].pickupTime!=null){
				command.setText("取餐时间:" + data[0].pickupTime);
			}
			command.setPrint(); //打印并换行
			command.setPrint();
			command.setSelectJustification(0); //设置居左
			
			command.setText("订单号:" + data[0].id);
			command.setPrint(); //打印并换行
			command.setPrint();
			
			command.setSelectJustification(0); //设置居左
			command.setText(`下单时间:${data[0].createTime.slice(0, 16).replace('T', '~')}`);
			command.setPrint(); //打印并换行
			command.setPrint();
			
			command.setSelectJustification(0); //设置居左
			
			command.setText(`支付时间:${data[0].updateTime.slice(0, 16).replace('T', '~')}`);
			command.setPrint();
			command.setPrint();
			
			command.setSelectJustification(0); //设置居左
			command.setText(`整单备注:${data[0].notes}`);
			
			command.setPrint();
			command.setPrint();
			command.setPrint();
			command.setPrint();

			this.orderId = ''; // 假设orderId用于标识当前处理的订单,用以区分不同打印任务
			this.isPrinting = false; // 确保标志位复位
			setTimeout(async () => {
				await this.senBlData(deviceId, serviceId, characteristicId, command.getData())
			}, 4000)
			backgroundAudioManager.src = 'http://110.42.248.235:866/images/static/yuyin.mp3'
			backgroundAudioManager.play()

		},
		async getMyOrders(data) {
			if (!this.requestQueue.some(req => req === data)) { // 假设data对象有id属性
				this.requestQueue.push(data);
				if (!this.isPrinting) {
					await this.processQueue();
				}
			} else {
				console.warn('订单已存在');
			}

		},
		async processQueue() {
			while (this.requestQueue.length > 0) {
				this.isPrinting = true;
				const data = this.requestQueue.shift()
				console.log(data)
				try {
					const res = await uni.request({
						url: getBaseUrl() + '/orders/my/page',
						method: 'POST',
						data: {
							id: data
						},
						header: {
							'cookie': uni.getStorageSync('cookie')
						},
					});
					console.log(res)
					if (res.data.code === 1) {
						this.message = res.data.data.records;
						await this.onPrint(res.data.data.records);
					} else {
						console.error('请求失败,状态码:', res.data.code);
					}
				} catch (error) {
					console.error('获取订单时发生错误:', error);
				} finally {
					this.isPrinting = false;
					// 处理完当前请求后,检查队列是否还有剩余请求
					if (this.requestQueue.length > 0) {
						// 继续处理队列
						await this.processQueue();
					}
				}
			}
		},
	}
})