<template>
    <view class="content weightPages">
        <view class="title" v-if="isConnection == 0">连接中，请稍后</view>
        <view class="title" v-if="isConnection == 1">连接成功，请开始测量</view>
        <view class="title" v-if="isConnection == 2" @click="openBluetoothAdapter">连接失败，点击重新连接</view>
        <view class="text">{{textW}}</view>
        <view class="text">{{textH}}</view>
        <view class="image">
            <image src="/BLEPages/static/H01pro.gif"></image>
        </view>
        <view class="tips">
            <text>请确保：</text>
            <text>1.请确定设备是开机状态</text>
            <text>2.请确定手机蓝牙、位置信息已打开</text>
            <text>3.ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
        </view>
    </view>
</template>

<script>
    import {
        mapState
    } from "vuex";
    var myTime;
    export default {
        data() {
            return {
                textW: "",
                textH: "",
                height: "",
                weight: "",
                imp: 0,
                macAddr: "",
                deviceId: "",
                serviceId: "",
                readId: "",
                writeId: "",
                notifyId: "",
                Unload: false,
                isConnection: 0,
            }
        },
        computed: {
            ...mapState(["user", "isConnected", "isBluetoothTyle","appTheme"]),
            info() {
                return this.user
            }
        },
        onUnload: function() {
            let that = this
            if (!that.Unload) {
                that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
                clearTimeout(myTime);
                that.closeBLEConnection()
                that.closeBluetoothAdapter()
                console.log("页面返回onUnload")
            }
        },
        watch: {
            isConnected: function() {
                let that = this
                if (!that.isConnected) {
                    that.handleBack()
                    that.isConnection = 2
                }
            },
            isBluetoothTyle: function() {
                let that = this
                if (!that.isBluetoothTyle) {
                    that.handleBack()
                    that.isConnection = 2
                }
            },
        },
        onLoad(options) {
            let that = this
            // 导航栏颜色
            uni.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: this.appTheme,
            })
            // 
            that.textW = ""
            that.textH = ""
            if (options && options.deviceId) {
                that.deviceId = options.deviceId
                that.closeBLEConnection()
                that.closeBluetoothAdapter()
                that.openBluetoothAdapter()
            }
            that.onBLEConnectionStateChange()
            uni.onBluetoothAdapterStateChange(function(res) {
                that.$store.commit("changeBluetooth", res.available);
            })
        },
        methods: {
            // 重新连接
            openBluetoothAdapter() {
                let that = this
                uni.openBluetoothAdapter({
                    success: e => {
                        that.isConnection = 0
                        that.startBluetoothDeviceDiscovery()
                    },
                    fail: e => {
                        that.isConnection = 2
                        that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
                    }
                });
            },
            // 监听蓝牙连接状态
            onBLEConnectionStateChange() {
                let that = this
                uni.onBLEConnectionStateChange(function(res) {
                    console.log("监听蓝牙连接状态", res.connected)
                    if (!res.connected) {
                        that.Unload = true
                        that.isConnection = 2
                        clearTimeout(myTime);
                        that.closeBLEConnection()
                        that.closeBluetoothAdapter()
                    }
                    that.$store.commit("changeConnected", res.connected);
                })
            },
            // 开始搜寻附近的蓝牙外围设备
            startBluetoothDeviceDiscovery() {
                let that = this
                uni.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: false,
                    interval: 500, //上报设备的间隔
                    success: res => {
                        that.isConnection = 0
                        that.onBluetoothDeviceFound();
                    },
                    fail: res => {
                        that.isConnection = 2
                        that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
                    }
                });
            },
            /**
             * 发现外围设备
             */
            onBluetoothDeviceFound() {
                var that = this;
                that.isConnection = 0
                uni.onBluetoothDeviceFound(res => {
                    res.devices.forEach(device => {
                        if (!device.name && !device.localName) {
                            return
                        }
                        console.log('开始监听寻找到新设备的事件', device);
                        if (device.name.indexOf('My') != -1) {
                            clearTimeout(myTime);
                            let buff = device.advertisData.slice(-6)
                            device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
                            let tempMac = Array.from(device.mac)
                            console.log('开始监听寻找到新设备的事件0', device)
                            device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
                            if (device.deviceId.indexOf(that.deviceId) != -1 || device.macAddr.indexOf(that.deviceId) != -1) {
                                console.log('开始监听寻找到新设备的事件1', that.deviceId)
                                that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
                                that.deviceId = device.deviceId
                                that.macAddr = device.macAddr
                                that.createBLEConnection()
                                return;
                            }
                        }
                    })
                });
                that.handleMyTime()
            },
            handleMyTime() {
                var that = this;
                myTime = setTimeout(function() {
                    if (!that.macAddr) {
                        clearTimeout(myTime);
                        that.Unload = true
                        that.isConnection = 2
                        that.closeBLEConnection()
                        that.closeBluetoothAdapter()
                    }
                }, 20000);
            },
            /**
             * 停止搜索蓝牙设备
             */
            stopBluetoothDevicesDiscovery() {
                uni.stopBluetoothDevicesDiscovery({
                    success: e => {
                        console.log("停止搜索蓝牙设备", e)
                    },
                });
            },
            // 连接蓝牙
            createBLEConnection() {
                let that = this;
                uni.createBLEConnection({
                    deviceId: that.deviceId,
                    success: res => {
                        that.isConnection = 0
                        that.getBLEDeviceServices();
                    },
                    fail: res => {
                        that.isConnection = 2
                        console.log("设备连接失败，请重新连接", res);
                    }
                });
            },
            /**
             * 获取设备的UUID
             */
            getBLEDeviceServices() {
                let serviceList = [];
                let that = this;
                uni.getBLEDeviceServices({
                    deviceId: that.deviceId,
                    success: res => {
                        console.log("获取设备的UUID成功", res)
                        serviceList = res.services;
                        for (let i = 0; i < serviceList.length; i++) {
                            let service = serviceList[i];
                            if (service.uuid.indexOf('FFE0') != -1) {
                                that.serviceId = service.uuid;
                                that.isConnection = 1
                                that.getBLEDeviceCharacteristics(that.deviceId, service.uuid);
                                console.log("设备的FFE0的serviceId： ", that.serviceId);
                                break;
                            }
                        }
                    },
                    fail: res => {
                        console.log('获取设备的UUID失败:', res)
                    }
                });
            },
            /**
             * 获取指定服务的特征值
             */
            getBLEDeviceCharacteristics(deviceId, serviceId) {
                let characteristicsList = [];
                let that = this;
                uni.getBLEDeviceCharacteristics({
                    deviceId: deviceId,
                    serviceId: serviceId,
                    success: res => {
                        console.log("服务的特征值成功", res)
                        characteristicsList = res.characteristics;
                        for (let i = 0; i < characteristicsList.length; i++) {
                            let item = characteristicsList[i];
                            if (item.uuid.indexOf("FFE1") != -1) {
                                if (item.properties.notify == true) {
                                    that.notifyId = item.uuid
                                }
                                if (item.properties.write == true) {
                                    that.writeId = item.uuid
                                }
                                if (item.properties.read) {
                                    that.readId = item.uuid
                                }
                            }
                        }
                        // 打开监听
                        uni.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: that.notifyId,
                            state: true,
                        })
                        uni.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: that.writeId,
                            state: true,
                        })
                        uni.onBLECharacteristicValueChange(function(res) {
                            let value = that.$tools.ab2hex(res.value, '');
                            let weight = parseInt(value.substring(4, 8), 16) / 100
                            let height = parseInt(value.substring(30, 34), 16) / 10
                            let imp0 = value.substring(28, 30) + value.substring(34, 36)
                            let imp = parseInt(imp0, 16)
                            that.imp = imp
                            that.textW = "您的体重是：" + weight + 'kg'
                            that.textH = "您的身高是：" + height + 'cm'
                            that.weight = weight + 'kg'
                            that.height = height
                            console.log("测量完成", that.weight, that.height, that.imp)
                            if (imp == 0) {
                                uni.showModal({
                                    title: '提示',
                                    content: "体脂测量失败，是否保存本次测量结果？",
                                    cancelText: "放弃",
                                    confirmText: "保存",
                                    success(res) {
                                        if (res.confirm) {
                                            that.handleGetMeasure()
                                        } else {
                                            that.Unload = true
                                            that.closeBLEConnection()
                                            that.closeBluetoothAdapter()
                                            uni.navigateBack({
                                                delta: 1
                                            })
                                        }

                                    }
                                })
                            } else {
                                that.handleGetMeasure()
                            }
                        });
                    },
                    fail: res => {
                        console.log('获取特征值失败:', JSON.stringify(res))
                    }
                })
            },
            // 保存测量结果
            handleGetMeasure() {
                console.log("保存结果")
                let that = this
                that.$model.getmeasure({
                    weight: that.weight,
                    imp: that.imp,
                    ecode: that.macAddr,
                    height: that.height ? that.height : that.info.height,
                    familyid: that.info.familyid,
                }).then(res => {
                    if (res.code == 0) {
                        that.$tools.msg("测量成功")
                        that.$store.dispatch("getUserInfo", {
                            familyid: that.info.familyid,
                        });
                        that.$store.dispatch("getResult", {
                            birthday: that.info.birthday,
                            familyid: that.info.familyid,
                            height: that.height ? that.height : that.info.height,
                            sex: that.info.sex,
                        });
                    } else {
                        console.log("测量失败", res.message)
                        that.$tools.msg(res.message)
                    }
                    that.Unload = true
                    setTimeout(function() {
                        that.closeBLEConnection()
                        that.closeBluetoothAdapter()
                        uni.switchTab({
                            url: "/pages/index/index"
                        })
                    }, 200)

                })
            },
            handleBack() {
                let that = this
                that.textW = ""
                that.textH = ""
                that.Unload = true
                that.Unload = true
                that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
                that.closeBLEConnection()
                that.closeBluetoothAdapter()
            },
            /**
             * 断开蓝牙模块
             */
            closeBluetoothAdapter() {
                let that = this;
                uni.closeBluetoothAdapter({
                    success: res => {
                        console.log('蓝牙模块关闭成功');
                    }
                })
            },
            /**
             * 断开蓝牙连接
             */
            closeBLEConnection() {
                var that = this;
                uni.closeBLEConnection({
                    deviceId: that.deviceId,
                    success: res => {
                        console.log('断开蓝牙连接成功');
                    }
                });
            },
        },
    }
</script>

<style scoped lang="scss">
</style>
