<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import Navbar from "@/components/Navbar.vue";

const handleSignIn = async (response) => {
  const credential = response.credential;
  const profile = JSON.parse(
    decodeURIComponent(
      escape(
        window.atob(
          credential.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")
        )
      )
    )
  );

  console.log("profile", profile);

  const target = document.getElementById("GOOGLE_STATUS_1");
  const html = `
    ID: ${profile.sub}<br/>
    會員暱稱： ${profile.name}<br/>
    會員頭像： ${profile.picture}<br/>
    會員 email： ${profile.email}<br/>
  `;
  target.innerHTML = html;

  let data = {
    username: profile.name,
    password: "googleLogin",
    email: profile.email,
  };

  try {
    const response = await axios.post(
      "https://cmm.ai:8088/api/login/google/access-token",
      data
    );
    console.log("response", response);
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  const script = document.createElement("script");
  script.src = "https://accounts.google.com/gsi/client";
  script.async = true;
  script.defer = true;
  document.head.appendChild(script);

  window.onSignIn1 = handleSignIn;
});
</script>

<template>
  <Navbar />
  <div>Login</div>
  <div style="width: 200px; margin: 20px 0">
    <div
      id="g_id_onload"
      data-client_id="626437744072-q6djn202411is5vdk2v0tu8fo7n07qr0.apps.googleusercontent.com"
      data-callback="onSignIn1"
    ></div>
    <div class="g_id_signin" data-type="standard"></div>

    <p class="mt-3">目前狀態：</p>

    <span id="GOOGLE_STATUS_1"></span>
  </div>
</template>
