<template>
	<view class="container">
		<view class="wifiListBox">
			<view>扫描附近设备</view>
			<view style="font-size: 24rpx;color: #696D70">持续自动搜索中...</view>
			<view class="wifiList" v-for="(device, index) in devices" :key="index" @click="connectToDevice(device.deviceId)">
				<view>{{ device.name }}</view>
				<view>({{ device.deviceId }})</view>
			</view>
			<view style="font-size: 24rpx;color: #696D70;padding-top: 30rpx;">请打开蓝牙并将手机尽量靠近要添加的设备</view>
		</view>
		<view @tap="WiFiBoxopen">
			传输文件
		</view>

		<u-popup :show="showWiFiBox" mode='center' border-radius='14'>
			<view class="wifiBox">
				<view style="font-size: 24rpx;color: #696D70;">请输入当前WIFI的名称和密码...</view>
				<view class="faildLis">
					<view>wifi名称：</view>
					<view><input type="text" v-model="wifiName" placeholder="请输入wifi名称"></view>
				</view>
				<view class="faildLis">
					<view>wifi密码：</view>
					<view><input type="text" v-model="wifiPassword" placeholder="请输入wifi密码"></view>
				</view>
				<view class="wifiBtnBox">
					<view @click="showWiFiBox = false">取消</view>
					<view @click="sendData()">确认</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			devices: [],
			deviceId: '',
			serviceId: '',
			characteristicId: '',
			wifiName: '',
			wifiPassword: '',
			showWiFiBox: false,
		};
	},
	onLoad() {
		this.openBluetoothAdapter(); // 初始化蓝牙
		
		// 这里是获取wifi信息的
		uni.startWifi({
			success:(result) => {
				console.log(result)
				uni.getConnectedWifi({
					success: (res) => {
						console.log(res)
						this.wifiName = res.wifi.SSID
					},
					fail: (err) => {
						console.log('获取Wi-Fi信息失败', err);
					}
				});
			},
			fail: (err) => {
				console.log('start - Wi-Fi信息失败', err);
			}
		})
	},
	methods: {
		WiFiBoxopen(){
			console.log(this.showWiFiBox)
			this.showWiFiBox = true	
			console.log(this.showWiFiBox)
		},
		// 初始化蓝牙
		openBluetoothAdapter() {
			uni.openBluetoothAdapter({
				success: () => {
					console.log('蓝牙适配器初始化成功');
					this.startScan(); // 开始扫描设备
				},
				fail: (err) => {
					console.error('蓝牙适配器初始化失败:', err);
					uni.showModal({
						title: '错误',
						content: '蓝牙初始化失败，请确保蓝牙开启并重试',
						showCancel: false,
					});
				},
			});
		},

		// 扫描蓝牙设备
		startScan() {
			this.devices = [];
			uni.startBluetoothDevicesDiscovery({
				success: () => {
					console.log('开始扫描蓝牙设备');
					this.listenForDevices();
				},
				fail: (err) => {
					console.error('扫描蓝牙设备失败:', err);
				},
			});
		},

		// 监听扫描到的设备
		listenForDevices() {
			uni.onBluetoothDeviceFound((devices) => {
				devices.devices.forEach((device) => {
					const deviceName = device.name || device.localName;
					// console.log(deviceName)
					// 这里监听 蓝牙名称中包含 Paper 的 所有列表 也可去掉 看自己的需求
					if (deviceName && deviceName.includes('Paper')) {
					// if (deviceName.includes('Paper') || deviceName.includes('EDIFIER') || deviceName) {
						const exists = this.devices.some((d) => d.deviceId === device.deviceId);
						if (!exists) {
							this.devices.push({
								name: deviceName,
								deviceId: device.deviceId,
							});
						}
					}
				});
			});
		},

		// 连接蓝牙设备
		connectToDevice(deviceId) {
			let that = this;
			uni.showLoading({ title: '正在连接...', mask: true });
			uni.createBLEConnection({
				deviceId,
				success: () => {
					this.deviceId = deviceId;
					uni.showToast({ title: '设备连接成功', icon: 'none' });
					
					
					 uni.getConnectedBluetoothDevices({
						success(res) {
						  // 获取设备的服务和特征值
						  that.getServices(deviceId); // 获取设备服务
						},
						fail(err) {
						  console.error("获取连接设备失败：", err);
						},
					});
					
					
				},
				fail: (err) => {
					console.error('设备连接失败:', err);
					uni.hideLoading();
					uni.showModal({ title: '连接失败', content: '无法连接到设备', showCancel: false });
				},
			});
		},

		// 获取服务
		getServices(deviceId) {
			console.log(deviceId,"deviceId")
  setTimeout(()=>{
			uni.getBLEDeviceServices({
				deviceId,
				success: (res) => {
					console.log('获取服务成功:', res);
					this.serviceId = res.services[0].uuid; // 假设取第一个服务
					this.getCharacteristics();
				},
				fail: (err) => {
					console.error('获取服务失败:', err);
				},
			});
  }, 2000)

		},

		// 获取特征值
		getCharacteristics() {
			uni.getBLEDeviceCharacteristics({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				success: (res) => {
					console.log('获取特征值成功:', res);
					console.log('获取特征值成功:', res.characteristics);
					const notifyCharacteristic = res.characteristics.find(
						(char) => char.properties.notify || char.properties.indicate
					);
					const writeCharacteristic = res.characteristics.find(
						(char) => char.properties.write || char.properties.writeWithoutResponse
					);
					if (writeCharacteristic && notifyCharacteristic) {
						this.characteristicId = writeCharacteristic.uuid;
						console.log('找到支持写入的特征值:', this.characteristicId);
						this.enableNotify(notifyCharacteristic.uuid); // 启用通知
					} else {
						uni.showModal({ title: '错误', content: '未找到支持写入或通知的特征值', showCancel: false });
					}
				},
				fail: (err) => {
					console.error('获取特征值失败:', err);
				},
			});
		},

		// 启用通知
		enableNotify(notifyCharacteristicId) {
			uni.notifyBLECharacteristicValueChange({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId: notifyCharacteristicId,
				state: true, // 开启通知
				success: () => {
					console.log('通知已启用');
					this.startListeningForResponse(); // 开始监听返回数据
				},
				fail: (err) => {
					console.error('启用通知失败:', err);
				},
			});
		},

		// 构建数据包
		buildConnectionRequest() {
			// 这里生成发送数据的格式参数   根据不同的文档进行修改   这里只是示例 ！！！
			const protocolHeader = [0x11]; // 协议头
			const command = [0x11]; // CMD：发起连接请求
			const dataLength = [0x00]; // 数据长度
			const crc = this.calculateCRC([...protocolHeader, ...command, ...dataLength]);
			return new Uint8Array([...protocolHeader, ...command, ...dataLength, crc]).buffer;
		},
		// 发送数据
		sendData() {
			const data = this.buildConnectionRequest(); // 构建连接请求数据
			uni.writeBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId: this.characteristicId,
				value: data,
				success: () => {
					console.log('数据发送成功');
				},
				fail: (err) => {
					console.error('数据发送失败:', err);
				},
			});
		},
		stringToUint8Array(str) {
		    const utf8 = unescape(encodeURIComponent(str)); // 将字符串转换为 UTF-8 编码
		    const uint8Array = new Uint8Array(utf8.length);
		    for (let i = 0; i < utf8.length; i++) {
		        uint8Array[i] = utf8.charCodeAt(i);
		    }
		    return uint8Array;
		},
	    
		// 监听设备返回
		startListeningForResponse() {
		    console.log("监听返回数据");
		    uni.onBLECharacteristicValueChange((res) => {
		        const response = new Uint8Array(res.value);
		        console.log('收到设备返回的数据:', response);

		    });
		    console.log("设备监听已设置");
		},


		
		// 验证 CRC 的方法
		validateCRC(response) {
		    const data = response.slice(0, response.length - 1); // 去掉 CRC 字节
		    const receivedCRC = response[response.length - 1]; // 设备返回的 CRC
		    const calculatedCRC = this.calculateCRC(data); // 重新计算 CRC
		    return receivedCRC === calculatedCRC; // 比较 CRC 是否一致
		},
		
		// 改进后的 CRC 计算方法
		calculateCRC(data) {
		    return data.reduce((acc, curr) => (acc + curr) % 256, 0); // 模 256 加和
		},
		
		// 这个是不同方式的配网  根据文档来 下面的这个是 发送json格式的数据  并且需要分块发送   也可以参考这个方式
	// 	sendData() {
	// 		this.bindClient()
	// 		this.inputData = '{"ssid":"' + this.wifiName + '","password":"' + this.wifiPassword + '","clientid":"' +
	// 			this.clientidNumber + '","mqtttopic":"test1/' + this.clientidNumber + '","pubtopic":"test/' + this
	// 			.clientidNumber + '","mqttserver":"127.0.0.1","mqttport":1883}'

	// 		let buffer = this.stringToUint8Array(this.inputData);

	// 		let byteLen = buffer.byteLength; //长度
	// 		let pos = 0; //字符位置
	// 		let tempBuffer; //一次发送的数据
	// 		var i = 0; //计数

	// 		while (byteLen > 0) {
	// 			i++;
	// 			if (byteLen > 18) {
	// 				tempBuffer = buffer.slice(pos, pos + 18);
	// 				pos += 18;
	// 				byteLen -= 18;
	// 				console.log("第", i, "次发送:", tempBuffer);
	// 				this.writeBLEDef(tempBuffer);
	// 			} else {
	// 				tempBuffer = buffer.slice(pos, pos + byteLen);
	// 				pos += byteLen;
	// 				byteLen -= byteLen;
	// 				console.log("第", i, "次发送:", tempBuffer);
	// 				this.writeBLEDef(tempBuffer);
	// 			}
	// 		}
			
	// 		uni.showToast({
	// 			title: '数据发送完成',
	// 			icon: 'none'
	// 		});
	// 	},
	
	// 	writeBLEDef(tempBuffer){
	// 		console.log("deviceId：", this.deviceId);
	// 		console.log("serviceId：", this.serviceId);
	// 		console.log("characteristicId：", this.characteristicId);
	// 		console.log("数据:", tempBuffer)
	// 		uni.writeBLECharacteristicValue({
	// 			deviceId: this.deviceId,
	// 			serviceId: this.serviceId,
	// 			characteristicId: this.characteristicId,
	// 			value: tempBuffer,
	// 			success: (res) => {
	// 				console.log('数据发送成功', res);
	// 			},
	// 			fail: (err) => {
	// 				console.log('数据发送失败', err);
	// 			}
	// 		});
	// 	},	
	},
};
</script>



