// pages/deviceConnect3/deviceConnect3.ts
const app = getApp();
let xBlufi = require("../../utils/blufi/xBlufi.js");
let percentIn = null;
let _this = null;
let errTi = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scopeBluetooth: app.globalData.scopeBluetooth,
    ssid: app.globalData.ssid,
    password: app.globalData.pwdData,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '连接配网', //导航栏 中间的标题
    },
    version: '2.0',
    name: '',
    connectedDeviceId: '',
    connected: true,
    deviceInfo: null,
    isInitOK: false,
    customData: '',
    percent: 0,
    ruterStatus: 0, // 0 连接中 // 1 成功 // 2失败
  },
  onShow: function(options) {

  },
  onLoad: function(options) {
    _this = this;
    _this.setData({
      name: options.name,
      connectedDeviceId: options.deviceId,
    })
    xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
    xBlufi.notifyInitBleEsp32({
      deviceId: options.deviceId,
    });
    percentIn = setInterval(()=> {
      if(_this.data.percent === 100) {
        clearInterval(percentIn);
        _this.setData({
          ruterStatus: 2
        });
        return;
      };
      _this.data.percent++;
      _this.setData({
        percent: _this.data.percent
      });
    }, 600);
  },
  onUnload: function() {
    // 关闭蓝牙连接
    let _this = this
    xBlufi.notifyConnectBle({
      isStart: false,
      deviceId: _this.data.connectedDeviceId,
      name: _this.data.name,
    });
    xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
    clearTimeout(errTi);
    clearInterval(percentIn);
  },
  funListenDeviceMsgEvent: function(options) {
    let _this = this;
    switch (options.type) {
      
      case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
        _this.setData({
          connected: options.result
        });
        if (!options.result) {
          wx.showModal({
            title: '很抱歉提醒你！',
            content: '小程序与设备异常断开',
            showCancel: false, //是否显示取消按钮
            success: function(res) {
              wx.navigateBack({
                delta: 1
              });
            },
          })
        }
        break;


      case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT:
        wx.hideLoading();
        if (!options.result)
          errTi = setTimeout(()=> {
            _this.setData({
              ruterStatus: 2
            });
            clearTimeout(errTi);
            clearInterval(percentIn);
          }, 5000);
          
        else {
          
          // 配网成功
          if (options.data.progress == 100) {
            clearTimeout(errTi);
            clearInterval(percentIn);
            // 更新数据
            wx.getStorage({
              key: 'devicelist',
              success (res) {
                if(res.data) {
                  let arr = JSON.parse(res.data);
                  // 同一个设备
                  const devicelist = arr.filter((v)=> v.deviceId === _this.data.name);
                  if(devicelist.length > 0) {
                    arr = arr.filter((v)=> v.deviceId !== _this.data.name);
                  };
                  arr.unshift({
                    deviceId: _this.data.name,
                    name: _this.data.name,
                    state: "online"
                  });
                  wx.setStorage({
                    key:"devicelist",
                    data: JSON.stringify(arr),
                    success() {
                      _this.setData({
                        percent: 100,
                        ruterStatus: 1
                      });
                    }
                  })
                }
              },
              fail() {
                wx.setStorage({
                  key:"devicelist",
                  data: JSON.stringify([{
                    name: _this.data.name,
                    deviceId: _this.data.name,
                    state: "online"
                  }]),
                  success() {
                    _this.setData({
                      percent: 100,
                      ruterStatus: 1
                    });
                  }
                })
              }
            })
            // 记住密码
            wx.setStorage({
              key:"wifiInfo",
              data: JSON.stringify({"password": app.globalData.pwdData, "ssid": app.globalData.ssid})
            });
          }
        }
        break;
      case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
        wx.hideLoading();
        // console.log("初始化结果：", JSON.stringify(options))
        if (options.result) {
          console.log('初始化成功');
          _this.OnClickStart();
        } else {
          console.log('初始化失败')
          _this.setData({
            connected: false
          })
          _this.setData({
            ruterStatus: 2
          });
        }
        break;
    }
  },

  OnClickStart: function() {
    if (!app.globalData.ssid) {
      wx.showToast({
        title: 'SSID不能为空',
        icon: 'none'
      })
      return
    }

    if (!app.globalData.pwdData) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none'
      })
      return;
    }
    xBlufi.notifySendRouterSsidAndPassword({
      ssid: app.globalData.ssid,
      password: app.globalData.pwdData
    });
  },
  bindPasswordInput: function(e) {
    this.setData({
      password: e.detail.value
    })
  },
  bindCustomDataInput: function(e) {
    this.setData({
      customData: e.detail.value
    })
  },
  egen(){
    wx.navigateBack({
      delta: 1
    })
  },
  goIndex(){
    //  BLUFI_7cdfa1fd3cfc
    app.globalData.newDeviceId = this.data.name;
    wx.switchTab({
      url: `./../index/index`
    });
  }
})