//判断用户是否授权、、或者是否登录

import { userLoginApi } from '@/services/home'
import type { LoginParams } from '@/types/home'
import { useMemberStore } from '@/stores/'

const useMember = useMemberStore()

//当用户已授权手机号、、或者已登录
const home = '/home/banner'

//登录但是我返回的是code  登录凭证
export const login = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        console.log(res)
        const re = <LoginParams>{ code: res.code }
        userLogin(re)
        console.log('login')
        resolve(re)
      },
      fail: (error) => {
        // reject(error)
      },
    })
  })
}

const userLogin = async (code: LoginParams) => {
  const res = await userLoginApi(code)
  //存储token
  //存储用户信息
  useMember.token = res.data.token
  console.log('userLogin')
  // if (res.data.user.isAuth == '0') {
  // }
  useMember.saveUserInfo(res.data.user)

  return code.code
}

//应该再写一个返回用户信息
export const loginUser = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        console.log(res)
        const re = <LoginParams>{ code: res.code }
        userLoginApi(re).then((res) => {
          //此时这个方法执行完了
          //查看返回的数据
          useMember.token = res.data.token
          useMember.saveUserInfo(res.data.user)
          resolve(res.data.user.id)
        })
      },
      fail: (error) => {
        reject(error)
      },
    })
  })
}

// const loginUserInfo = async (code: LoginParams) => {
//   const res = await userLoginApi(code)
//   //存储token
//   //存储用户信息
//   useMember.token = res.data.token
//   console.log(res)
//   // if (res.data.user.isAuth == '0') {
//   // }
//   useMember.saveUserInfo(res.data.user)

//   return code.code
// }
