<script>
  let updateManager = null
  let canIUse = true

  class WxUpdate {
    updateManager = wx.getUpdateManager();
    canIUse = wx.canIUse('getUpdateManager');
    
    static getInstance(){
      if (!this.instance) {
        this.instance = new WxUpdate();
      }
      return this.instance
    }
    
    check() {
      const that = this
      if (that.canIUse) {
        that.updateManager.onCheckForUpdate(function(res) {
          if (res.hasUpdate) {
            wx.showModal({
              title: '更新提示',
              content: '检测到新版本，是否下载新版本并重启小程序？',
              success: function(res) {
                if (res.confirm) {
                  that.downLoadAndUpdateApplet()
                } else if (res.cancel) {
                  wx.showModal({
                    title: '温馨提示~',
                    content: '本次版本更新比较重要，旧版本可能无法正常访问的哦~',
                    showCancel: false,
                    confirmText: "确定更新",
                    success: function(res) {
                      if (res.confirm) {
                        that.downLoadAndUpdateApplet()
                      }
                    }
                  })
                }
              }
            })
          }
          // 不走if就是最新版
        })
      } else {
        that.downLoadAndUpdateWeChat()
      }
    }
    downLoadAndUpdateApplet() {
      const that = this;
      wx.showLoading();
      that.updateManager.onUpdateReady(function() {
        wx.hideLoading();
        that.updateManager.applyUpdate()
      })
      that.updateManager.onUpdateFailed(function() {
        wx.hideLoading();
        wx.showModal({
          title: '已经有新版本了哟~',
          content: '新版本已经上线啦~，请您删除当前小程序，重新从公众号或搜索打开小程序哟~',
        })
      })
    }
    downLoadAndUpdateWeChat() {
      wx.showModal({
        title: '重要提示',
        content: '您当前微信版本过低，使用过程可能会不稳定。点击确认立刻升级微信。',
        success: function(res) {
          if (res.confirm) {
            wx.updateWeChatApp({
              success: function(res) {
                console.log('res', res)
              },
              fail: function(err) {
                console.log('err', err)
              },
            })
          }
        }
      })
    }
  }

  export default {
    onLaunch: function() {
      //#ifdef MP-WEIXIN
      WxUpdate.getInstance()
      //#endif
    },
    onShow: function() {
      //#ifdef MP-WEIXIN
      const wxUpdate = WxUpdate.getInstance()
      wxUpdate.check();
      //#endif
    },
    onHide: function() {
      console.log('App Hide')
    }
  }
</script>

<style>
  /*每个页面公共css */
</style>
