import mqtt from './utils/mqtt';
import update from './utils/update';
import strings from './utils/strings';
import store from './utils/store.js';
import env from './utils/env.js';

//连接的服务器域名
// const host = 'wxs://mqtt.test.radio1964.com';
// const host = 'wxs://mqtt.ssl.keepradioon.net:8884'

const iosHost = 'wxs://mqtt.test.radio1964.com:8884';
const androidHost = 'wxs://mqtt.ssl.keepradioon.net:8884'
App({
  globalData: {
    isRelease: true,
    is_debug: 2, // 1 测试环境 // 2正式环境
    baseUrl: env.prod.baseUrl,

    userInfo: null,
    classifyProducts: "",
    statusBarHeight: 0,
    safeBottomHeight: 0,
    navBarHeight: 0,
    MenuButtonheight: 0,
    MenuButtonTop: 0,
    scopeBluetooth: true,
    ssid: "",
    pwdData: "",
    userData: null,
    client: null,
    oneInitBluetooth: true,

    mDeviceList: [],
    // 当前设备
    // device: {},
    // 设备列表，跟app同步字段
    classifyProducts: [],
    //MQTT连接的配置
    host: iosHost,
    options: {
      clientId: "wx_" + parseInt(Math.random() * 100 + 800, 10),
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true)
      keepalive: 3, //每3秒发送一次心跳
    },
  },

  ///全局初始化
  onLaunch() {
    var that = this;
    that.globalData.is_debug = that.globalData.isRelease ? 2 : 1;
    that.globalData.baseUrl = that.globalData.isRelease ? env.prod.baseUrl : env.test.baseUrl;

    ///用户信息
    var userInfo = store.getStore("userInfo");
    if (!strings.isEmpty(userInfo)) {
      that.globalData.userInfo = userInfo;
    }

    ///设备列表
    var classifyProducts = store.getStore("classifyProducts");
    if (!strings.isEmpty(classifyProducts)) {
      that.globalData.classifyProducts = classifyProducts;
    }
    //自定义导航栏 获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
    const res = wx.getSystemInfoSync(); // 获取系统信息
    /// android ios
    const platform = res.platform; // 获取平台类型
    if (platform === 'android') {
      that.globalData.host = androidHost;
    }

    const safeArea = res.safeArea;
    var height = safeArea.height || 0;
    var bottom = safeArea.bottom || 0;
    var reduce = bottom - height;
    var safeBottomHeight = reduce > 0 ? reduce : -reduce;
    that.globalData.safeBottomHeight = safeBottomHeight;

    let custom = wx.getMenuButtonBoundingClientRect();
    that.globalData.navBarHeight = res.statusBarHeight + custom.height + (custom.top - res.statusBarHeight) * 2;
    that.globalData.MenuButtonheight = custom.height;
    that.globalData.MenuButtonTop = custom.top;
    // var platform = res.platform;
    // that.globalData.isIOS = platform == "ios";
    // that.globalData.isAndroid = platform == "android";

    ///显示界面
    wx.onAppShow(() => {
      if (!(that.globalData.client && that.globalData.client.connected)) {
        that.connect();
      }
    });

    ///界面后台化
    wx.onAppHide(() => {
      // if (that.globalData.client && that.globalData.client.connected) {
      //   that.globalData.client.end(true);
      // };
    });
  },

  onShow: function () {
    update.update();
  },

  onHide: function () {},

  ///连接设备
  connect() {
    var that = this;
    var options = that.globalData.options;
    var host = that.globalData.host;
    that.globalData.client = mqtt.connect(host, options);

    // 设备连接
    that.globalData.client.on('connect', () => {
      var pages = getCurrentPages();
      var length = pages.length;
      var currentPage = pages[length - 1];
      if (!strings.isEmpty(currentPage.mqttCallback)) {
        currentPage.mqttCallback("connect")
      };
      ///多个界面回调首页
      if (length > 1) {
        pages[0].mqttCallback("connect");
      }
    });

    // 消息回调 wx.hideLoading();
    that.globalData.client.on("message", function (topic, payload) {
      var pages = getCurrentPages();
      var length = pages.length;
      var currentPage = pages[length - 1];
      if (topic.indexOf("status/onoffline") !== -1) {
        ///当前界面回调
        if (!strings.isEmpty(currentPage.mqttCallback)) {
          currentPage.mqttCallback("message_onoffline", {
            topic,
            payload
          });
        }
        if (length > 1) {
          pages[0].mqttCallback("message_onoffline", {
            topic,
            payload
          });
        }
      } else if (topic.indexOf("user/pub_response") !== -1) {
        if (!strings.isEmpty(currentPage.mqttCallback)) {
          currentPage.mqttCallback("message", {
            topic,
            payload
          });
        }
        if (length > 1) {
          pages[0].mqttCallback("message", {
            topic,
            payload
          });
        }
      }
    });

    // 重连
    that.globalData.client.on("reconnect", function (errr) {
      console.log("reconnect的回调==" + JSON.stringify(errr))
      var pages = getCurrentPages();
      var length = pages.length;
      var currentPage = pages[length - 1];
      if (!strings.isEmpty(currentPage.mqttCallback)) {
        currentPage.mqttCallback("reconnect")
      };
      if (length > 1) {
        pages[0].mqttCallback("reconnect");
      }
    });

    // 离线回调
    that.globalData.client.on("offline", function (errr) {
      console.log("offline的回调==" + JSON.stringify(errr))
      var pages = getCurrentPages();
      var length = pages.length;
      var currentPage = pages[length - 1];
      if (!strings.isEmpty(currentPage.mqttCallback)) {
        currentPage.mqttCallback("offline")
      };
      if (length > 1) {
        pages[0].mqttCallback("offline");
      }
    });

    // 错误回调
    that.globalData.client.on("error", function (error) {
      console.log("错误码的回调==" + JSON.stringify(errr))
      var pages = getCurrentPages();
      var length = pages.length;
      var currentPage = pages[length - 1];
      if (!strings.isEmpty(currentPage.mqttCallback)) {
        currentPage.mqttCallback("error", {})
      };
      if (length > 1) {
        pages[0].mqttCallback("error", {});
      }
    });
  },

  // topic
  // /AIrSMArT_7cdfa1fd3af0/status/onoffline
  // /AIrSMArT_7cdfa1fd3af0/user/pub_response
  // 订阅主题
  subscribe: function (topic, callback) {
    var that = this;
    if (that.globalData.client && that.globalData.client.connected) {
      //订阅主题
      // err:null
      // granted:[{"topic":"/AIrSMArT_861210052355545/status/onoffline","qos":0}]
      that.globalData.client.subscribe(topic, function (err, granted) {
        if (!err) {
          if (callback) {
            callback();
          }
          console.log("订阅成功===" + topic);
        } else {
          console.log('订阅主题失败');
        }
      })
    } else {
      console.log("服务器已断开");
    }
  },

  // 取消订阅
  unsubscribe: function (topic) {
    var that = this;
    if (that.globalData.client && that.globalData.client.connected) {
      that.globalData.client.unsubscribe(topic);
    } else {
      console.log('请先连接服务器');
    }
  },

  /**
   * 发布信息
   * @param {*} data
   * DstDeviceName：目标设备
   * type: 指令
   * other：other
   * .......................
   * AIrSMArT_: 设备前缀
   */
  PubMsg(option, callback) {
    var that = this;
    if (strings.isEmpty(that.globalData.userInfo)) {
      return;
    }

    // {"type":"get_dev_info","DstDeviceName":"AIrSMArT_7cdfa1fd3af0"}
    // get_dev_info
    var type = option.type;
    // AIrSMArT_7cdfa1fd3af0
    var DstDeviceName = option.DstDeviceName;
    // ALY_933625
    var SrcDeviceName = `ALY_${that.globalData.userInfo.userId}`;
    if (that.globalData.client && that.globalData.client.connected) {
      const data = {
        "type": type,
        "DstDeviceName": DstDeviceName,
        "SrcDeviceName": SrcDeviceName,
      };
      if (option.other) {
        data.other = option.other;
      };

      // /AIrSMArT_7cdfa1fd3af0/user/sub_control
      var publish = `/${DstDeviceName}/user/sub_control`;
      // {"type":"get_dev_info","DstDeviceName":"AIrSMArT_7cdfa1fd3af0","SrcDeviceName":"ALY_933625"}
      var dataString = `${JSON.stringify(data)}`;
      that.globalData.client.publish(publish, dataString, (err) => {
        if (err) {
          console.log("发布消息失败");
        }
      });
    } else {
      console.log("服务器已断开");
    }
  },

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

        if (getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck) {
          getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck(that.globalData.scopeBluetooth);
        }
      }
    });
  },
})