const { $Message} = require('/component/iView/base/index');
const md5 = require('./utils/md5.js');
const secret = "117c0743819088468e590246464cc75e"
const {baseUrl, showMsg} = require("./utils/util.js");
const util = require('./utils/util.js');

App({
  globalData: {
    pageSize: 10,
    userInfo: {},
    departments: false,
    studyInfo: {},
  },
  onLaunch: function () {
    this.autoUpgrade()
  },
  autoUpgrade: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('res.hasUpdate====')
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                console.log('success====', res)
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    }
  },
  gotoLogin: function(){
    wx.navigateTo({
      url: `/pages/user/identify/index`,
    })
  },
  checkLogin: function(cb){
    if( this.globalData.userInfo){
      cb&&cb( this.globalData.userInfo );
    }else{
      this.formPost("user/info", {}).then( res=>{
        if( res.code == 200){
          this.setUserInfo( res.data )
          cb&&cb( this.data.user )
        }else{
          this.gotoLogin()
        }
      })
    }
  },
  message: function (content, type) {
    $Message({
      content: content,
      type: type
    });
  },
  formPost: function (action, data) {
    let uid = wx.getStorageSync('@userId')||0;
    let token = wx.getStorageSync('@token')||'';
    let timestamp = Date.now()
    let signstr = `weixin_${uid}_${token}_${timestamp}_${secret}`
    let signsure = md5.md5(signstr).toLowerCase()
    let headers = {
      'Content-Type': 'application/json',
      'x-token': token,
      'x-signsure': signsure,
      'x-timestamp': timestamp,
      'x-user-id': uid
    }
    return new Promise(function (resolve, reject) {
      wx.showNavigationBarLoading();
      wx.request({
        url: `${baseUrl}api/${action}`,
        header: headers,
        method: 'POST',
        data,
        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            showMsg( "请求异常" )
          }
          if( res.data.data && res.data.data.reload  ){
            wx.navigateTo({
              url: '/pages/user/identify/index',
            })
          }
          resolve(res.data);
        },
        fail(res) {
          showMsg( "请求错误" )
          resolve({});
        },
        complete(res) {
          wx.hideNavigationBarLoading();
        }
      })
    })
  },
  getUserInfo: function ( cb ) {
    let userInfo = this.globalData.userInfo
    if( userInfo && userInfo.token ){
      cb && cb( userInfo);
      return
    }
    let openid = wx.getStorageSync('@openid');
    // let openid="oG3Fi5ait37qL-3edzAkzysH5apU"
    if( !openid ) {
      cb && cb({});
      return
    }
    let param = {"openid": openid};
    this.formPost('Auth.wxLogin', param).then( res =>{
      if (res.code == 200) {
        this.setUserInfo(res.data);
      }
      cb && cb(res.data||{});
    })
  },
  getSystemInfo(  cb ){
    wx.getSystemInfo({
      success: function(res) {
        cb &&cb( res.system )
      }
    })
  },
  checkNavigateTo: function(url){
    let openid = wx.getStorageSync('@openid');
    if( !openid ) return this.gotoLogin()
    wx.navigateTo({url})
  },
  getDepartments: function( cb  ){
    if( this.globalData.departments ){
      cb&&cb( this.globalData.departments||[])
    }else{
      this.loadDepartments( cb )
    }
  },
  loadDepartments: function( cb ){
    this.formPost( 'base/loadDepartmentList', {}).then( res=>
      {
        if( res.code == 200){
          this.globalData.departments = res.data
          cb && cb( this.globalData.departments)
        }
      }
    )
  },
  setUserInfo: function (info) {
    let {token, user} = info
    this.globalData.userInfo = user;
    wx.setStorageSync('@token', token)
    wx.setStorageSync('@userId', user.userId )
    this.loadDepartments()
  }
})