<script>
import ble_store from "@/store/bluetooth";
import Dialog from "../../../../static/vant/dialog/dialog";
import Toast from "../../../../static/vant/toast/toast";

let $this;
export default {
  name: "ConnectionScan",
  created() {
    $this = this;
  },
  methods: {
    /**
     * 扫描二维码连接脑机
     */
    openScan() {
      // 微信异步获取系统信息
      wx.getSystemInfoAsync({
        success(res) {
          // 蓝牙的系统开关 boolean
          if (!res.bluetoothEnabled) {
            Dialog.alert({
              title: '蓝牙功能未开启',
              message: '请打开蓝牙，允许水母星球使用蓝牙服务',
            }).then(() => {
              // 跳转系统蓝牙设置页
              wx.openSystemBluetoothSetting()
            });
          }
          // 地理位置的系统开关 boolean
          else if (!res.locationEnabled) {
            // 如果是苹果系统则直接打开扫描
            if (res.system.indexOf("iOS") !== -1) {
              $this.scanBluetooth();
            } else {
              Dialog.alert({
                title: '位置信息未开启',
                message: '当前无位置访问权限，请在设置中，允许水母星球使用位置服务',
              }).then(() => {
              });
            }
          }
          // 允许微信使用定位的开关 boolean
          else if (!res.locationAuthorized) {
            Dialog.alert({
              title: '位置权限未开启',
              message: '当前无位置访问权限，请在手机[设置]应用中，允许[微信]使用位置服务',
            }).then(() => {
              // 跳转系统微信授权管理页
              wx.openAppAuthorizeSetting()
            });
          }
          // 已允许权限
          else {
            $this.scanBluetooth();
          }
        },
      });
    },
    /**
     * 扫描连接蓝牙
     */
    scanBluetooth() {
      // 调起微信客户端扫码界面进行扫码
      wx.scanCode({
        // 是否只能从相机扫码
        onlyFromCamera: true,
        // barCode:一维码, qrCode:二维码
        scanType: ["barCode", "qrCode"],
        success: (scan) => {
          console.log(scan.result)
          if (scan.result) {
            let url = decodeURIComponent(scan.result);
            let $code = "";
            if (scan.scanType === "QR_CODE") {
              // 二维码
              $code = url.substring(url.indexOf("AI"));
            } else {
              // 一维码
              $code = scan.result.toUpperCase();
            }
            ble_store.setters.setDeviceSn($code);
            console.log("扫码得到头环SN码:", $code);
            // 检查微信蓝牙权限
            this.openWechatBluetooth();
          }
        },
        fail(err) {
          console.log(err["errMsg"])
          setTimeout(() => {
            Toast.fail({
              message: err["errMsg"],
            });
          }, 3000);
        },
      });
    },
    /**
     * 检查微信蓝牙权限
     */
    openWechatBluetooth: function () {
      // 获取系统信息
      wx.getSystemInfo({
        success(res) {
          // 判断ios
          if (res.platform === "ios") {
            // 初始化蓝牙模块。iOS上开启主机central/从机peripheral（外围设备）模式时需分别调用一次，并指定对应的 mode
            wx.openBluetoothAdapter({
              // 判断主机模式蓝牙是否打开
              mode: "central",
              success(res) {
                // 正常
                if (res["errMsg"] === "openBluetoothAdapter:ok") {
                  // 判断从机模式蓝牙是否打开
                  wx.openBluetoothAdapter({
                    // 判断从机模式蓝牙是否打开
                    mode: "peripheral",
                    success(res) {
                      if (res["errMsg"] === "openBluetoothAdapter:ok") {
                        $this.setScanStatus(1);
                      }
                    },
                    fail(err) {
                      setTimeout(() => {
                        Toast.fail({
                          message: $this.$connection.connectionError(err["errCode"]),
                        });
                      }, 3000);
                    },
                  });
                }
              },
              fail(err) {
                setTimeout(() => {
                  Toast.fail({
                    message: $this.$connection.connectionError(err["errCode"]),
                  });
                }, 3000);
              },
            });
          } else {
            // 安卓手机
            wx.openBluetoothAdapter({
              mode: "peripheral",
              success(res) {
                // 正常
                if (res["errMsg"] === "openBluetoothAdapter:ok") {
                  $this.setScanStatus(1);
                }
              },
              fail(err) {
                setTimeout(() => {
                  Toast.fail({
                    message: err["errMsg"],
                  });
                }, 3000);
              },
            });
          }
        },
      });
    },
    /**
     * 修改扫码状态
     * @param $status 0未，1扫码成功
     */
    setScanStatus($status = 0) {
      $this.$emit("scanStatus", $status);
    },

  },
};
</script>

<template>
  <div>
    <van-row>
      <van-col span="11" class="text-gray text-sm left" offset="1">
        <view>1.打开手机蓝牙和位置信息</view>
        <view>2.长按脑机侧面按钮启动脑机</view>
        <view>3.点击扫码开始连接</view>
      </van-col>
      <van-col span="8" offset="2">
        <img src="https://img.shuimuai.com/lanyashuimu.png" class="connect_img" alt=""/>
      </van-col>
    </van-row>
    <button class="cu-btn lg cu-btn-primary text-white text-center scan_button margin-tb" @click="openScan">扫码连接脑机</button>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog"/>
  </div>
</template>
<style scoped></style>
