<template>
	<view>
		<u-navbar :title="headline" autoBack placeholder></u-navbar>
		<view class="card_stamp">
			<view class="title_bluetooth">匹配蓝牙设备</view>
			<view class="center_in">
				<x-radar :BlueState="BlueState"></x-radar>
			</view>
			<view class="nearby_title">{{nearbyTitle}}</view>
			<view class="search_card">
				<u-button style="width: 200rpx;" size="small" type="warning" :text="searchTitle"
					@click="openBluetoothAdapter(searchType)"></u-button>
			</view>
			<view class="space_between">
				<view class="waybill_num">运单号: {{waybillNo}}</view>
			</view>
			<view class="waybill_numil" v-if="printType == 'record'">请选择运单温湿度时间段</view>
			<view class="card_waybill" v-for="(item,index) in timeQuantumList" :key="index" @click="selectChange(item)">
				<x-checkbox :label="item.title" :isChecked="item.isChecked"></x-checkbox>
				<view class="time_title">{{item.startTime}}</view>
				<view class="time_title">{{item.endTime}}</view>
			</view>
			<view class="card_bluetooth" v-if="pairedDeviceList.length > 0">
				<view class="equipment_title">已配对设备</view>
				<view class="card_equipment">
					<x-bluetooth :list="pairedDeviceList" text="打印" btnType="success" @connect="getPrint"></x-bluetooth>
				</view>
			</view>
			<view class="card_bluetooth">
				<view class="equipment_title">可连接设备</view>
				<view class="card_equipment">
					<x-bluetooth :list="devices" @connect="connect"></x-bluetooth>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		printList
	} from './waybill.js'
	import PrinterJobs from './gprint/printerjobs.js'
	import printerUtil from './gprint/printerutil.js'
	import util from './gprint/util.js'
	import drawQrcode from './gprint/weapp.qrcode.esm.js'
	import getCode128 from './gprint/code128'
	export default {
		data() {
			return {
				headline: '',
				barCodeShow: false,
				pairedDeviceList: [],
				matchingUnit: {},
				BlueState: true,
				nearbyTitle: '使用蓝牙设备打印...',
				searchTitle: '开始搜索',
				searchType: false,
				devices: [],
				deviceId: null,
				serviceId: null,
				characteristicId: null,
				waybillNo: '',
				printType: '',
				waybillList: {},
				humitureData: [],
				maxData: [],
				timeQuantumList: [],
				checkboxValue: [],
				userInfo: {},
			}
		},
		onLoad(value) {
			const arr = this.$cache.getCache('commodity')
			this.waybillList = JSON.parse(arr)
			var userInfo = this.$cache.getCache('userInfo')
			this.userInfo = userInfo
			if (value.printType == 'barCode') {
				this.headline = '条码打印'
			} else if (value.printType == 'record') {
				this.headline = '温湿度记录打印'
				this.getHumiture(value.waybillNo)
			}
			this.waybillNo = value.waybillNo
			this.printType = value.printType
		},
		methods: {
			openBluetoothAdapter(value) {
				var that = this
				if (value) {
					that.BlueState = true
					that.searchTitle = '开始搜索'
					that.nearbyTitle = '已停止蓝牙查找附近设备...'
					that.searchType = false
				} else {
					that.BlueState = false
					console.log('开始搜索')
					that.searchTitle = '停止搜索'
					that.nearbyTitle = '正通过蓝牙查找附近设备...'
					that.searchType = true
					uni.openBluetoothAdapter({ //打开蓝牙适配器接口
						success: (res) => { //已打开
							that.onDevice() //监听寻找到新设备的事件
							uni.getBluetoothAdapterState({ //获取本机蓝牙适配器状态
								success: function(res) {
									// console.log(res)
									if (res.available) {
										//搜索蓝牙
										//开始搜寻附近的蓝牙外围设备
										console.log("开始搜寻附近的蓝牙外围设备")
										uni.startBluetoothDevicesDiscovery({
											success(res) {
												console.log(res)
											}
										})

									} else {
										console.log('本机蓝牙不可用')
									}
								},
							})
						},
						fail: err => { //未打开 
							uni.showToast({
								icon: 'none',
								title: '查看手机蓝牙是否打开'
							});
						}
					})
				}
			},
			onDevice() {
				var that = this
				//监听寻找到新设备的事件
				uni.onBluetoothDeviceFound(function(devices) {
					var re = JSON.parse(JSON.stringify(devices))
					if (re.devices[0].name != '') {
						let deviceId = re.devices[0].deviceId
						let name = re.devices[0].name
						that.devices.push({
							name: name,
							deviceId: deviceId,
							services: []
						})

						for (let i = 0; i < that.devices.length; i++) {
							for (let j = i + 1; j < that.devices.length; j++) {
								if (that.devices[i].deviceId == that.devices[j].deviceId) {
									that.devices.splice(j, 1);
									j--;
								}
							}
						}
						that.devices = that.devices
					}
				})
			},
			stopFindBule() {
				const that = this
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						that.searchTitle = '开始搜索'
						that.nearbyTitle = '已停止蓝牙查找附近设备...'
						that.searchType = false
						that.BlueState = true
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			connect(value) {
				// console.log(value, 66)
				this.createBLEConnection(value)
			},
			// item 是要连接的设备数据
			createBLEConnection(item) {
				let that = this;
				that.matchingUnit.deviceId = item.deviceId
				uni.showLoading({
					title: "连接中，请稍等",
					mask: true,
				});
				uni.createBLEConnection({
					deviceId: item.deviceId,
					success(res) {
						that.stopFindBule(); // 停止搜索蓝牙
						setTimeout(function() {
							that.getBLEDeviceServices(item); // 获取蓝牙的服务
						}, 2000)
					},
					fail(res) {
						uni.showToast({
							title: item.name + "蓝牙连接失败",
							icon: "none",
						});
						uni.hideLoading()
					}
				});
			},
			getBLEDeviceServices(item) {
				const that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: item.deviceId,
						complete(res) {
							let serviceId = ""
							if (res.services.length > 0) {
								for (var s = 0; s < res.services.length; s++) {
									let serviceId = res.services[s].uuid
									that.matchingUnit.serviceId = serviceId
									uni.getBLEDeviceCharacteristics({ //获取蓝牙设备某个服务中所有特征值(characteristic)
										// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
										deviceId: item.deviceId,
										// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
										serviceId: serviceId,
										success(res) {
											// console.log('获取服务成功')
											that.pairedDeviceList = []
											that.pairedDeviceList.push(item)
											var re = JSON.parse(JSON.stringify(res))
											for (var c = 0; c < re.characteristics.length; c++) {
												if (re.characteristics[c].properties.write ==
													true) {
													let uuid = re.characteristics[c].uuid
													that.matchingUnit.characteristicId = uuid
													break
												}
											}
											uni.hideLoading()
										}
									})
								}
							} else {
								uni.hideLoading()
							}
						},
						fail(res) {
							console.log(res)
						},
					})
				});
			},
			// 断开连接
			closeBLEConnection(item) {
				uni.closeBLEConnection({
					deviceId: item.deviceId,
					success: (res) => {
						// res.characteristics 特征值列表
						// 读写都需要用到特征值
					},
					fail: (res) => {
						console.log(res);
					},
				})
			},
			// 配对设备打印
			async getPrint(value) {
				this.deviceId = this.matchingUnit.deviceId
				this.serviceId = this.matchingUnit.serviceId
				this.characteristicId = this.matchingUnit.characteristicId
				if (this.printType == 'barCode') {
					const showFirstName = (name) => {
						let newStr;
						if (name.length === 2) {
							newStr = name.substr(0, 1) + '*';
						} else if (name.length > 2) {
							let char = '';
							for (let i = 0, len = name.length - 1; i < len; i++) {
								char += '*';
							}
							newStr = name.substr(0, 1) + char;
						} else {
							newStr = name;
						}
						return newStr;
					}
					const shippingAddress = (addres) => {
						let title;
						if (addres.length < 16) {
							title = addres + ' \n'
						} else {
							title = addres
						}
						return title
					}
					let printerJobs = new PrinterJobs();
					let codeValue = this.waybillNo
					const ENV = require('../../.env.js')
					let logistics = ENV.APP_LINK_URL + '/newInquiry?waybillNo=' + codeValue
					let code128 = getCode128(codeValue);
					let numArr = []
					if (this.waybillList.quantity != 0) {
						for (var i = 0; i < this.waybillList.quantity; i++) {
							let numa = i + 1
							numArr.push(numa)
						}
					} else {
						let numa = 1
						numArr.push(numa)
					}
					numArr.forEach((numitem, indexnum) => {
						printerJobs
							.setSize(1, 1)
							.setAlign('LT')
							.print('#' + this.userInfo.dept.name)
							.setAlign('CT')
							.printBarcode(code128)
							.setSize(1, 1)
							.setAlign('LT')
							.text('  ')
							.text(codeValue + ' \n')
							.print(printerUtil.fillLine())
							.setAlign('LT')
							.setSize(1, 2)
							.setSize(2, 1)
							.setBold()
							.text('收:')
							.setSize(1, 1)
							.setBold(false)
							.text(' ' + showFirstName(this.waybillList.senderAddressName))
							.text(' ' + this.waybillList.senderAddressPhone.substr(0, 3) + "****" + this
								.waybillList
								.senderAddressPhone.substr(7) + ' \n')
							.print(shippingAddress(this.waybillList.senderAddressDetails))
							.print(printerUtil.fillLine())
							.setSize(1, 2)
							.setSize(2, 1)
							.setBold()
							.text('寄:')
							.setSize(1, 1)
							.setBold(false)
							.text(' ' + showFirstName(this.waybillList.consigneeAddressName))
							.text(' ' + this.waybillList.consigneeAddressPhone.substr(0, 3) + "****" + this
								.waybillList
								.consigneeAddressPhone.substr(7) + ' \n')
							.print(shippingAddress(this.waybillList.consigneeAddressDetails))
							.print(printerUtil.fillLine())
							.text('备注:')
							.text('防拆标签码：' + this.waybillList.tamperProofLabel + ' \n')
							.setAlign('CT')
							.printQrcode(logistics)
							.print('扫码查询物流温湿度信息 \n')
							.println()
					})
					let buffer = printerJobs.buffer();
					this.printbuffs(buffer);
				} else {
					let printerJobs = new PrinterJobs();
					printerJobs
						.setSize(1, 1)
						.setAlign('lt')
						.print('#' + this.userInfo.dept.name)
						.print('运单号：' + this.waybillNo)
						.print('货物类型：' + this.waybillList.cargoType)
						.print('温度需求：' + this.waybillList.temperatureInterval)
						.print('配送要求：' + this.waybillList.deliveryCondition)
						.print('寄件人：' + this.waybillList.senderAddressName)
						.print('收件人：' + this.waybillList.consigneeAddressName)
						.print(printerUtil.fillLine())
					this.humitureData.forEach((item, index) => {
						// console.log(item,123)
						const exists = this.checkboxValue.some(Tid => Tid === item.id);
						if (item.isChecked) {
							// printerJobs
							// .print('设备号：' + item.sn)
							// .print('标识名：' + item.title)
							// .print('开始时间：' + item.startTime)
							// .print('结束时间：' + item.endTime)
							// .print(printerUtil.fillLine())
							item.arr.forEach((item1, index1) => {
								printerJobs
									.print('日期:' + item1.time + '单位℃ ')
									.text('时间 ')
									.text('|')
									.text(' ')
									.text('T1  ')
									.text(' ')
									.text('|')
									.text(' ')
									.text('T2  ')
									.text(' ')
									.text('|')
									.text(' ')
									.text('T3  ')
									.text(' ')
									.text('|')
									.text(' ')
									.text('T4  \n')
								item1.arr.forEach((item2, index2) => {
									printerJobs
										.text(`${item2[0].time}`)
										.text('|')
										.text(' ')
										.text(
											`${item2[0] == '---' ? '----' : character(item2[0].T_t) }`
										)
										.text(' ')
										.text('|')
										.text(' ')
										.text(
											`${item2[1] == '---' ? '----' : character(item2[1].T_t) }`
										)
										.text(' ')
										.text('|')
										.text(' ')
										.text(
											`${item2[2] == '---' ? '----' : character(item2[2].T_t) }`
										)
										.text(' ')
										.text('|')
										.text(' ')
										.text(
											`${item2[3] == '---' ? '----' : character(item2[3].T_t) }`
										)

									function character(value) {
										var arr = value.toFixed(1)
										if (arr.length == 3) {
											var arr1 = arr + ' '
											return arr1
										} else {
											return arr
										}
									}
								})
							})
							// printerJobs.println()
						}
					})
					printerJobs.println()
					let buffer = printerJobs.buffer();
					this.printbuffs(buffer);
				}
			},
			printbuffs(buffer) {
				// 1.并行调用多次会存在写失败的可能性
				// 2.建议每次写入不超过20字节
				// 分包处理，延时调用
				const maxChunk = 20;
				const delay = 20;
				for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
					let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
					setTimeout(this.printbuff, j * delay, subPackage);
				}
			},
			printbuff(buffer) {
				let deviceId = this.deviceId;
				let serviceId = this.serviceId;
				let characteristicId = this.characteristicId;
				// console.log(deviceId, serviceId, characteristicId, 333)
				return new Promise((resolve, reject) => {
					uni.writeBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId,
						value: buffer,
						success(res) {
							//console.log('message发送成功', JSON.stringify(res));
							resolve(res);
						},
						fail(err) {
							console.log('message发送失败', JSON.stringify(err));
							reject(err);
						}
					});
				});
			},
			// 获取设备信息探头
			getHumiture(waybillNo) {
				this.checkboxValue = []
				this.$api.get('/api/waybill-task', {
					waybillNo: waybillNo,
				}).then(res => {
					if (res.code == 200) {
						const arrlsist = res.data.list
						let arrList = []
						arrlsist.forEach((item, index) => {
							let dataList = {}
							dataList.id = item.id
							dataList.sn = item.sn
							dataList.deviceSensorList = item.deviceSensorList
							dataList.startTime = item.startTime
							dataList.endTime = item.endTime
							if (item.car.id) {
								dataList.title = item.car.carNo
							} else if (item.warehouse.id) {
								dataList.title = item.warehouse.name
							}
							arrList.push(dataList)
						})
						this.timeQuantumList = arrList
						this.timeQuantumList.forEach((item1, index1) => {
							item1.isChecked = true
							this.checkboxValue.push(item1.id)
						})
						this.humitureInfo(arrList)
					}
				})
			},
			// 选择打印
			selectChange(value) {
				this.timeQuantumList.forEach((item, index) => {
					if (value.id == item.id) {
						if (value.isChecked) {
							item.isChecked = false
						} else {
							item.isChecked = true
						}
					}
					if (item.isChecked) {
						this.checkboxValue = []
						this.checkboxValue.push(item.id)
					}
				})
				// console.log(this.humitureData,'------')
				this.$forceUpdate()
			},
			// 获取温湿度信息
			humitureInfo(value) {
				// console.log(printList(), 2666)
				// console.log(value, 25)
				let arrData = value
				let arrData1 = printList()
				arrData.forEach((item, index) => {
					let arr = []
					item.deviceSensorList.forEach((ote, te) => {
						arr.push(ote.T_id)
					})
					let params = {
						t_ids: arr,
						taskId: item.id,
						waybillNo: this.waybillNo,
						page: 1,
						pageSize: 9999,
					}
					// console.log(item,999)
					item.arr = []
					this.getWaybillTask(params).then(res => {
						const arrL = JSON.parse(JSON.stringify(res))
						const timeList = JSON.parse(JSON.stringify(res))
						const arrLil = res
						for (let i = 0; i < arrLil.length; i++) {
							for (let j = i + 1; j < arrLil.length; j++) {
								if (arrLil[i].T_time == arrLil[j].T_time) {
									arrLil.splice(j, 1);
									j--;
								}
							}
						}
						var resultArr = arrLil
						let list1 = []
						resultArr.forEach(k => {
							let arr1 = {
								T_sn: k.T_sn,
								time: k.T_time,
								arr: [],
							}
							list1.push(arr1)
						})
						this.maxData = list1
						for (let i = 0; i < timeList.length; i++) {
							for (let j = i + 1; j < timeList.length; j++) {
								if (timeList[i].time == timeList[j].time) {
									timeList.splice(j, 1);
									j--;
								}
							}
						}
						this.maxData.forEach((item3, index3) => {
							timeList.forEach((item2, index2) => {
								const result1 = arrL.find(fruit => fruit.T_id === 1 &&
									fruit.time === item2.time && fruit.T_time === item3
									.time)
								const result2 = arrL.find(fruit => fruit.T_id === 2 &&
									fruit.time === item2.time && fruit.T_time === item3
									.time)
								const result3 = arrL.find(fruit => fruit.T_id === 3 &&
									fruit.time === item2.time && fruit.T_time === item3
									.time)
								const result4 = arrL.find(fruit => fruit.T_id === 4 &&
									fruit.time === item2.time && fruit.T_time === item3
									.time)

								const flag = areAllUndefined(result1, result2, result3,
									result4)
								if (!flag) {
									let list2 = [
										result1 == undefined ? '---' : result1,
										result2 == undefined ? '---' : result2,
										result3 == undefined ? '---' : result3,
										result4 == undefined ? '---' : result4,
									]
									item3.arr.push(list2)
								}

								function areAllUndefined(...args) {
									return args.every(arg => arg === undefined);
								}
							})
						})
						item.arr = this.maxData
					})
				})
				this.humitureData = arrData
				// console.log(this.humitureData, 26)
			},
			getWaybillTask(params) {
				return new Promise((resolve, reject) => {
					this.$api.post('/api/waybill-task/data', params).then(res => {
						if (res.code == 200) {
							let arr1 = res.data.list
							if (arr1) {
								let arr2 = []
								arr1.forEach(item1 => {
									const dateString = item1.T_time;
									const parts = dateString.split(" ")[0].split("-");
									const extractedDate = parts[0] + "-" + parts[1] + "-" + parts[
										2];
									const parts1 = dateString.split(" ")[1].split(":");
									const extractedTime = parts1[0] + ":" + parts1[1];
									let arr3 = {
										T_sn: item1.T_sn,
										T_id: item1.T_id,
										T_time: extractedDate,
										T_t: item1.T_t,
										T_rh: item1.T_rh,
										time: extractedTime
									}
									arr2.push(arr3)
								})
								resolve(arr2)
							}
						}
					})
				});
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.title_bluetooth {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 40rpx;
		margin: 20rpx;
		font-weight: 600;
	}

	.nearby_title {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		margin: 20rpx;
		font-weight: 600;
	}

	.card_stamp {
		display: flex;
		flex-direction: column;
		padding: 30rpx 20rpx;
	}

	.search_card {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.card_bluetooth {
		margin-top: 20rpx;
	}

	.equipment_title {
		font-size: 28rpx;
		font-weight: 600;
	}

	.card_equipment {
		margin-top: 20rpx;
		min-height: 90rpx;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.1);
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}

	.waybill_num {
		margin-top: 20rpx;
		font-size: 30rpx;
		font-weight: 600;
	}

	.waybill_numil {
		margin-top: 10rpx;
		font-size: 28rpx;
		color: #767a82;
	}

	.time_title {
		margin-top: 5rpx;
		font-size: 28rpx;
	}

	.card_waybill {
		display: flex;
		flex-direction: column;
		box-shadow: 1rpx 2rpx 14rpx rgba(0, 0, 0, .12);
		padding: 20rpx;
		border-radius: 10rpx;
		margin-top: 20rpx;
	}
</style>