// app.js

import Activity from './api/activity';
App({
  onLaunch() {
    // 展示本地存储能力
    var that = this;
    wx.checkSession({
      success: (res) => {
        var openId = wx.getStorageSync('loginInfo').openId;
        
        //过渡代码 以前存到前端的现在不存在了
        var sessionKey = wx.getStorageSync('loginInfo').sessionKey;
        if(!openId || sessionKey){
          that.login();
        }
      },
      fail () {
        // session_key 已经失效，需要重新执行登录流程
        that.login() //重新登录
      }
      
    })
    
   
  },
  checkInvalid(param={},callBack='') {
    let _self = this;
    wx.checkSession({
      success () {
        //session_key 未过期，并且在本生命周期一直有效
        if(typeof(callBack)==='function'){
          callBack(param);
        }
      },
      fail () {
        _self.login(function(){
           // session_key 已经失效，需要重新执行登录流程
          if(typeof(callBack)==='function'){
            callBack(param);
          }
        });
       
      }
    })
  },
   // 登录
   login() {
    wx.login({
      success: res => {
        let code = res.code;
        let result = Activity.getSessionKeyFromApi(code);
        result.then(res=>{
          wx.setStorageSync('loginInfo',{
            openId:res.openId,
          });
        });
       
      }
    })
  },

  

  async doDecodePhoneNew(code,call='') {
 
    //验证登录是否失效
      var params = {
        code:code,
        appCode:this.globalData.appCode
      };
      try {
        let res = Activity.getAuthMobileNew(params);   
        res.then(userInfo=>{
          console.log(userInfo)
          let mobile = userInfo.phoneNumber;
          // @todo从缓存里面取openId
          let openId = Activity.getOpenId();
          //保存用户信息
          Activity.saveUser(openId,mobile);
          Activity.setMobileCache(mobile);
          call();
        })
      }catch(err) {
        console.log(err);
      }
    
  },
  /**
   * 接口请求手机号
   * @param {*} encryptedData
   * @param {*} iv
   * @param call
   */
  async doDecodePhone(encryptedData,iv,call='') {
    let _self = this;
    //验证登录是否失效
    _self.checkInvalid({encryptedData:encryptedData,iv:iv,call:call},function(param){
      var params = {
        encryptedData: param.encryptedData,
        iv: param.iv,
        // sessionKey:Activity.getSessionKey(),
        openId:wx.getStorageSync('loginInfo').openId,
      };
      try {
        let res = Activity.getAuthMobile(params);   
        res.then(userInfo=>{
          let mobile = userInfo.phoneNumber;
          // @todo从缓存里面取openId
          let openId = Activity.getOpenId();
          //保存用户信息
          Activity.saveUser(openId,mobile);
          Activity.setMobileCache(mobile);
          if(param.call && typeof(param.call)=='function') {
            param.call();
          }
        })
      }catch(err) {
        console.log(err);
      }
    });
  },

  showToast(title,icon='success',time=2000,call='') {
    wx.showToast({
      title: title,
      icon: icon,
      duration: time,
      success:function(){
        if(typeof(call)=='function') {
          call();
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    appCode:'HSAY_SHARE_COUPON',
    typeSwitchObj : {"C":'现金券',"D":"折扣券"}
  },
  showLoading() {
    if (this._loadingLock) {
      return
    }
    this._loadingLock = true
    const page = this.getComponent("#Page")
    if (page) {
      page.setValue("showLoading", true)
    }
  },
  hideLoading() {
    const page = this.getComponent("#Page")
    if (page) {
      // setTimeout(_ => {
      //   page.setValue("showLoading", false)
      // }, 1000) 
      page.setValue("showLoading", false)
    }
    this._loadingLock = false
  },
  getComponent(id) {
    const page = getCurrentPages()[getCurrentPages().length - 1]
    return page.selectComponent(id)
  }
})
