<template>
    <view>
        <!-- 横向均分 -->
        <view style="background-color: #fff">
            <!--
<view class="layout_horizontal">
  <button class="button_sp"hover-class="button_sp2"style="flex:1"bindtap='gotosetuuid'>设置UUID</button>
  <view class="div" style='background-color:white'></view>
  <button class="button_sp"hover-class="button_sp2"style="flex:1" bindtap='gotoabout'>关于我们</button>
</view>
-->

            <button :loading="misScanding" class="button_sp" hover-class="button_sp2" @tap="openBluetoothAdapter">{{ scandbutName }}</button>
         <!--   <button style="display: none" @tap="stopBluetoothDevicesDiscovery">停止扫描</button>
            <button style="display: none" @tap="closeBluetoothAdapter">结束流程</button> -->
        </view>
        <view style="background-color: #fff; height: 10px; width: 100%"></view>

        <view class="devices_summary">已发现 {{ devices.length }} 个BLE设备：</view>
        <scroll-view class="device_list" scroll-y scroll-with-animation>
            <view
                :data-device-id="item.deviceId"
                :data-name="item.name || item.localName"
                @tap="goto_Comm"
                class="device_item"
                hover-class="device_item_hover"
                v-for="(item, index) in devices"
                :key="index"
            >
                <view style="font-size: 16px; color: #111">{{ item.name }}</view>

                <view style="font-size: 12px; color: #555">RSSI: {{ item.RSSI }}dBm</view>

                <view style="font-size: 12px; color: #555">{{ item.deviceId }}</view>
            </view>
        </scroll-view>

       <!-- <view style="display: none" class="connected_info" v-if="connected">
            <view>
                <text>已连接到 {{ name }}</text>
                <view class="operation">
                    <button v-if="canWrite" size="mini" @tap="writeBLECharacteristicValue">写数据</button>
                    <button size="mini" @tap="closeBLEConnection">断开连接</button>
                </view>
            </view>
            <view style="font-size: 12px; margin-top: 10px" v-for="(item, index) in chs" :key="index">
                <view>特性UUID: {{ item.uuid }}</view>

                <view>特性值: {{ item.value }}</view>
            </view>
        </view> -->
    </view>
</template>

<script>
const app = getApp();
function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2);
    });
    return hexArr.join('');
}
export default {
    data() {
        return {
            devices: [],
            connected: false,
            chs: [],
            misScanding: false,
            scandbutName: '搜索蓝牙设备',
            name: '',
            deviceId: '',
            // canWrite: false
        };
    },
    methods: {
        openBluetoothAdapter() {
            this.misScanding = false;
            uni.openBluetoothAdapter({
                success: (res) => {
                    console.log('openBluetoothAdapter success', res);
                    this.startBluetoothDevicesDiscovery();
                },
                fail: (res) => {
                    if (res.errCode === 10001) {
                        uni.onBluetoothAdapterStateChange(function (res) {
                            console.log('onBluetoothAdapterStateChange', res);
                            if (res.available) {
                                this.startBluetoothDevicesDiscovery();
                            }
                        });
                    }
                }
            });
        },

        // getBluetoothAdapterState() {
        //     uni.getBluetoothAdapterState({
        //         success: (res) => {
        //             console.log('getBluetoothAdapterState', res);
        //             if (res.discovering) {
        //                 this.onBluetoothDeviceFound();
        //             } else if (res.available) {
        //                 this.startBluetoothDevicesDiscovery();
        //             }
        //         }
        //     });
        // },

        startBluetoothDevicesDiscovery() {
            var that = this;
            if (this._discoveryStarted) {
                this.stopBluetoothDevicesDiscovery();
                return;
            }
            // this.setData({
                this.misScanding =  true
                this.scandbutName= '正在搜索，点击停止'
                this.devices= []
                this.chs = []
            // });
            //console.log('lisn3188---------- misScanding = ', this.misScanding)
            this._discoveryStarted = true;
            uni.startBluetoothDevicesDiscovery({
                allowDuplicatesKey: true,
                success: (res) => {
                    setTimeout(function () {
                        console.log('----BluetoothDevicesDiscovery finish---- ');
                        if (that._discoveryStarted) {
                            that.stopBluetoothDevicesDiscovery();
                        }
                    }, 20000);
                    console.log('startBluetoothDevicesDiscovery success', res);
                    this.onBluetoothDeviceFound();
                }
            });
        },

        stopBluetoothDevicesDiscovery() {
            this._discoveryStarted = false;
            uni.stopBluetoothDevicesDiscovery();
            // this.setData({
                this.misScanding = false
                this.scandbutName= '重新刷新列表'
            // });
            //console.log('lisn3188---------- misScanding = ', this.misScanding)
        },

        onBluetoothDeviceFound() {
            uni.onBluetoothDeviceFound((res) => {
                res.devices.forEach((device) => {
                    if (!device.name && !device.localName) {
                        return;
                    }
                    const foundDevices = this.devices;
					console.log('设备列表', foundDevices)
					// 查找当前已发现蓝牙数据，如果可以匹配到，则更新对应数据
                    const idx = inArray(foundDevices, 'deviceId', device.deviceId);
                    // const data = {};
                    if (idx === -1) { // 如果没有发现列表已有蓝牙数据则新增
                        this.devices[foundDevices.length] = device;
                    } else {
                        this.devices[idx] = device;
                    }
                    // this.setData(data);
                });
            });
        },

        goto_Comm(e) {
			console.log('e.currentTarget.dataset', e.currentTarget.dataset)
            // this.$globalData.ble_device = e.currentTarget.dataset;
			const deviceInfo = e.currentTarget.dataset
			// loca
            this.stopBluetoothDevicesDiscovery();
            uni.navigateTo({
                url: `/pages/tabBar/component/comm?deviceId=${deviceInfo.deviceId}&name=${deviceInfo.name}`
            });
        },

        // createBLEConnection(e) {
        //     const ds = e.currentTarget.dataset;
        //     const deviceId = ds.deviceId;
        //     const name = ds.name;
        //     uni.createBLEConnection({
        //         deviceId,
        //         success: (res) => {
        //             // this.setData({
        //                this.connected= true;
        //                 this.name = name;
        //                 this.deviceId = deviceId
        //             // });
        //             this.getBLEDeviceServices(deviceId);
        //         }
        //     });
        //     this.stopBluetoothDevicesDiscovery();
        // },

        // closeBLEConnection() {
        //     uni.closeBLEConnection({
        //         deviceId: this.deviceId
        //     });
        //     // this.setData({
        //         this.connected= false
        //         this.chs= []
        //         this.canWrite= false
        //     // });
        // },

        // getBLEDeviceServices(deviceId) {
        //     uni.getBLEDeviceServices({
        //         deviceId,
        //         success: (res) => {
        //             for (let i = 0; i < res.services.length; i++) {
        //                 if (res.services[i].isPrimary) {
        //                     this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
        //                     return;
        //                 }
        //             }
        //         }
        //     });
        // },

        // getBLEDeviceCharacteristics(deviceId, serviceId) {
        //     uni.getBLEDeviceCharacteristics({
        //         deviceId,
        //         serviceId,
        //         success: (res) => {
        //             console.log('getBLEDeviceCharacteristics success', res.characteristics);
        //             for (let i = 0; i < res.characteristics.length; i++) {
        //                 let item = res.characteristics[i];
        //                 if (item.properties.read) {
        //                     uni.readBLECharacteristicValue({
        //                         deviceId,
        //                         serviceId,
        //                         characteristicId: item.uuid
        //                     });
        //                 }
        //                 if (item.properties.write) {
        //                     // this.setData({
        //                         this.canWrite = true
        //                     // });
        //                     this._deviceId = deviceId;
        //                     this._serviceId = serviceId;
        //                     this._characteristicId = item.uuid;
        //                     this.writeBLECharacteristicValue();
        //                 }
        //                 if (item.properties.notify || item.properties.indicate) {
        //                     uni.notifyBLECharacteristicValueChange({
        //                         deviceId,
        //                         serviceId,
        //                         characteristicId: item.uuid,
        //                         state: true
        //                     });
        //                 }
        //             }
        //         },
        //         fail(res) {
        //             console.error('getBLEDeviceCharacteristics', res);
        //         }
        //     });
        //     // 操作之前先监听，保证第一时间获取数据
        //     uni.onBLECharacteristicValueChange((characteristic) => {
        //         const idx = inArray(this.chs, 'uuid', characteristic.characteristicId);
        //         const data = {};
        //         if (idx === -1) {
        //             data[`chs[${this.chs.length}]`] = {
        //                 uuid: characteristic.characteristicId,
        //                 value: ab2hex(characteristic.value)
        //             };
        //         } else {
        //             data[`chs[${idx}]`] = {
        //                 uuid: characteristic.characteristicId,
        //                 value: ab2hex(characteristic.value)
        //             };
        //         }
        //         // data[`chs[${this.data.chs.length}]`] = {
        //         //   uuid: characteristic.characteristicId,
        //         //   value: ab2hex(characteristic.value)
        //         // }
        //         this.setData(data);
        //     });
        // },

        // writeBLECharacteristicValue() {
        //     // 向蓝牙设备发送一个0x00的16进制数据
        //     let buffer = new ArrayBuffer(1);
        //     let dataView = new DataView(buffer);
        //     dataView.setUint8(0, (Math.random() * 255) | 0);
        //     uni.writeBLECharacteristicValue({
        //         deviceId: this._deviceId,
        //         serviceId: this._deviceId,
        //         characteristicId: this._characteristicId,
        //         value: buffer
        //     });
        // },

        closeBluetoothAdapter() {
            uni.closeBluetoothAdapter();
            this._discoveryStarted = false;
        }
    }
};
</script>
<style>
page {
    color: #333;
}
.devices_summary {
    padding: 10px;
    font-size: 16px;
    background-color: hsl(216, 5%, 22%);
    color: #fff;
    align-items: center;
    justify-content: center;
    display: flex;
}
.device_list {
    height: auto;
    margin: 50px 5px;
    margin-top: 5px;
    border: 1px solid #eee;
    border-radius: 5px;
    width: auto;
}
.device_item {
    border-bottom: 1px solid #222;
    padding: 10px;
    color: #666;
}
.device_item_hover {
    background-color: rgba(0, 0, 0, 0.1);
}
.connected_info {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #f0f0f0;
    padding: 10px;
    padding-bottom: 20px;
    margin-bottom: env(safe-area-inset-bottom);
    font-size: 14px;
    min-height: 100px;
    box-shadow: 0px 0px 3px 0px;
}
.connected_info .operation {
    position: absolute;
    display: inline-block;
    right: 30px;
}
.button_sp {
    margin-left: 10px;
    margin-right: 10px;
    margin-top: 5px;
    background-color: #10b7ff;
    color: #fff;
    font-size: 15px;
}
.button_sp2 {
    margin-left: 10px;
    margin-right: 10px;
    margin-top: 5px;
    background-color: #757575;
    color: #fff;
}
.flex-wrp {
    height: auto;
    display: flex;
    background-color: #ffffff;
}
/*横向布局  */
.layout_horizontal {
    display: flex;
    /*row 横向  column 列表  */
    flex-direction: row;
}
/*纵向布局  */
.layout_vertical {
    height: 100rpx;
    display: flex;
    /*row 横向  column 列表  */
    flex-direction: column;
}
/*划线  */
.line {
    background-color: blue;
    height: 5px;
    width: 100%;
}
.div {
    background-color: white;
    height: 10px;
    width: 10px;
}
</style>
