<template>
    <form @submit.prevent="handleSubmit">
        <div class="col-xl-12">
            <UserFormInput title="아이디" name="id" :is-alert="idAlert" :useInputGroup="true" @update:data="handleIdChange" :value="id" />

            <UserFormInput
                title="비밀번호"
                name="password"
                type="password"
                :is-alert="passwordAlert"
                @update:data="handlePasswordChange"
                :value="password"
            />

            <div class="d-grid gap-2 mt-7 mb-5">
                <button type="submit" class="btn btn-primary">로그인</button>
                <p v-if="errorMessage" class="invalid-feedback d-block mb-0">{{ errorMessage }}</p>
            </div>

            <div class="mb-3 d-flex justify-content-around">
                <div>
                    <input type="checkbox" class="form-check-input" id="rememberCheck" v-model="remember" />
                    <label class="form-check-label fw-bold" for="rememberCheck">&nbsp;자동로그인</label>
                </div>
                <RouterLink class="text-dark fw-bold" to="/register">등록신청</RouterLink>
                <RouterLink class="text-dark fw-bold" to="/pw">비밀번호 재설정</RouterLink>
            </div>
        </div>
    </form>
</template>

<script setup>
    import $api from '@api';
    import router from '@/router';
    import {  ref } from 'vue';
    import UserFormInput from '@c/input/UserFormInput.vue';
    import { useUserInfoStore } from '@/stores/useUserInfoStore';

    const id = ref('');
    const password = ref('');
    const idAlert = ref(false);
    const passwordAlert = ref(false);
    const remember = ref(false);
    const errorMessage = ref("");

    const userStore = useUserInfoStore();

    const handleIdChange = value => {
        id.value = value;
        idAlert.value = false;
    };

    const handlePasswordChange = value => {
        password.value = value;
        passwordAlert.value = false;
    };

    const handleSubmit = async () => {
        errorMessage.value = '';
        idAlert.value = id.value.trim() === '';
        passwordAlert.value = password.value.trim() === '';

        if (idAlert.value || passwordAlert.value) {
            return;
        }


        $api.post('user/login', {
            loginId: id.value,
            password: password.value,
            remember: remember.value,
        }, { headers: { isLogin: true } })
        .then(async res => {
            // 로그인 실패 확인
            if (res.data.code > 10000) {
                // 로그인 실패 시 에러 메시지 표시
                errorMessage.value = res.data.message;
                return;
            }

                // 로그인 성공 처리
                await userStore.userInfo();
                router.push('/');
        })
    };
</script>
