<script setup>
import { onMounted, ref, watch, inject } from "vue";
import { Login } from "@/apis/login";
import { getAuth } from "@/apis/building";
import { AUTHPAGES } from "@/constant";
import * as yup from "yup";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import { useRouter } from "vue-router";
import useUserInfoStore from "@/stores/useUserInfoStore";

const { openToast } = inject("app_toast");
const store = useUserInfoStore();
const router = useRouter();
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const imageSrc =
  import.meta.env.MODE === "production"
    ? "../dist/background.png"
    : "./background.png";
let schema = yup.object({
  account: yup.string().required("必填"),
  password: yup.string().required("必填"),
});
const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(schema);

const formState = ref({
  account: "",
  password: "",
});
const showPassword = ref(false);
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const doLogin = async () => {
  const value = await handleSubmit(schema, formState.value);
  const res = await Login(value);
  if (res.isSuccess) {
    store.user = res.data;
    
    // 獲取並存儲使用者權限到 store
    try {
      const authRes = await getAuth();
      const userAuthPages = authRes.data.map((d) =>
        AUTHPAGES.find(({ authCode }) => authCode === d.authCode)
          ? {
              ...d,
              ...AUTHPAGES.find(({ authCode }) => authCode === d.authCode),
            }
          : d
      );
      
      // 將權限資料存入 store
      store.updateAuthPage(userAuthPages);
      
      // 找到第一個有 showView 且有導航路徑的頁面
      const firstAvailablePage = userAuthPages.find(page => page.showView && page.navigate);
      const redirectPath = firstAvailablePage?.navigate || "/dashboard";
      
      router.replace({ path: redirectPath });
    } catch (error) {
      console.error("獲取使用者權限時發生錯誤:", error);
      router.replace({ path: "/dashboard" });
    }
  } else {
    openToast("error", res.msg);
  }
};
</script>

<template>
  <div
    class="absolute top-0 left-0 w-screen h-screen bg-cover bg-left bg-no-repeat z-0"
    :style="{ backgroundImage: `url(${imageSrc})` }"
  ></div>
  <div
    class="absolute sm:bottom-10 sm:left-52 z-20 w-full max-w-md p-6 rounded-lg bg-white dark:bg-gray-800 "
  >
      <div class="mt-4">
        <div class="flex items-center">
          <label
            class="w-16 text-lg text-gray-600 dark:text-gray-200"
            for="account"
            >帳號</label
          >
          <input
            name="account"
            class="block w-full px-4 py-2 text-gray-700 placeholder-gray-400 bg-white border border-gray-200 rounded-lg dark:placeholder-gray-600 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700 focus:border-rose-400 dark:focus:border-rose-400 focus:ring-rose-400 focus:outline-none focus:ring focus:ring-opacity-40"
            v-model="formState.account"
            autocomplete="none"
          />
          <span class="text-error text-base">
            {{ formErrorMsg.account }}
          </span>
        </div>
        <div class="flex items-center mt-3">
          <label class=" w-16 text-lg text-gray-600 dark:text-gray-200" for="password"
            >密碼</label
          >
          <div class="relative w-full">
            <input
              name="password"
              class="block w-full px-4 py-2 text-gray-700 placeholder-gray-400 bg-white border border-gray-200 rounded-lg dark:placeholder-gray-600 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700 focus:border-rose-400 dark:focus:border-rose-400 focus:ring-rose-400 focus:outline-none focus:ring focus:ring-opacity-40"
              :type="showPassword ? 'text' : 'password'"
              v-model="formState.password"
              autocomplete="off"
            />
            <FontAwesomeIcon
              :icon="['fas', showPassword ? 'eye-slash' : 'eye']"
              class="text-stone-200 text-xl absolute top-1/2 right-4 transform -translate-y-1/2 cursor-pointer"
              @click="togglePasswordVisibility"
            />
          </div>
          <span class="text-error text-base">
            {{ formErrorMsg.password }}
          </span>
        </div>
        <div class="mt-6">
          <button
            class="text-lg w-full px-4 py-2 tracking-wide text-white transition-colors duration-300 transform bg-rose-500 rounded-lg hover:bg-rose-400 focus:outline-none focus:bg-rose-400 focus:ring focus:ring-rose-300 focus:ring-opacity-50"
            @click.stop.prevent="doLogin"
          >
            登入
          </button>
        </div>
      </div>
  </div>
</template>

<style lang="scss" scoped></style>
