<template>
    <view class="content">
        <view class="tips">请在设备开机状态下，搜索设备</view>
        <view class="item" @click="handleWeight">开始搜索设备</view>
        <view class="devices_summary">已发现 {{devices.length}} 个设备：</view>
        <view>
            <scroll-view class="device_list" scroll-y scroll-with-animation v-if="popup">
                <view v-for="(item,index) in devices" :key="index" @tap="createBLEConnection(item)" class="device_item">
                    <view>
                        <text>{{item.name|| item.localName}}</text>
                    </view>
                    <view>mac地址:{{item.macAddr || item.deviceId}}</view>
                </view>
            </scroll-view>
        </view>
        <view class="tishi">
            <view class="text">
                <icon class="t-icon t-icon-tishi"></icon> 设备激活流程说明
            </view>
            <view class="dv">
                <text>1、打开手机蓝牙和位置信息</text>
                <text>2、ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
                <text>3、设备亮屏状态下搜索蓝牙</text>
                <text>4、选择蓝牙进行激活</text>
            </view>
        </view>
        <userLogin :url="'active'"></userLogin>
    </view>
</template>

<script>
    var myTime;
    import {
        mapState
    } from "vuex";
    import userLogin from "@/components/userLogin.vue"
    export default {
        data() {
            return {
                token: "",
                macAddr: "",
                code: "",
                deviceId: "",
                popup: false,
                devices: [],
            }
        },
        components: {
            userLogin
        },
        computed: {
            ...mapState(["user", "isBluetoothTyle"])
        },
        onLoad(options) {
            let that = this
            console.log("设备code码", options)
            if (options) {
                that.code = options.code
            }
            that.token = uni.getStorageSync('token')
            that.login()
            uni.onBluetoothAdapterStateChange(function(res) {
                that.$store.commit("changeBluetooth", res.available);
            })
        },
        methods: {
            login() {
                let that = this
                uni.login({
                    success(res) {
                        if (res.code) {
                            if (res.errMsg = "login:ok") {
                                that.$model.onlogin({
                                    code: res.code,
                                }).then(res => {
                                    if (res.code == 2) {
                                        uni.clearStorageSync()
                                        uni.removeStorageSync('token')
                                        uni.removeStorageSync('changeUser')
                                        uni.setStorageSync('tenantid', res.data.tenantid)
                                        uni.setStorageSync('sessionid', res.data.sessionid)
                                        uni.setStorageSync('iswxphone', res.data.iswxphone)
                                        that.$store.commit("changeUserLogin", true)
                                        return
                                    } else {
                                        uni.setStorageSync('sessionid', res.data.sessionid)
                                        uni.setStorageSync('token', res.data.token)
                                        uni.setStorageSync('iswxphone', res.data.iswxphone)
                                        uni.setStorageSync('tenantid', res.data.tenantid)
                                        uni.setStorageSync('refreshtoken', res.data.refreshtoken)
                                    }
                                }).catch(e => {})
                            }
                        }
                    }
                })
            },
            handleWeight() {
                let that = this
                that.devices = []
                if (!that.token) {
                    that.$store.commit("changeUserLogin", true)
                    return
                }
                uni.openBluetoothAdapter({
                    success: e => {
                        that.$store.commit("changeBluetooth", true);
                        that.startBluetoothDeviceDiscovery()
                    },
                    fail: e => {
                        wx.hideLoading()
                        console.log("openBluetoothAdapter失败", e)
                        return that.$tools.getBluetoothAdapter(e)
                    }
                });
            },
            startBluetoothDeviceDiscovery() {
                let that = this;
                wx.showLoading({
                    title: '设备搜索中',
                })
                uni.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                    success: res => {
                        that.onBluetoothDeviceFound();
                    },
                    fail: res => {
                        wx.hideLoading()
                        console.log("startBluetoothDeviceDiscovery失败", res)
                    }
                });
            },
            onBluetoothDeviceFound() {
                var that = this;
                const foundDevices = []
                uni.onBluetoothDeviceFound(res => {
                    res.devices.forEach(device => {
                        if (!device.name && !device.localName) {
                            return
                        }
                        if (device.name.indexOf('AiLink_') != -1) {
                            const foundDevices = that.devices
                            const idx = that.$tools.inArray(foundDevices, "deviceId", device.deviceId)
                            let buff = device.advertisData.slice(-6)
                            device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
                            let tempMac = Array.from(device.mac)
                            tempMac.reverse()
                            device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
                            that.deviceId = device.deviceId
                            that.macAddr = device.macAddr
                            console.log("device0", device.macAddr, that.deviceId, )
                            if (idx === -1) {
                                that.devices.push(device);
                            } else {
                                that.devices[idx] = device
                            }
                            that.popup = true
                            return
                        }
                        if (device.advertisServiceUUIDs[0].indexOf("F0A0") !== -1) {
                            const foundDevices = that.devices
                            const idx = that.$tools.inArray(foundDevices, "deviceId", device.deviceId)
                            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.deviceId = device.deviceId;
                            that.macAddr = device.macAddr
                            console.log("device1", device.macAddr, that.deviceId)
                            if (idx === -1) {
                                that.devices.push(device);
                            } else {
                                that.devices[idx] = device
                            }
                            that.popup = true
                            return
                        }
                    })
                });
                that.handleMyTime()
            },
            handleMyTime() {
                var that = this;
                myTime = setTimeout(function() {
                    if (!that.devices.length) {
                        clearTimeout(myTime);
                        wx.hideLoading()
                        that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
                        uni.showModal({
                            title: '提示',
                            content: '请确定蓝牙和手机位置信息已打开！请确定设备已开机；ios系统需打开设置——>应用——>微信里的蓝牙权限！是否继续？',
                            cancelText: "取消",
                            confirmText: "继续",
                            success(res) {
                                if (res.confirm) {
                                    that.startBluetoothDeviceDiscovery()
                                } else {
                                    that.$tools.msg("您已取消操作")
                                }
                            }
                        })
                    } else {
                        clearTimeout(myTime);
                        that.stopBluetoothDevicesDiscovery()
                    }
                }, 30000);
            },
            /**
             * 停止搜索蓝牙设备
             */
            stopBluetoothDevicesDiscovery() {
                uni.stopBluetoothDevicesDiscovery({
                    success: e => {
                        console.log("停止搜索蓝牙设备", e)
                    },
                });
            },
            // 连接蓝牙
            createBLEConnection(e) {
                let that = this;
                that.stopBluetoothDevicesDiscovery()
                that.macAddr = e.macAddr
                that.getCode()
            },
            getCode() {
                let that = this;
                clearTimeout(myTime);
                wx.hideLoading()
                uni.showModal({
                    title: '提示',
                    content: '是否激活该设备?',
                    cancelText: "取消",
                    confirmText: "确定",
                    success: (res) => {
                        if (res.confirm) {
                            that.getActive()
                        } else {
                            that.$tools.msg("您已取消操作")
                        }
                    }
                })
            },
            getActive() {
                let that = this
                that.$model.getdevactive({
                    code: that.code,
                    sn: that.macAddr
                }).then(res => {
                    that.$tools.msg(res.message)
                    that.closeBluetoothAdapter()
                    that.closeBLEConnection()
                    that.devices = []
                    if (res.code == 0) {
                        setTimeout(function() {
                            uni.reLaunch({
                                url: "/pages/index/index?t=" + that.devtype
                            })
                        }, 500)
                    }
                })
            },
            /**
             * 断开蓝牙模块
             */
            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">
    .content {
        min-height: 100vh;
        padding: 0;
        border-top: 66px solid #75DAD0;
        background-color: #fff;
    }

    .tishi {
        width: 100%;
        font-size: 14px;
        line-height: 25px;
        font-weight: bold;
        position: absolute;
        bottom: 30px;
        padding-left: 15px;

        .text {
            display: flex;
            align-items: center;

            icon {
                margin-right: 5px;
            }
        }

        text {
            font-weight: 500;
            font-size: 12px;
            color: #999;
            width: 100%;
            display: block;
        }
    }

    .item {
        width: 70%;
        height: 40px;
        line-height: 38px;
        text-align: center;
        background: #f7f7f7;
        border: 1px solid #dfdfdf;
        font-weight: bold;
        margin: auto;
        border-radius: 15px;
        margin-top: 15px;
    }

    .devices_summary {
        width: 100%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        font-size: 16px;
        color: #666;
    }

    .device_list {
        flex: 1;
        width: 100%;
        height: auto;
        max-height: 200px;
        margin-top: 0;
        margin-bottom: 10px;

        .device_item {
            font-size: 14px;
            padding: 10px;
            color: #999;
            border-bottom: 1px solid #dfdfdf;

            text {
                display: inline-block;
                font-size: 14px;
                font-weight: bold;
                color: #666;
                margin-bottom: 5px;
            }
        }
    }

    .tips {
        font-size: 14px;
        text-align: center;
        color: #e83a1e;
        background: #f7e4c8;
        padding: 5px 0;
        margin-top: 15px;
    }
</style>
