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

let $this;
export default {
  name: "Connecting",
  props: ['status'],
  data() {
    return {
      // 设备状态 0为未连接，1：连接中，2：已连接 3：连接失败
      device_status: 0,
      // 脑机sn码
      code: "AI00000000",
      bleFoundTimeOut: undefined
    }
  },
  created() {
    $this = this;
  },
  mounted() {
    $this.code = ble_store.getters.getDeviceSn();
  },
  watch: {
    'status': {
      handler: function($status) {
        console.log("监听到父级扫码状态",$status);
        if ($status*1 === 1) {
          this.device_status = 1;
          this.getBluetoothState();
        }
      }, immediate: true
    }
  },
  methods:{
    /**
     * 修改设备连接状态
     * @param $status 设备状态 0:为未连接，1:连接中，2:已连接 3:连接失败 5:取消连接
     */
    setDeviceStatus($status = 0) {
      $this.device_status = $status;
      $this.$emit("deviceStatus", $status);
    },
    /**
     * 获取蓝牙状态
     *
     */
    getBluetoothState() {
      // 获取本机蓝牙适配器状态
      wx.getBluetoothAdapterState({
        success: function (res) {
          if (res.available) {
            // 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源，请在搜索到需要的设备后及时调用 wx.stopBluetoothDevicesDiscovery 停止搜索。
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: true,
              success: () => {
                $this.onBluetoothFound();
              },
              fail() {
                // 失败取消连接
                $this.setDeviceStatus(3);
              },
            });
          } else {
            // 打印相关信息
            console.log(res["errMsg"])
            setTimeout(() => {
              Toast.fail({
                message: res["errMsg"],
              });
            }, 3000);
          }
        },
        fail: function (err) {
          // 打印相关信息
          console.log(err["errMsg"])
          setTimeout(() => {
            Toast.fail({
              message: err["errMsg"],
            });
          }, 3000);
        }
      })
    },
    /**
     * 监听搜索到新设备的事件
     */
    onBluetoothFound() {
      $this.bleFoundTimeOut = setTimeout(() => {
        if ($this.device_status === 0 || $this.device_status === 3) {
          // 移除搜索到新设备的事件的全部监听函数
          wx.offBluetoothDeviceFound();
          // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时，建议调用该接口停止蓝牙搜索。
          wx.stopBluetoothDevicesDiscovery();
          Dialog.confirm({
            message: '脑机连接失败',
            showCancelButton: true,
            cancelButtonText: "查看指引",
          }).catch(() => {
            mpvue.navigateTo({
              url: "/pages/banner/guide/main"
            })
          });
        }
      }, 7000)
      try {
        // 监听搜索到新设备的事件
        wx.onBluetoothDeviceFound((res) => {
          $this.code = ble_store.getters.getDeviceSn();
          res.devices.forEach((device) => {
            if (!device.name && !device.localName) { return; }
            if (device.localName && device.localName !== "") {
              device.name = device.localName;
            }
            if (device["name"].toUpperCase() === $this.code) {
              // 停止搜寻附近的蓝牙外围设备
              wx.stopBluetoothDevicesDiscovery();
              // 连接低功耗蓝牙设备
              $this.bLEConnection(device.deviceId);
              //$this.device_data.deviceId = device.deviceId;
              clearTimeout($this.bleFoundTimeOut);
              console.log("连接低功耗蓝牙设备：", JSON.stringify(device));
            }
          });
        });
      } catch (e) {
        console.log("打开蓝牙error", e);
        $this.setDeviceStatus(3);
      }
    },
    /**
     * 连接低功耗蓝牙设备
     */
    bLEConnection(deviceId) {
      // 移除搜索到新设备的事件的全部监听函数
      wx.offBluetoothDeviceFound();
      // 停止搜寻附近的蓝牙外围设备
      wx.stopBluetoothDevicesDiscovery();
      // 连接蓝牙低功耗设备。(若小程序在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备，无需再次进行搜索操作)
      wx.createBLEConnection({
        deviceId: deviceId,
        success: () => {
          // 协商设置蓝牙低功耗的最大传输单元 (Maximum Transmission Unit, MTU)。需在 wx.createBLEConnection 调用成功后调用。仅安卓系统 5.1 以上版本有效，iOS 因系统限制不支持。
          wx.setBLEMTU({
            deviceId,
            mtu: 250,
            success(res) {
              console.log("设置mtu成功", JSON.stringify(res));
            }
          })
          // $this.$bluetooth.current_device_sn = $this.code;
          ble_store.setters.setDeviceId(deviceId);
          // 获取蓝牙设备服务
          $this.$connection.getBLEDeviceServices(deviceId);
          //成功连接脑机蓝牙
          $this.setDeviceStatus(2);
          // 记录日志
          WechatLog.info("脑机蓝牙连接成功:", $this.code);
        },
        fail(err) {
          //连接脑机蓝牙失败
          $this.setDeviceStatus(3);
          console.log(err);
        },
      });
    },
    /**
     * 取消连接
     */
    cancelConnect() {
      clearTimeout($this.bleFoundTimeOut);
      $this.setDeviceStatus(5);
    },
  },
}
</script>

<template>
  <div>
    <van-row class="padding">
      <van-col span="5" offset="4">
        <div class="device_bg flex flex-direction align-center justify-center">
          <img src="https://img.shuimuai.com/web/phone.png" alt="" class="device_phone">
          <text class="text-gray device_text"> 我的手机</text>
        </div>
      </van-col>
      <van-col span="3" offset="1">
        <div class="dot_container flex align-center">
          <div class="dot_wait">
            <img v-if="status*1 === 1" src="https://img.shuimuai.com/web/dot.png" alt="" class="moving_dot"
                 :class="{moving: status*1 === 1}"
            />
            <img v-if="status*1 === 2" src="https://img.shuimuai.com/m_sign_gou%402x.png" alt="" class="moving_dot">
            <img v-if="status*1 === 3" src="https://img.shuimuai.com/fail.png" alt="" class="moving_dot">
          </div>
        </div>
      </van-col>
      <van-col span="5" offset="0">
        <div class="device_bg flex flex-direction align-center justify-center">
          <img src="https://img.shuimuai.com/web/brain.png" alt="" class="device_brain">
          <text class="text-gray device_text"> 水母智能脑机</text>
        </div>
      </van-col>
    </van-row>
    <van-row>
      <van-col span="9" offset="1">
        <button class="cu-btn bg-red lg text-white" @click="cancelConnect">
          <img src="https://img.shuimuai.com/m_duankainaohuan.png" class="cut_brain_icon" alt="">
          <text class="padding-lr cut_text">取消连接</text>
        </button>
      </van-col>
      <van-col span="12" offset="1">
        <text class="text-gray text-lg">
          <template v-if="status*1 === 1">
            连接中...
          </template>
          <template v-if="status*1 === 2">
            连接成功
          </template>
          <template v-if="status*1 === 3">
            连接失败
          </template>
        </text>
      </van-col>
    </van-row>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog"/>
  </div>
</template>

<style scoped></style>
