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 = isAgency ? UserApi.loginByPhoneCodeAgency : UserApi.loginByPhoneCode
  return LoginApi(data).then(res => {
    const data = res.data
    data.user = data.user || data.agency
    data.user.user_id = data.user.user_id || data.user.agency_user_id
    saveToken(data.token)
    saveUserInfo(data.user)
    getApp().globalData.token = data.token
    getApp().globalData.userinfo = data.user
    EventEmitter.emit('login')
    return res
  })
}

function tips (res) {
  console.log(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
  }
}

//获取用户信息接口
function getUserProfile() {
  return new Promise((resovle, reject) => {
    wx.getUserProfile({
      desc: "用于完善用户资料", 
      //异步请求：回调函数中调用下一个函数
      success (res)  {
        resovle(res)
      },
      fail(err) {
        wx.showModal({
          title: "登录失败",
          content: "异常，请重试",
        })
        reject(err)
      },
    });
    
  })
}
export  function Login(phone_data, code, isAgency) {
  const { encryptedData, iv } = 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 }, 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 => {
            console.log(err, 'err')
            tips(err)
          })
        })
      })
  })
}


// export async function loginByUserInfo () {
//   wx.showLoading('登录中')
//   return new Promise(async (resolve, reject) => {
//     let code = await wxLogin()
//     wx.getUserInfo({
//       withCredentials: true,
//       success (res) {
//         console.log(res)
//         res.wx_code = code
//         UserApi.loginByUserInfo(res).then(loginRes => {
//           const data = loginRes.data
//           data.user = data.user || data.agency
//           data.user.user_id = data.user.user_id || data.user.agency_user_id
//           saveToken(data.token)
//           saveUserInfo(data.user)
//           getApp().globalData.token = data.token
//           getApp().globalData.userinfo = data.user
//           EventEmitter.emit('login')
//           wx.hideLoading()
//           resolve(res)
//         })
//       },
//       fail (err) {
//         wx.hideLoading()
//         reject(err)
//       }
//     })
//   })
  
// }
export async function loginByUserInfo () {
  // wx.showLoading('登录中')
  let UserProfile  = await getUserProfile()
  let code = await wxLogin()
  console.log('************')
  console.log(UserProfile)
  return new Promise(async (resolve, reject) => {
    wx.getUserInfo({
      withCredentials: true,
      success (res) {
        res.wx_code = code
        res.userInfo = UserProfile.userInfo
     
        UserApi.loginByUserInfo(res).then(loginRes => {
          const data = loginRes.data
          console.log(data)
          data.user = data.user || data.agency
          UserProfile.userInfo.user_id = data.user.user_id || data.user.agency_user_id
          saveToken(data.token)
          getApp().globalData.token = data.token
          UserProfile.userInfo.name = UserProfile.userInfo.name || UserProfile.userInfo.nickName
          UserProfile.userInfo.avatar = UserProfile.userInfo.avatar || UserProfile.userInfo.avatarUrl
          getApp().globalData.userinfo =UserProfile.userInfo
          getApp().globalData.userinfo.agency_user_id =data.agency.agency_user_id
          getApp().globalData.userinfo.phone = data.agency.phone
          getApp().globalData.userinfo.agency_company_name = data.agency.agency_company_name
          saveUserInfo(UserProfile.userInfo)
          EventEmitter.emit('login')
          wx.hideLoading()
          resolve(res)
        })
      },
      fail (err) {
        wx.hideLoading()
        reject(err)
      }
    })
  })
}
