<template>
  <view class="btns_item" @click="handleFacebookLogin">
    <view class="btn_icon">
      <image src="@/static/login/facebook.png" class="img" mode="widthFix"></image>
    </view>
    <trans _t="使用脸书登录" />
  </view>
</template>

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

const emit = defineEmits(['success', 'error'])

const platform = ref(systemInfo().uniPlatform)
const isInitialized = ref(false)


// #ifdef H5
// 初始化Facebook登录
const initFacebookAuth = async () => {
  if (platform.value === 'web') {
    initFacebookSDK()
  }
}
const initFacebookSDK = () => {
  return new Promise((resolve) => {
    if (window.FB) {
      isInitialized.value = true
      resolve()
      return
    }

    if (window.fbAsyncInit) {
      const originalInit = window.fbAsyncInit
      window.fbAsyncInit = function () {
        originalInit()
        isInitialized.value = true
        resolve()
      }
    } else {
      window.fbAsyncInit = function () {
        FB.init({
          appId: '501088503016892',
          xfbml: 1,
          version: 'v23.0',
          autoLogAppEvents: true
        })
        isInitialized.value = true
        resolve()
      }
    }

    if (!document.getElementById('facebook-jssdk')) {
      const script = document.createElement('script')
      script.id = 'facebook-jssdk'
      script.src = 'https://connect.facebook.net/en_US/sdk.js'
      script.async = true
      script.defer = true
      document.body.appendChild(script)
    } else {
      if (!window.FB) {
        const script = document.getElementById('facebook-jssdk')
        script.parentNode.removeChild(script)
        const newScript = document.createElement('script')
        newScript.id = 'facebook-jssdk'
        newScript.src = 'https://connect.facebook.net/en_US/sdk.js'
        newScript.async = true
        newScript.defer = true
        document.body.appendChild(newScript)
      }
    }
  })
}
const FacebookLoginInH5 = () => {
  FB.login(response => {
    if (response.authResponse) {
      emit('success', response.authResponse)
    } else {
      console.log('用户取消登录');
    }
  }, { scope: 'public_profile,email' });
}
// #endif

// #ifdef APP-PLUS
const FacebookLoginInApp = async () => {
  try {
    uni.login({
      provider: 'facebook',
      success: function (loginRes) {
        // 登录成功
        uni.getUserInfo({
          provider: 'facebook',
          success: function (info) {
            emit('success', info.authResult)
          }
        })
      },
      fail: function (err) {
        console.log('登录失败:', err);
      }
    });

  } catch (error) {
    emit('error', error)
  }
}
// #endif

const handleFacebookLogin = async () => {
  try {
    if (platform.value === 'app') {
      await FacebookLoginInApp()
    } else if (platform.value === 'web') {
      if (!isInitialized.value) {
        await initFacebookSdk()
      }
      await FacebookLoginInH5()
    } else {
      emit('error', new Error('不支持的平台'))
    }
  } catch (error) {
    emit('error', error)
  }
}

onMounted(() => {
  // #ifdef H5
  initFacebookAuth()
  // #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>