export function useGoogleLogin() {
  const loading = ref(false)
  const clientID = '686587510116-r0soonrdftkj8d6lhsp0qprguqa65n60.apps.googleusercontent.com'
  onMounted(() => {
    const script = document.createElement('script')
    script.src = 'https://accounts.google.com/gsi/client'
    script.async = true
    script.defer = true
    document.head.appendChild(script)
  })

  /**
   * 初始化 Google Auth
   */
  function initializeGoogleAuth(resolve, reject) {
    return window.google.accounts.oauth2.initTokenClient({
      client_id: clientID,
      scope: 'email profile',
      callback: async (response) => {
        try {
        // 获取用户基本信息
          const userInfo = await fetchUserInfo(response.access_token)
          const res = {
            token: response.access_token,
            userInfo,
          }
          resolve(res)
        }
        catch (error) {
          reject(error)
        }
      },
      error_callback: (error) => {
        reject(error)
      },
    })
  }

  /**
   * 获取用户详细信息
   */
  async function fetchUserInfo(accessToken) {
    const res = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    })
    if (!res.ok)
      throw new Error('获取用户信息失败')
    return await res.json()
  }

  // 触发登录
  function handleGoogleLogin() {
    return new Promise((resolve, reject) => {
      if (!window.google) {
        const t = setTimeout(() => {
          clearTimeout(t)
          ElMessage.error('当前环境不支持 Google 登录，请使用其他方式登录')
          reject(new Error('Google SDK not loaded'))
        }, 1000)
        return
      }
      const client = initializeGoogleAuth(resolve, reject)
      client.requestAccessToken()
    })
  }

  async function onGoogleLogin() {
    try {
      loading.value = true
      const result = await handleGoogleLogin()
      loading.value = false
      return result
    }
    catch (error) {
      loading.value = false
    }
  }
  return { loading, onGoogleLogin }
}
