<script setup>
import { onMounted, ref, watch } from "vue";
import { Login } from "@/apis/login";
import Image from "@/assets/img/logo.png";
import * as yup from "yup";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import { useRouter } from "vue-router";
import useUserInfoStore from "@/stores/useUserInfoStore";

const store = useUserInfoStore();
const router = useRouter();

let schema = yup.object({
  account: yup.string().required("必填"),
  password: yup.string().required("必填"),
});
const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(schema);

const formState = ref({
  account: "",
  password: "",
});

const imageSrc =
  import.meta.env.MODE === "production" ? "./blackball.png" : Image;

const doLogin = async () => {
  const value = await handleSubmit(schema, formState.value);
  const res = await Login(value);
  if (res.isSuccess) {
    store.user = res.data;
    router.replace({ path: "/dashboard" });
  }
};
</script>

<template>
  <div
    class="absolute top-10 left-1/2 -translate-x-1/2 z-20 border-4 rounded-3xl p-5 bg-white bg-opacity-60"
  >
    <div class="flex flex-col items-start w-96">
      <img :src="imageSrc" class="w-full mb-5" />
      <div class="w-full flex flex-col items-end my-2">
        <div class="w-full flex justify-between">
          <label class="mr-2 text-2xl text-black" for="account">帳號</label>
          <input
            name="account"
            class="w-5/6 border-2 rounded-full bg-white text-black px-4 py-1"
            v-model="formState.account"
            autocomplete="none"
          />
        </div>
        <span class="text-error text-base">
          {{ formErrorMsg.account }}
        </span>
      </div>
      <div class="w-full flex flex-col items-end my-2">
        <div class="w-full flex justify-between">
          <label class="mr-2 text-2xl text-black" for="password">密碼</label>
          <input
            name="password"
            class="w-5/6 border-2 rounded-full bg-white text-black px-4 py-1"
            type="password"
            v-model="formState.password"
            autocomplete="off"
          />
        </div>
        <span class="text-error text-base">
          {{ formErrorMsg.password }}
        </span>
      </div>
      <button
        class="mt-3 px-6 py-2 bg-red-800 text-white rounded-full self-end hover:bg-red-900"
        @click.stop.prevent="doLogin"
      >
        登入
      </button>
    </div>
  </div>
</template>

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