import { wxLogin, myself, wxInfo, wxPhone, bindPhone, membersStatus } from '@/utils/api'
import store from '@/store/index'

/**
 * 登录初始化
 * 1.清除数据 2.获取 token 3.获取用户信息 4.获取是否绑定
 */
export async function loginInfo () {
  clearAllInfo()
  await login()
  await getLoginInfo()
  await getIsUserInit()
}

/**
 * 登录
 */
export async function login () {
  // get wxlogin code
  let code = (await wx.login()).code

  // get userInfo
  let userInfo = await wxLogin(code)

  userInfo.token = 'Bearer ' + userInfo.token

  // set userInfo
  store.commit('changeUserInfo', userInfo)
}

/**
 * 获取登录信息
 */
export async function getLoginInfo () {
  let loginInfo = await myself()
  // 和微信统一字段
  loginInfo.nickName = loginInfo.nickname
  store.commit('changeUserInfo', {...store.state.userInfo, ...loginInfo})
}

/**
 * 获取用户信息
 * userInfo 微信授权加密信息
 */
export async function getUserInfo (userInfo) {
  // console.log(userInfo)
  let { encryptedData, iv, rawData, signature } = userInfo
  let sessionKey = store.state.userInfo.sessionKey

  store.commit('changeUserInfo', {...store.state.userInfo, ...userInfo.userInfo, isGetUserInfo: true})

  // console.log(store.state.userInfo)
  // console.log(encryptedData, iv, rawData, signature, sessionKey)
  await wxInfo(encryptedData, iv, rawData, signature, sessionKey)
}

/**
 * 获取手机号码 并 绑定
 * returnData 微信授权加密信息
 */
export async function getPhone (returnData) {
  let { encryptedData, iv } = returnData
  let sessionKey = store.state.userInfo.sessionKey

  let phoneNumber = (await wxPhone(encryptedData, iv, sessionKey)).phoneNumber
  console.log(phoneNumber)
  let code = (await wx.login()).code
  await bindPhone(code, phoneNumber)
  store.commit('changeUserInfo', {...store.state.userInfo, isBind: true})
  console.log(store.state.userInfo)
}

/**
 * 获取初始化账号状态
 * userInfo 微信授权加密信息
 */
export async function getIsUserInit () {
  let memberData = await membersStatus()

  store.commit('changeUserInfo', {...store.state.userInfo, ...memberData})
  console.log(store.state.userInfo)
}

/**
 * 清除登录信息和用户信息
 */
export function clearAllInfo () {
  // clear userInfo
  store.commit('changeUserInfo', null)
}

/**
 * 校验权限
 */
export function checkAuto () {
  console.log(store.state.userInfo)
  let {isGetUserInfo = false, isBind = false} = store.state.userInfo || {}

  if (!isGetUserInfo) {
    wx.showToast({
      title: '请先授权获取个人信息',
      icon: 'none'
    })
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/user/main'
      })
    }, 1500)
    return false
  }

  return isGetUserInfo && isBind
}
