<template>
  <view class="btns_item" @click="handleGoogleLogin">
    <view class="btn_icon">
      <image src="@/static/login/google.png" class="img" mode="widthFix"></image>
    </view>
    <trans _t="使用谷歌登录" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { systemInfo, Toast } from "@/utils"

const emit = defineEmits(['success', 'error'])
const platform = ref(systemInfo().uniPlatform)
const isLoggingIn = ref(false)
const isGoogleApiLoaded = ref(false)
// #ifdef H5

// 初始化Google登录
const initGoogleAuth = async () => {
  if (isGoogleApiLoaded.value) return

  return new Promise((resolve) => {
    if (window.google && window.google.accounts) {
      initWebGoogleAuth()
      isGoogleApiLoaded.value = true
      return resolve()
    }

    const script = document.createElement('script')
    script.src = 'https://accounts.google.com/gsi/client'
    script.async = true
    script.defer = true
    script.onload = () => {
      initWebGoogleAuth()
      isGoogleApiLoaded.value = true
      resolve()
    }
    document.head.appendChild(script)
  })
}

const initWebGoogleAuth = () => {
  window.google.accounts.id.initialize({
    client_id: '132211687127-bo929nasc04jk3927j07facbgovfv9vj.apps.googleusercontent.com',
    callback: handleCredentialResponse
  })
}
const handleCredentialResponse = (response) => {
  emit('success', response)
}
const googleLoginInH5 = () => {
  if (!window.google || !window.google.accounts) {
    return initGoogleAuth().then(googleLoginInH5)
  }
  window.google.accounts.id.prompt((notification) => {
    if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
      emit('error', new Error('Google登录弹出框被阻止'))
    }
  })
}
// #endif

// #ifdef APP-PLUS
const googleLoginInApp = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'google',
      success: (loginRes) => {
        uni.getUserInfo({
          provider: 'google',
          success: (info) => {
            Toast(info.authResult)
            emit('success', info.authResult)
            resolve(info)
          },
          fail: (err) => {
            console.error('获取用户信息失败:', err)
            emit('error', err)
            reject(err)
          }
        })
      },
      fail: (err) => {
        console.error('登录失败:', err)
        emit('error', err)
        reject(err)
      }
    })
  })
}
// #endif


// 统一登录处理
const handleGoogleLogin = async () => {
  if (isLoggingIn.value) return

  try {
    isLoggingIn.value = true

    // #ifdef H5
    if (!window.google || !window.google.accounts) {
      await initGoogleAuth()
    }
    // #endif

    if (platform.value === 'app') {
      await googleLoginInApp()
    } else if (platform.value === 'web') {
      await googleLoginInH5()
    } else {
      emit('error', new Error('不支持的平台'))
    }
  } catch (error) {
    emit('error', error)
  } finally {
    isLoggingIn.value = false
  }
}

onMounted(() => {
  // #ifdef H5
  initGoogleAuth().catch(err => {
    console.error('Google API 初始化失败:', err)
  })
  // #endif
})
</script>

<style lang="less" scoped>
@import url('@/style.less');

.btns_item {
  .ver();
  width: 400rpx;
  border: 1px solid var(--black);
  border-radius: 100px;
  padding: 14rpx 52rpx;
  margin-top: 18rpx;
  color: var(--text-02);
  .size(24rpx);

  .btn_icon {
    width: 48rpx;
    margin-right: 52rpx;

    .img {
      width: inherit;
      display: block;
    }
  }
}
</style>