<script setup>
import { useGenerateImageVariant } from "@core/composable/useGenerateImageVariant";
import pages401 from "@images/pages/401.png";
import miscMaskDark from "@images/pages/misc-mask-dark.png";
import miscMaskLight from "@images/pages/misc-mask-light.png";
import { onMounted, ref } from "vue";

const isLoading = ref(true);
const hasError = ref(false);
const homeUrl = import.meta.env.VITE_KM_HOME_URL;
const route = useRoute();
const router = useRouter();
const ability = useAbility();
definePage({
  meta: {
    layout: "blank",
    public: true,
  },
});

const authThemeMask = useGenerateImageVariant(miscMaskLight, miscMaskDark);
const token = route.params.token || undefined;
const defaultPath = import.meta.env.VITE_PATH_DEFAULT;

async function sendTokenToApi() {
  if (token) {
    try {
      const res = await $api("/auth/token", {
        method: "POST",
        body: JSON.stringify({ token }),
        headers: {
          "Content-Type": "application/json",
        },
      });
      isLoading.value = false;
      const {
        accessToken,
        userData,
        userAbilityRules,
        project_number,
        project_name,
        startDate,
        work_duration,
      } = res;

      useCookie("userAbilityRules").value = userAbilityRules;
      ability.update(userAbilityRules);
      useCookie("userData").value = userData;
      useCookie("accessToken").value = accessToken;

      router.replace({ path: "/" });
    } catch (error) {
      console.error("API 請求失敗:", error);
      isLoading.value = false; // 加載完成
      hasError.value = true; // 發生錯誤
    }
  } else {
    console.log("沒有提供 token");
    isLoading.value = false; // 加載完成
    hasError.value = true; // 假設缺少 token 也是一種錯誤
  }
}

// 在组件挂载后发送 token
onMounted(() => {
  sendTokenToApi();
});
</script>

<template>
  <div class="misc-wrapper">
    <template v-if="isLoading">
      <VProgressCircular indeterminate color="primary"></VProgressCircular>
    </template>

    <template v-else-if="hasError">
      <ErrorHeader
        status-code="401"
        title="您無權限! 🔐"
        description="您在登入時提供的憑證無法查看此頁面。
       請聯繫您的網站管理員。"
      />
      <VBtn class="mt-2 mb-10" :href="homeUrl"> 返回首頁 </VBtn>
      <div class="misc-avatar w-100 text-center">
        <VImg :src="pages401" alt="即將上線" :max-width="170" class="mx-auto" />
      </div>
      <VImg :src="authThemeMask" class="misc-footer-img d-none d-md-block" />
    </template>

    <template v-else> </template>
  </div>
</template>

<style lang="scss">
@use "@core-scss/template/pages/misc.scss";
</style>
