import UserApi from "../apis/user"
import { saveToken, saveUserInfo } from './storage'
import EventEmitter from './eventEmitter'
const app = getApp()
function wxLogin() {
  return new Promise((resovle, reject) => {
    wx.login({
      success(res) {
        resovle(res.code)
      },
      fail(err) {
        wx.showModal({
          title: "登录失败",
          content: "网络异常，请重试",
        })
        reject(err)
      },
    })
  })
}

function checkSession() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: (res) => {
        resolve(res)
      },
      fail(err) {
        reject(err)
      },
    })
  })
}

function loginByPhone(data, isAgency) {
  const LoginApi = UserApi.loginByPhoneCode
  return LoginApi(data).then(res => {
    const data = res.data
    data.user = data.guide
    data.user.user_id = data.user.viewerId
    saveToken(data.token)
    saveUserInfo(data.user)
    app.globalData.token = data.token
    app.globalData.userinfo = data.user
    EventEmitter.emit('login')
    return res
  })
}

function tips (res) {
  if (res.data.code == 3032) {
    wx.showToast({
      title: '经纪人未注册，请联系管理员',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (res.data.code != 3008) {
    wx.showToast({
      title: res.data.msg,
      icon: 'none',
      duration: 2000,
    })
    return
  }
}

export function loginFn(phone_data, code, isAgency) {
  const { encryptedData, iv, rawData, signature } = phone_data.detail
  if (!encryptedData || !iv) {
    return new Promise((_, reject) => reject())
  }
  return new Promise((resolve, reject) => {
    checkSession()
      .then(() => {
        return loginByPhone({ phone_num: encryptedData, iv, wx_code: code, rawData, signature }, isAgency).then(res => {
          resolve(res)
        })
      })
      .catch((err) => {
        // 登录失败可能是code失效，故重新wx.login重新获取code
        tips(err)
        wxLogin().then((code) => {
          loginByPhone({ phone_num: encryptedData, iv, wx_code: code }, isAgency).then(res => {
            resolve(res)
          }).catch(err => {
            tips(err)
          })
        })
      })
  })
}

export function loginByUserInfo (data, code) {
  data.wx_code = code
    data.phone_num = ''
    return UserApi.loginByUserInfo(data).then(res => {
      data = res.data
      data.viewer.user_id = data.viewer.viewerId
      saveToken(data.token)
      saveUserInfo(data.viewer)
      app.globalData.token = data.token
      app.globalData.userinfo = data.viewer
      EventEmitter.emit('login')
      return res
    }).catch(err => {
      tips(err)
    })
  
}

