// 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)
    })
  },
  // checkAuth: async function (force = true) {
  //   return new Promise(async (resolve,rej)=>{
  //     let that = this;
  //     // 0.检测是否开启各页面强制登陆
  //     let enabledOptions = wx.getStorageSync("enabledOptions");
  //     if (force || (enabledOptions && enabledOptions["check-auth"])) {
  //       let invite = wx.getStorageSync('invite')
  //       let token = wx.getStorageSync('sessionToken')
  //       if(!token){
  //         token = await this.getParseToken()
  //         let userInfo = wx.getStorageSync("userInfo");
  //         that.globalData.userInfo = userInfo
  //         if(!token){
  //           wx.showModal({
  //             title: '提示',
  //             content: '获取登录信息失败,请删除小程序重新进入',
  //             showCancel: true,
  //             cancelText: '取消',
  //             cancelColor: '#000000',
  //             confirmText: '确定',
  //             confirmColor: '#3CC51F',
  //             success: (result) => {
  //               if(result.confirm){
  //                 wx.exitMiniProgram()
  //               }
  //             },
  //           });
  //           resolve(false)
  //           return
  //         }
  //       }
  //       Parse.User.become(token).then(async currentUser => {
  //         console.log(currentUser)
  //         if (invite && !currentUser.get('invite') && currentUser.id != invite && !currentUser.get('agentLevel')) {
  //           //查询邀请人user,邀请人不能是自己的下级
  //           let query = new Parse.Query("_User")
  //           query.equalTo('objectId',invite)
  //           query.select('invite')
  //           let result = await query.first()
  //           if (!(result && result.id && result.get("invite")?.id == currentUser.id)) {
  //             console.log('上下级绑定成功');
  //             currentUser.set('invite', {
  //               __type: "Pointer",
  //               className: "_User",
  //               objectId: invite
  //             })
  //             currentUser.set('agent', {
  //               __type: "Pointer",
  //               className: "_User",
  //               objectId: invite
  //             })
  //             await currentUser.save()
  //           }
  //         }
  //         currentUser.get('mobile') ? wx.setStorageSync("userLogin", currentUser.id) : wx.removeStorageSync("userLogin");
  //         resolve(currentUser)
  //         return true
  //       }).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)
  //       })
  //     } else {
  //       resolve(false) 
  //     }
  //   })
  // },

  // async getParseToken(){
  //   return new Promise((resolve, reject) => {
  //     wx.login({
  //       success: function (res) {
  //         if (res.code) {
  //           let url = 'https://server.fmode.cn/api/wxapp/login'
  //           wx.request({
  //             url: url,
  //             data: {
  //               companyId: getApp().globalData.company,
  //               code: res.code,
  //               appType: getApp().globalData.appType ? getApp().globalData.appType : ''
  //             },
  //             async success(res) {
  //               console.log(res);
  //               let data = res.data
  //               if(data.code == 200){
  //                 wx.setStorageSync("sessionToken", data.data.token);
  //                 wx.setStorageSync("userInfo", data.data?.userInfo);
  //                 resolve(data.data.token)
  //               }else{
  //                 resolve()
  //               }
  //             },
  //           });
  //         }
  //       },
  //       fail: function (err) {
  //         console.warn('小程序wx.login失败');
  //         resolve()
  //       }
  //     });
  //   })
  // },


  //获取全局定位信息
  // async getLocationInfo(refrensh = false) {
  //     let that = this;
  //     let locationInfo = that.globalData.locationInfo;
  //     if (locationInfo && !refrensh) {
  //         return locationInfo;
  //     } else {
  //         let locationInfo = await util.getLocation();
  //         that.globalData.locationInfo = locationInfo;
  //         return locationInfo;
  //     }
  // },
  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,
            })
          }
        });
      }
    }
  }

})