// pages/deviceConnect0/deviceConnect0.ts
const app = getApp();
let xBlufi = require("../../utils/blufi/xBlufi.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '连接配网', //导航栏 中间的标题
    },
    devicesList: [],
    searching: false,
    version: '2.0',
    name: '',
    connectedDeviceId: '',
    connected: true,
    deviceInfo: null,
    isInitOK: false,
    customData: '',
    isOne: true,
    isSubmit: false,
    islanya: false,
    isOnBluetooth: false,
  },
  onShow() {
    if(!this.data.isOne) {
      this.Search();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const _this = this;
    const isOne = setTimeout(()=> {
      clearTimeout(isOne);
      if(_this.data.isOne) {
        _this.setData({
          isOne: false,
        });
      }
    }, 2000);
    if(app.globalData.oneInitBluetooth) {
      app.globalData.oneInitBluetooth = false;
      xBlufi.initXBlufi(1);
    };
    xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
    this.Search();
  },
  funListenDeviceMsgEvent: function(options) {
    const _this = this;
    switch (options.type) {
      case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
        // 搜索到蓝牙
        if (options.result) {
          if(options.data.filter((v)=> v.name.indexOf("BLUFI_") !== -1 ).length > 0) {
            _this.setData({
              islanya: true,
              devicesList: options.data.filter((v)=> v.name.indexOf("BLUFI_") !== -1 )
            });
          }
        }
          
        break;

      case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
        // console.log("连接回调：" + JSON.stringify(options))
        if (options.result) {
          wx.hideLoading();
          if(_this.data.isOnBluetooth) {
            return;
          };
          _this.setData({
            isOnBluetooth: true,
          });
          setTimeout(()=> {
            _this.setData({
              isSubmit: false,
              islanya: false,
              devicesList: [],
              isOnBluetooth: false,
            });
            wx.navigateTo({
              url: '../deviceConnect3/deviceConnect3?deviceId=' + options.data.deviceId + '&name=' + options.data.name,
            });
          }, 500);

        } else {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '连接失败',
            showCancel: false
          });
        }
        break;

      case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
        if (!options.result) {
          console.log("蓝牙未开启 fail =》", options)
          wx.showToast({
            title: '蓝牙未开启',
            icon: 'none'
          })
        } else {
          //蓝牙搜索开始
          _this.setData({
            searching: true
          });
        }
        break;

      case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
        if (options.result) {
          //蓝牙停止搜索ok
          console.log('蓝牙停止搜索ok')
        } else {
          //蓝牙停止搜索失败
          console.log('蓝牙停止搜索失败')
        }
        _this.setData({
          searching: false
        });
        break;

    }
  },
  Search: function() {
    xBlufi.notifyStartDiscoverBle({
      'isStart': true,
    });
  },
  Connect: function(e) {
    if(!this.data.islanya) {
      return;
    };
    const deviceIdData = this.data.devicesList;
    if(deviceIdData.length < 1) {
      wx.showToast({
        title: '请短按设备配对键',
        icon: 'none',
        duration: 2000
      });
      return;
    };
    
    if(this.data.isSubmit) {
      return;
    };
    this.setData({
      isSubmit: true
    });
    // 停止搜索
    xBlufi.notifyStartDiscoverBle({
      'isStart': false,
    });
    //开始连接
    let name = deviceIdData[0].name;
    // console.log('点击了，蓝牙准备连接的deviceId:' + deviceIdData[0].deviceId)
    xBlufi.notifyConnectBle({
      isStart: true,
      deviceId: deviceIdData[0].deviceId,
      name
    });
    wx.showLoading({
      title: '请稍后',
    });
  },
  onUnload: function() {
    xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
  },
  getBluetoothStatus() {
    app.getBluetoothStatus();
  },
  notRoter(){
    wx.navigateBack({
      delta: 1
    });
  },
})