// pages/connectBle/connectBle.js
const {
  BtHelper
} = require('../../devices/bt_helper');
const toastUtil = require('../../utils/toast_util');
import routeUtil from '../../utils/route_util'
import route_constant from '../../utils/route_constant.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    connectDevice: {},
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '连接设备', //导航栏 中间的标题
      callback() {
        wx.navigateBack({
          delta: 1,
        })
      }
    },
    connectStatus: 0,
    searchTips: "正在搜索设备，请保持开机状态…",
    subTips: "确认手机蓝牙已打开",
    buttonTips: "正在搜索设备",
    btHelper: null

  },
  setStatus(bleType) {
    var searchTips = ""
    var subTips = ""
    var buttonTips = ""
    let name = this.data.connectDevice.name;
    console.log("搜索状态", bleType)
    switch (bleType) {
      case 0:
        // 搜索中
        searchTips = "正在搜索设备，请保持开机状态…"
        subTips = "确认手机蓝牙已打开"
        buttonTips = "正在搜索设备"

        break;
      case 1:
        // 搜索失败
        searchTips = "未搜索到" + name
        subTips = "请检查设备是否被其他手机连接，或在手机蓝牙忽略掉原来的蓝牙连接重新连接。"
        buttonTips = "重新搜索"

        break;
      case 2:
        // 搜索到
        searchTips = "搜索到" + name
        subTips = ""
        buttonTips = "连接"
        break;
      case 3:
        // 连接成功
        searchTips = "连接到" + name
        subTips = ""
        buttonTips = "连接成功"
        break;
      case 4:
        // 连接失败
        searchTips = "未连接到" + name
        subTips = "请检查设备是否被其他手机连接，或在手机蓝牙忽略掉原来的蓝牙连接重新连接。"
        buttonTips = "重新搜索"
        break;

    }

    this.setData({
      searchTips: searchTips,
      subTips: subTips,
      buttonTips: buttonTips,
      connectStatus: bleType
    })
  },
  async connectDeviceTap() {
    let _this = this
    console.log("点击搜索状态", this.data.connectStatus)

    switch (this.data.connectStatus) {
      case 0:
        // 搜索中
        break;
      case 1:
      case 4:
        // 搜索失败，点击重新搜索
        _this.startSearch()
        break;
      case 2:
        _this.connectToDvice()
        break;
      case 3:
        // 连接成功
        break;
    }
  },
  connectToDvice() {
    toastUtil.show("开始连接设备")

    let _this = this
    //  搜索到
    this.data.btHelper.connect(_this.data.connectDevice, function (data) {
      console.log("连接成功：", data)

      _this.setStatus(data ? 3 : 4)
      if (data) {
        // 蓝牙模式
        _this.data.connectDevice.connectType = 1
        // getApp().globalData.device = _this.data.connectDevice

        // {"applicationType":"[0, 1]","deviceId":"D9:8D:D8:76:42:16","img":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100711728016597.png","offlineImg":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100714667384264.png","connectImg":null,"name":"猫王音响·小王子 OTR-X","bluetoothName":"猫王音响·小王子 OTR-X","bluetoothNames":["猫王音响·小王子 OTR-X"],"isChannelsPlatforms":0,"platform":-1,"typeList":[{"is5g":0,"type":1,"connectType":1,"functionList":[1,3,6],"deviceLinkResp":{"icon1":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100644913162836.png","icon2":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100648938942906.png","icon":null,"guideUrl":null}},{"is5g":0,"type":2,"connectType":3,"functionList":[1,3],"deviceLinkResp":{"icon1":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20230313155903515728925.png","icon2":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20230313155910706032704.png","icon":null,"guideUrl":null}}],"clientType":"MW-2AX(WIFI)","firstVersion":"0.0.1","filter":null,"guideUrl":null,"manufacturer":"ShanJing","deviceType":0,"mac":"598dd876e2160000",

        var connectDevice = _this.data.connectDevice;
        getCurrentPages()[0].addConnectBlueDevice(connectDevice);
        setTimeout(() => {
          // wx.redirectTo({
          //   url: '/pages/index/index'
          // });
          wx.navigateTo({
            url: '/pages/deviceDetail/detail'
          });
        }, 200);
      }

    })
  },
  getConnectedDevices: async function () {
    let _this = this
    const connectedDevices = await this.data.btHelper.getConnectedDevices()
    console.log("全部设备", connectedDevices)
    if (connectedDevices.length > 0) {
      connectedDevices.forEach(element => {
        console.log('已连接的蓝牙设备:', element);
        _this.didFindDevice(element)

      });
    } else { }
    return connectedDevices;
  },
  async startSearch() {
    this.setStatus(0)
    let _this = this
    this.data.btHelper.search(async function () {
      const connectedDevices = await _this.getConnectedDevices()
      if (connectedDevices.length == 0) {
        _this.setStatus(1)
      }
    })

  },

  findAllDevice() {
    let _this = this
    this.data.btHelper.findDevices(function (devices) {
      devices.forEach(element => {
        console.log('发现设备2:', element);

        _this.didFindDevice(element)
      });
    })
  }, didFindDevice(element) {
    let deviceId = element.deviceId
    let _this = this
    // todo 暂定这样

    if (
      // deviceId.includes("D8:24:07:89:31") ||
      // // 2axk
      // element.deviceId.includes("F5:A5:43:70:C8:F1") ||
      // // 黑色2x
      // element.deviceId.includes("F6:61:D8:24:E5:98")
      // /// mac: D7:92:84:87:09:7D
      // ||
      // element.deviceId.includes("F6:61:D8:24:E5:98") ||
      // 黑胶
      deviceId.includes("00:33:52:A7:3E:D0")
    ) {
      if (element.connectable == true) {
        _this.data.connectDevice.mac = element.mac
        _this.data.connectDevice.deviceId = element.deviceId
        _this.data.btHelper.stopSearch()
        _this.setStatus(2)
      }

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this
    const btHelper = BtHelper.getInstance();
    this.data.btHelper = btHelper;
    // getApp().globalData.btHelper = btHelper.getInstance();


    btHelper.initBluetooth(function (adapterState, hasPermission) {
      console.log("蓝牙状态", adapterState, hasPermission)
      if (adapterState && hasPermission) {
        // wx.getSystemInfo({
        //   success: function (res) {
        //     // { "screenWidth": 407, "cpuType": "unknown", "phoneCalendarAuthorized": true, "windowHeight": 888, "bluetoothEnabled": true, "bluetoothAuthorized": true, "language": "zh_CN", "microphoneAuthorized": true, "fontSizeScaleFactor": 1, "locationAuthorized": true, "notificationAuthorized": true, "model": "23078RKD5C", "statusBarHeight": 35, "safeArea": { "width": 407, "right": 407, "top": 35, "left": 0, "bottom": 888, "height": 853 }, "brand": "Redmi", "windowWidth": 407, "locationEnabled": true, "benchmarkLevel": 15, "screenHeight": 888, "abi": "arm64-v8a", "version": "8.0.53", "cameraAuthorized": true, "deviceAbi": "arm64-v8a", "system": "Android 14", "memorySize": 15367, "fontSizeSetting": 16, "pixelRatio": 3, "deviceOrientation": "portrait", "wifiEnabled": true, "screenTop": 0, "errMsg": "getSystemInfo:ok", "platform": "android", "SDKVersion": "3.6.6", "enableDebug": false, "devicePixelRatio": 3, "host": { "env": "WeChat", "version": 671102271 }, "mode": "default" }
        //     console.log('UUID: ' + JSON.stringify(res));
        //     console.log('MAC: ' + res.macaddress);
        //   }
        // });
        _this.setStatus(0)
        _this.startSearch()
      } else {
        _this.setStatus(1)
      }
    })

    _this.findAllDevice()

    let json = JSON.parse(options.param)
    console.log("要连接设备：", json)
    this.setData({
      connectDevice: json
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // todo 要关闭吗
    // this.data.btHelper.closeBle()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})