// app.js
let Nova = require("./utils/nova.js");
const CONFIG = require("config.js");
const request = require("./utils/request");
const plugin = requirePlugin('fm-plugin')
const { Parse } = plugin
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
    if (extConfig && extConfig.company) {
      this.globalData.company = extConfig.company
      this.globalData.appid = extConfig.wxappid
    }
    let {
      model,
      platform,
      statusBarHeight,
      safeArea,
      screenHeight
    } = wx.getSystemInfoSync();
    this.globalData.platform = platform;
    this.globalData.statusBarHeight = statusBarHeight;
    this.globalData.safeArea = safeArea;
    this.globalData.screenHeight = screenHeight;
    this.globalData.isIpx = model.includes("iPhone X");

    let {
      system
    } = wx.getSystemInfoSync();
    let headHeight;
    if (/iphone\s{0,}x/i.test(model)) {
      headHeight = 88;
    } else if (system.indexOf("Android") !== -1) {
      headHeight = 68;
    } else {
      headHeight = 64;
    }
    this.globalData.headerHeight = headHeight;
  },
  Nova: Nova,
  Parse: Parse,
  JIMData: {
    convers: [],
    messages: {},
  },
  globalData: {
    userInfo: null,
    theme: CONFIG.default.theme,
    //腾讯地图的key
    tencentKey: CONFIG.default.tencentKey,
    // NovaCloud
    ncloud: request,
    // JMessage
    jmessage: CONFIG.default.jmessage,
    // We7
    api: CONFIG.default.api,
    approot: CONFIG.default.approot,
    // Tabbar
    defaultTabBar: CONFIG.default.defaultTabBar,
    // checkAuth
    appid: CONFIG.default.appid,
    company: CONFIG.default.company,
    rootPage: CONFIG.default.rootPage,
    appType: CONFIG.default.appType,
    //获取相关tabs的name
    moduleTab:CONFIG.default.moduleTab,
  },
  checkAuth: plugin.checkAuth,
  parseLogin(token){
    return Parse.User.become(token).then(async currentUser => {
      console.log(currentUser)
      resolve(currentUser)
    }).catch(err => {
      wx.setStorageSync("sessionToken", null);
      wx.showModal({
        title: '提示',
        content: '登录信息过期,请退出重新进入小程序',
        showCancel: false,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            wx.exitMiniProgram()
          }
        },
      });
      rej(err)
    })
  },
  onShow: function (options) {
    this.autoUpdate()
    let { referrerInfo } = options
    if(referrerInfo?.extraData?.status && referrerInfo.extraData.status == 'success'){
      getApp().globalData.merchant_trade_no = referrerInfo.extraData.req_extradata.merchant_trade_no
    }
  },
  autoUpdate() {
    let self = this
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本,是否下载新版本并重启小程序?',
            success: function (res) {
              if (res.confirm) {
                //2. 用户确定下载更新小程序,小程序下载及更新静默进行
                self.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                //用户点击取消按钮的处理,强制更新
                wx.showModal({
                  title: '温馨提示~',
                  content: '本次版本更新涉及到新的功能添加,旧版本无法正常访问的哦~',
                  showCancel: false,
                  confirmText: "确定更新",
                  success: function (res) {
                    if (res.confirm) {
                      //下载新版本,并重新应用
                      self.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      })
    }
  },
  /**
   * 下载小程序新版本并重启应用
   */
  downLoadAndUpdate(updateManager) {
    wx.showLoading();
    //静默下载更新小程序新版本
    updateManager.onUpdateReady(function () {
      wx.hideLoading()
      //新的版本已经下载好,调用 applyUpdate 应用新版本并重启
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~',
      })
    })
  },
  onHide: function () {
    let pages = getCurrentPages()
    if (pages.length > 0) {
      let prevPage = pages[pages.length - 1]
      if (prevPage.route === 'nova-exam/pages/live-pusher/index') {
        prevPage.data.client.leave()
        prevPage.stop()
        prevPage.data.timer && clearInterval(prevPage.data.timer)
        wx.showModal({
          title: '提示',
          content: '考生将应用切换至后台,请重新进入',
          showCancel: false,
          success: (res) => {
            wx.navigateBack({
              delta: 1,
            })
          }
        });
      }
    }
  }

})