<template>
    <view>
        <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">{{text}}</view>
            <view class="image">
                <image src="/BLEPages/static/L01.gif"></image>
            </view>
            <view class="tips">
                <text>提示：</text>
                <text>1.请确定设备是开机状态</text>
                <text>2.请确定手机蓝牙、位置信息已打开</text>
                <text>3.ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
            </view>
        </view>
    </view>
</template>

<script>
    import {
        mapState
    } from "vuex";
    let myTime
    const plugin = requirePlugin("sdkPlugin").AiLink;
    export default {
        data() {
            return {
                text: "",
                height: "",
                weight: "",
                imp: 0,
                macAddr: "",
                deviceId: "",
                serviceId: "",
                Unload: false,
                stopblue: true,
                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("测量页返回1")
            }
        },
        onLoad(options) {
            let that = this
            // 导航栏颜色
            uni.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: this.appTheme,
            })
            // 
            that.text = ""
            if (options && options.deviceId) {
                that.deviceId = options.deviceId
                that.openBluetoothAdapter()
            }
            uni.onBluetoothAdapterStateChange(function(res) {
                that.$store.commit("changeBluetooth", res.available);
            })
        },
        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
                }
            },
            stopblue: function() {
                let that = this
                if (!that.stopblue) {
                    console.log("停止成功", that.weight, that.imp)
                    if (that.imp == 0) {
                        uni.showModal({
                            title: '提示',
                            content: "体脂测量失败，是否保存本次测量结果？",
                            cancelText: "放弃",
                            confirmText: "保存",
                            success(res) {
                                if (res.confirm) {
                                    that.imp = 0
                                    that.handleGetMeasure()
                                } else {
                                    that.Unload = true
                                    that.startBluetoothDeviceDiscovery()
                                    that.closeBLEConnection()
                                    that.closeBluetoothAdapter()
                                    uni.navigateBack({
                                        delta: 1
                                    })
                                }
                            }
                        })
                    } else {
                        that.handleGetMeasure()
                    }

                }
            }
        },
        methods: {
            // 初始化蓝牙
            openBluetoothAdapter() {
                let that = this
                that.text = ""
                that.stopblue = true
                uni.openBluetoothAdapter({
                    success: e => {
                        that.isConnection = 0
                        that.startBluetoothDeviceDiscovery()
                    },
                    fail: e => {
                        that.isConnection = 2
                        that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
                    }
                });
            },
            // 开始搜寻附近的蓝牙外围设备
            startBluetoothDeviceDiscovery() {
                let that = this
                uni.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                    services: [
                        "F0A0",
                    ],
                    success: res => {
                        that.isConnection = 0
                        that.onBluetoothDeviceFound();
                    },
                    fail: res => {
                        that.isConnection = 2
                        that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
                    }
                });
            },
            /**
             * 停止搜索蓝牙设备
             */
            stopBluetoothDevicesDiscovery() {
                uni.stopBluetoothDevicesDiscovery({
                    success: e => {
                        console.log("停止搜索蓝牙设备", e)
                    },
                });
            },
            /**
             * 发现外围设备
             */
            onBluetoothDeviceFound() {
                var that = this;
                that.isConnection = 1
                uni.onBluetoothDeviceFound(res => {
                    res.devices.forEach(device => {
                        if (!device.name && !device.localName) {
                            return
                        }
                        if (device.advertisServiceUUIDs[0].indexOf("F0A0") !== -1) {
                            clearTimeout(myTime);
                            let value = that.$tools.ab2hex(device.advertisData)
                            let parseDataRes = plugin.parseBroadcastData(device.advertisData)
                            let analyzeData = plugin.analyzeBroadcastScaleData(parseDataRes)
                            let analyzeDataText = analyzeData.text
                            let data = analyzeData.data
                            console.log("analyzeData", parseDataRes, analyzeData)
                            if (parseDataRes.status == 1) {
                                let dw1 = "kg"
                                let dw2 = "kg"
                                if (data.weightUnit == "1") {
                                    dw1 = "斤"
                                    dw2 = "jin"
                                }
                                if (data.weightUnit == "4") {
                                    dw1 = "st:lb"
                                    dw2 = "st"
                                    data = 1 * data + 5
                                }
                                if (data.weightUnit == "6") {
                                    dw1 = "lb"
                                    dw2 = "lb"
                                }
                                if (data.weightDecimal == "1") {
                                    data.weight = data.weight / 10
                                }
                                if (data.weightDecimal == "2") {
                                    data.weight = data.weight / 100
                                }
                                if (data.weightDecimal == "3") {
                                    data.weight = data.weight / 1000
                                }
                                that.text = "您的体重是：" + data.weight + dw1
                                if (data.weightStatus == 1 || analyzeDataText.indexOf('阻抗测量失败') != -1) {
                                    let buffer = device.advertisData.slice(0, 8)
                                    device.mac = new Uint8Array(buffer)
                                    let tempMac = Array.from(device.mac)
                                    tempMac.reverse()
                                    device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
                                    that.macAddr = device.macAddr
                                    that.deviceId = device.deviceId;
                                    that.weight = data.weight + dw2
                                    that.imp = data.adc
                                    uni.stopBluetoothDevicesDiscovery({
                                        success: e => {
                                            return that.stopblue = false
                                        },
                                    });
                                    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);
            },
            // 保存测量结果 
            handleGetMeasure() {
                let that = this
                that.$model.getmeasure({
                    weight: that.weight,
                    imp: that.imp,
                    ecode: that.macAddr,
                    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.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.Unload = true
                clearTimeout(myTime)
                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>
