// app.ts
import btHelper from './devices/bt_helper';
import mqtt from './utils/mqtt';
//连接的服务器域名
// const host = 'wxs://mqtt.test.radio1964.com';
const host = 'wxs://mqtt.ssl.keepradioon.net:8884'

// const host = 'wxs://mqtt.test.radio1964.com:8884';
// const host = 'wxs://mqtt.ssl.keepradioon.net:8884'
App({
  globalData: {
    statusBarHeight: 0,
    navBarHeight: 0,
    MenuButtonheight: 0,
    MenuButtonTop: 0,
    scopeBluetooth: true,
    ssid: "",
    pwdData: "",
    userData: null,
    userInfo: null,
    newDeviceId: null,
    is_debug: 2, // 1 测试环境 // 2正式环境
    client: null,
    oneInitBluetooth: true,
    isIOS: false,
    isAndroid: false,
    isHuaWei: false,
    // 设备列表，跟app同步字段
    classifyProducts: [],
    //MQTT连接的配置
    options: {
      clientId: "wx_" + parseInt(Math.random() * 100 + 800, 10),
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true
      keepalive: 3, //每3秒发送一次心跳
    },
  },
  /**
   * 连接设备
   * mqttCallback：mqtt回调统一方法
   */
  connect() {
    this.globalData.client = mqtt.connect(host, this.globalData.options);
    // 连接成功
    this.globalData.client.on('connect', () => {
      const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
      if (pageinfo.mqttCallback) {
        pageinfo.mqttCallback("connect")
      };

    });
    // 接收消息
    this.globalData.client.on("message", function (topic, payload) {
      wx.hideLoading();
      const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
      const thisPageIsIndex = getCurrentPages().length === 1;
      if (pageinfo.mqttCallback) {
        if (topic.indexOf("status/onoffline") !== -1) {
          pageinfo.mqttCallback("message_onoffline", {
            topic,
            payload
          });
          if (!thisPageIsIndex) {
            getCurrentPages()[0].mqttCallback("message_onoffline", {
              topic,
              payload
            })
          }
        } else if (topic.indexOf("user/pub_response") !== -1) {
          pageinfo.mqttCallback("message", {
            topic,
            payload
          });
        }
      };
    });
    //服务器连接异常的回调
    this.globalData.client.on("error", function (error) {
      console.log(" 服务器 error 的回调" + error)
      const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
      if (pageinfo.mqttCallback) {
        pageinfo.mqttCallback("error")
      };
    })

    // 服务器重连
    this.globalData.client.on("reconnect", function (errr) {
      console.log(" 服务器 reconnect的回调", errr);
      const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
      if (pageinfo.mqttCallback) {
        pageinfo.mqttCallback("reconnect")
      };
    })
    //服务器断开连接
    this.globalData.client.on("offline", function (errr) {
      console.log(" 服务器 offline的回调", errr)
      const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
      if (pageinfo.mqttCallback) {
        pageinfo.mqttCallback("offline")
      };
    })
  },



  // 订阅主题
  subscribe: function (topic, callback) {

    if (this.globalData.client && this.globalData.client.connected) {
      //订阅主题
      this.globalData.client.subscribe(topic, function (err, granted) {
        if (!err) {
          if (callback) {
            callback();
          }
          console.log("订阅成功");
        } else {
          console.log('订阅主题失败');
        }
      })
    } else {
      console.log("服务器已断开");
      // wx.showToast({
      //   title: '服务器已断开',
      //   icon: 'error',
      //   duration: 2000
      // })
    }
  },
  // 取消订阅
  unsubscribe: function (Topic) {
    if (this.globalData.client && this.globalData.client.connected) {
      this.globalData.client.unsubscribe(Topic);
    } else {
      console.log('请先连接服务器');
      // wx.showToast({
      //   title: '请先连接服务器',
      //   icon: 'none',
      //   duration: 2000
      // })
    }
  },

  /**
   * 发布信息
   * @param {*} data
   * DstDeviceName：目标设备
   * type: 指令
   * other：other
   * .......................
   * AIrSMArT_: 设备前缀
   */
  PubMsg(option, callback) {
    if (this.globalData.client && this.globalData.client.connected) {
      wx.showLoading({
        title: '请稍后',
      });
      const data = {
        "DstDeviceName": option.DstDeviceName,
        "SrcDeviceName": `ALY_${this.globalData.userInfo.userId}`,
        "type": option.type
      };
      if (option.other) {
        data.other = option.other;
      };
      this.globalData.client.publish(`/${option.DstDeviceName}/user/sub_control`, `${JSON.stringify(data)}`, (err) => {
        if (err) {
          console.log("发布消息失败");
        }
      });
    } else {
      console.log("服务器已断开");
      // wx.showToast({
      //   title: '服务器已断开',
      //   icon: 'error',
      //   duration: 2000
      // })
    }
  },
  onLaunch() {
    var _this = this;
    wx.onAppHide(() => {
      if (_this.globalData.client && _this.globalData.client.connected) {
        _this.globalData.client.end(true);
        _this.globalData.client.end(true);
        console.log("断开");
      };
    });

    wx.onAppShow(() => {
      console.log("加载")
      if (_this.globalData.userInfo !== null) {
        if (_this.globalData.client) {
          _this.globalData.client.end(true);
          _this.globalData.client.end(true);
        }
        console.log("重连");
        _this.connect();
      };
    });
    this.getBluetoothStatus();
    //自定义导航栏 获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
    wx.getSystemInfo({
      success: (res) => {
        let custom = wx.getMenuButtonBoundingClientRect();

        _this.globalData.navBarHeight = res.statusBarHeight + custom.height + (custom.top - res.statusBarHeight) * 2;
        _this.globalData.MenuButtonheight = custom.height;
        _this.globalData.MenuButtonTop = custom.top;
        const platform = res.platform;
        _this.globalData.isIOS = platform == "ios";
        _this.globalData.isAndroid = platform == "android";
      }

    })
  },
  // 获取蓝牙权限
  getBluetoothStatus() {
    const _this = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting["scope.bluetooth"]) {
          _this.globalData.scopeBluetooth = true;
        } else if (res.authSetting["scope.bluetooth"] === undefined) {
          _this.globalData.scopeBluetooth = false;
          wx.authorize({
            scope: "scope.bluetooth",
            complete() {
              _this.getBluetoothStatus();
            }
          });
        } else {
          _this.globalData.scopeBluetooth = false;
          wx.showModal({
            title: '请打开系统蓝牙进行配网',
            content: '如已打开蓝牙仍然弹框，请尝试重启小程序',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.openSetting({
                  complete() {
                    // _this.getBluetoothStatus();
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        };
        if (getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck) {
          getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck(_this.globalData.scopeBluetooth);
        }
        // res.authSetting = {
        //   "scope.userInfo": true,
        //   "scope.userLocation": true
        // }
      }
    })
  },
})


// "tabBar": {
//   "borderStyle": "black",
//   "list": [{
//       "pagePath": "pages/index/index",
//       "text": "首页",
//       "iconPath": "./img/index_unaction.png",
//       "selectedIconPath": "./img/index_action.png"
//     },
//     {
//       "pagePath": "pages/me/me",
//       "text": "我的",
//       "iconPath": "./img/me_unaction.png",
//       "selectedIconPath": "./img/me_action.png"
//     }
//   ]
// },