<template>
    <div class="col-xl-12">
        <UserFormInput
            title="아이디"
            name="id"
            :is-alert="idAlert"
            :is-essential="true"
            :useInputGroup="true"
            @update:data="handleIdChange"
            :value="id"
            :disabled="resetForm"
        />
        <template v-if="!resetForm">
            <UserFormInput
                title="생년월일"
                name="birth"
                :type="'date'"
                :is-essential="true"
                :is-alert="birthAlert"
                @update:data="birth = $event"
                @update:alert="birthAlert = $event"
                :value="birth"
            />
            <FormSelect
                title="비밀번호 힌트"
                name="pwhint"
                :is-essential="true"
                :is-row="false"
                :is-label="true"
                :is-common="true"
                :data="pwhintList"
                @update:data="pwhint = $event"
            />
            <UserFormInput
                title="답변"
                name="pwhintRes"
                :is-essential="true"
                :is-alert="pwhintResAlert"
                @update:data="pwhintRes = $event"
                @update:alert="pwhintResAlert = $event"
                :value="pwhintRes"
            />
            <div class="d-flex gap-2 mt-7 mb-3">
                <BackBtn class=" w-50" @click="handleback"/>
                <SaveBtn class="w-50" @click="handleSubmit" />
            </div>
            <p v-if="userCheckMsg" class="invalid-feedback d-block mb-0">{{ userCheckMsg }}</p>
        </template>
    </div>

    <div v-if="resetForm" class="mt-4">
        <UserFormInput
            title="새 비밀번호"
            name="pw"
            type="password"
            :isEssential="true"
            :is-alert="passwordAlert"
            @update:data="password = $event"
            @update:alert="passwordAlert = $event"
            :value="password"
        />

        <UserFormInput
            title="비밀번호 확인"
            name="pwch"
            type="password"
            :isEssential="true"
            :is-alert="passwordcheckAlert"
            @update:data="passwordcheck = $event"
            @update:alert="passwordcheckAlert = $event"
            @input="checkPw"
            :value="passwordcheck"
        />
        <span v-if="passwordcheckError" class="invalid-feedback d-block">{{ passwordcheckError }}</span>

        <div class="d-flex gap-2 mt-7 mb-3">
                <BackBtn class=" w-50" @click="handleback"/>
                <SaveBtn class="w-50" @click="handleNewPassword" />
        </div>
        <p v-if="pwErrMsg" class="invalid-feedback d-block mb-0">{{ pwErrMsg }}</p>
    </div>
</template>

<script setup>
    import { ref, watch } from 'vue';
    import $api from '@api';
    import commonApi from '@/common/commonApi';
    import { useRouter } from 'vue-router';
    import { useToastStore } from '@s/toastStore';
    import UserFormInput from '@c/input/UserFormInput.vue';
    import FormSelect from '../input/FormSelect.vue';
    import BackBtn from '@c/button/BackBtn.vue';
    import SaveBtn from '../button/SaveBtn.vue';

    const router = useRouter();
    const toastStore = useToastStore();

    const id = ref('');
    const birth = ref('');
    const pwhint = ref('');
    const pwhintRes = ref('');
    const userCheckMsg = ref("");
    const pwErrMsg = ref("");

    const idAlert = ref(false);
    const birthAlert = ref(false);
    const pwhintResAlert = ref(false);
    const resetForm = ref(false);

    const password = ref('');
    const passwordcheck = ref('');
    const passwordcheckError = ref('');

    const passwordAlert = ref(false);
    const passwordcheckAlert = ref(false);
    const passwordMismatch = ref(false);

    const { pwhintList } = commonApi({
        loadPwhint: true,
    });

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

    const handleback = () => {
        router.push('/login');
    }

    // 비밀번호와 비밀번호 확인이 변경될 때마다 유효성 검사
    watch([password, passwordcheck], () => {
        if (passwordcheck.value !== '') {
            checkPw();
        }
    });

    // 아이디, 생년월일, 비밀번호 힌트, 답변이 일치하는 member 재설정 input 보이기
    const handleSubmit = async () => {
        userCheckMsg.value = '';
        idAlert.value = id.value.trim() === '';
        pwhintResAlert.value = pwhintRes.value.trim() === '';
        birthAlert.value = birth.value.trim() === '';

        if (idAlert.value || pwhintResAlert.value || birthAlert.value) {
            return;
        }

        const response = await $api.post('user/pwReset', {
            id: id.value,
            birth: birth.value,
            pwhint: pwhint.value,
            pwhintRes: pwhintRes.value,
        });

        if (response.status === 200 && response.data.data === true) {
            resetForm.value = true;
        } else {
            userCheckMsg.value = '입력하신 정보와 일치하는 회원이 없습니다.';
            return;
        }
    };

    const checkPw = () => {
        if (password.value !== passwordcheck.value) {
            passwordcheckError.value = '비밀번호가 일치하지 않습니다.';
            passwordMismatch.value = true;
        } else {
            passwordcheckError.value = '';
            passwordMismatch.value = false;
        }
    };

    // 비밀번호 업데이트
    const handleNewPassword = async () => {
        pwErrMsg.value = '';
        passwordAlert.value = password.value.trim() === '';
        passwordcheckAlert.value = passwordcheck.value.trim() === '';

        checkPw();

        if (passwordAlert.value || passwordcheckAlert.value || passwordMismatch.value) {
            return;
        }

        const checkResponse = await $api.post('user/checkPassword', {
            id: id.value,
            password: password.value
        });

        if (checkResponse.data.data === false) {
            pwErrMsg.value = '기존 비밀번호와 동일한 비밀번호로 변경할 수 없습니다.';
            return;
        }

        const response = await $api.patch('user/pwNew', {
            id: id.value,
            password: password.value
        });

        if (response.status === 200 && response.data.data === true) {
            toastStore.onToast('비밀번호가 재설정 되었습니다.', 's');
            router.push('/login');
        }
    };
</script>
