const getReq = require('../config.js').getReq
const api    = require('../config.js').host
export default class WxAuthor {
  constructor(app) {
    this.target = app
    this.init()
  }
  // 首先wx.login
  init() {
    wx.login({
      success: res => {
        this.ministart(res.code)
      }
    })
  }
  // 拿到code 请求act=login op=ministart
  ministart(code) {
    let params = {
      act: "login",
      op: "ministart",
      code
    }
    getReq(params, res => {
      if (res.code == 200) {
        let { openid, unionid, HPHPSESSID } = res.datas
        wx.setStorageSync('session_id', HPHPSESSID);
        if (openid && unionid) {
          this.setId(openid, unionid)
          this.getSetting(false)
        } else {
          this.getSetting(true)
        }
      }
      else {
        return
      }
    })
  }

  getSetting(flag) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          this.getUserInfo(flag)
        }
        else {
          return
        }
      }
    })
  }

  getUserInfo(flag) {
    let withCredentials = flag
    wx.getUserInfo({
      withCredentials,
      success: res => {
        this.setUserInfo(res.userInfo, res.userInfo.nickName)
        let userInfo = this.target.globalData.userInfo
        if (flag) {
          let { encryptedData, signature, iv } = res
          userInfo = Object.assign({}, { encryptedData }, { signature }, { iv }, userInfo)
        }
        else {
          userInfo = Object.assign({}, this.target.globalData.userId, userInfo)
        }
        this.wxauthen(userInfo)
      }
    })
  }
  wxauthen(userInfo) {
    let params = {
      user_info: userInfo,
      act: "login",
      op: "wxauthen"
    }
    getReq(params, res => {
      if (res.code == 200) {
        let url = this.getUrl()
        wx.reLaunch({
          url
        })
      }
      else {
        wx.showToast({
          icon: 'none',
          title: '登陆失败',
          duration: 2000
        })
      }
    })
  }

  getUrl() {
    let len = getCurrentPages().length
    let currentPage = getCurrentPages()[len - 1]
    let params = ''
    if (currentPage.options) {
      for (let k in currentPage.options) {
        params = params + k + '=' + currentPage.options[k] + '&'
      }
      params = params.slice(0, params.length - 1)
    }
    let current_url = "/" + currentPage['route']
    if (params) {
      current_url = current_url + '?' + params
    }
    return current_url
  }

  // 设置用户信息
  setUserInfo(userInfo, nickName) {
    this.target.globalData.userInfo = userInfo
    this.target.globalData.userInfo.nickname = nickName
  }

  //设置openid, unionid
  setId(openid, unionid) {
    this.target.globalData.userId.openid = openid
    this.target.globalData.userId.unionid = unionid
  }
}