<template>
    <view class="container">
        <button @click="initBluetooth" :disabled="isInitializing">初始化蓝牙</button>
        <button @click="startDiscovery" :disabled="isDiscovering || !isBluetoothOpened">开始搜索设备</button>
        <button @click="connectDevice" :disabled="!selectedDevice || isConnecting">连接设备</button>
        <button @click="startDataMonitor" :disabled="!isConnected">开始监听数据</button>
        <view v-if="scanData">扫描结果: {{ scanData }}</view>
		
		<view v-for="item in devices">
			{{item.name}}
		</view>
    </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const isInitializing = ref(false);
const isBluetoothOpened = ref(false);
const isDiscovering = ref(false);
const isConnecting = ref(false);
const isConnected = ref(false);
const devices = ref([]);
const selectedDevice = ref(null);
const scanData = ref(null);
const deviceId = ref('');
const serviceId = ref('');
const characteristicId = ref('');

const initBluetooth = () => {
    isInitializing.value = true;
    uni.openBluetoothAdapter({
        success: (res) => {
            console.log('蓝牙适配器初始化成功');
            isBluetoothOpened.value = true;
            isInitializing.value = false;
        },
        fail: (err) => {
            console.log('蓝牙适配器初始化失败：', err);
            isInitializing.value = false;
        }
    });
};

const startDiscovery = () => {
    isDiscovering.value = true;
    uni.startBluetoothDevicesDiscovery({
        success: (res) => {
            console.log('开始搜索蓝牙设备成功');
            uni.onBluetoothDeviceFound((devicesRes) => {
                const newDevices = devicesRes.devices;
                devices.value = devices.value.concat(newDevices);
				console.log(devices.value,'devices.value')
                const scanGunDevice = newDevices.find((device) => device.name.includes('Z0'));
                if (scanGunDevice) {
                    selectedDevice.value = scanGunDevice;
                    deviceId.value = scanGunDevice.deviceId;
                }
            });
            uni.onBluetoothAdapterStateChange((stateRes) => {
                if (!stateRes.available) {
                    isDiscovering.value = false;
                    console.log('蓝牙适配器不可用，停止搜索');
                }
            });
        },
        fail: (err) => {
            console.log('开始搜索蓝牙设备失败：', err);
            isDiscovering.value = false;
        }
    });
};

const connectDevice = () => {
    isConnecting.value = true;
    uni.createBLEConnection({
        deviceId: deviceId.value,
        success: (res) => {
            console.log('连接蓝牙设备成功');
            isConnected.value = true;
            isConnecting.value = false;
            getBLEDeviceServices(deviceId.value);
        },
        fail: (err) => {
            console.log('连接蓝牙设备失败：', err);
            isConnecting.value = false;
        }
    });
};

const getBLEDeviceServices = (deviceId) => {
    uni.getBLEDeviceServices({
        deviceId: deviceId,
        success: (res) => {
            console.log('获取服务列表成功：', res.services);
            const targetService = res.services.find((service) => service.uuid === '目标服务UUID');
            if (targetService) {
                serviceId.value = targetService.uuid;
                getBLEDeviceCharacteristics(deviceId, serviceId.value);
            }
        },
        fail: (err) => {
            console.log('获取服务列表失败：', err);
        }
    });
};

const getBLEDeviceCharacteristics = (deviceId, serviceId) => {
    uni.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success: (res) => {
            console.log('获取特征列表成功：', res.characteristics);
            const targetCharacteristic = res.characteristics.find((characteristic) => characteristic.properties.read && characteristic.properties.notify);
            if (targetCharacteristic) {
                characteristicId.value = targetCharacteristic.uuid;
            }
        },
        fail: (err) => {
            console.log('获取特征列表失败：', err);
        }
    });
};

const startDataMonitor = () => {
    uni.onBLECharacteristicValueChange((characteristicRes) => {
        const value = characteristicRes.value;
        const data = ab2str(value);
        console.log('获取到扫码枪扫描的数据：', data);
        scanData.value = data;
    });
    uni.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: deviceId.value,
        characteristicId: characteristicId.value,
        success: (res) => {
            console.log('开启特征值通知成功');
        },
        fail: (err) => {
            console.log('开启特征值通知失败：', err);
        }
    });
};

const ab2str = (buffer) => {
    return String.fromCharCode.apply(null, new Uint8Array(buffer));
};
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

button {
    margin: 10px 0;
    width: 200px;
}
</style>