<template>
    <div class="page">
        <div class="reset-container">
            <div class="reset-form">
                <remit-input
                    v-model:value="email"
                    type="text"
                    fkey="email"
                    label="邮箱"
                    :clearable="true"
                    @change="handleChange"
                    placeholder="请输入邮箱"
                    :rules="[
                        { required: true, message: '请输入邮箱' },
                        { pattern: config.Pattern.Email, message: '请输入正确的邮箱格式' },
                    ]"
                >
                    <template #left-icon1> <van-icon name="envelop-o" /> </template>
                </remit-input>
                <div class="reset-button">
                    <van-button type="primary" block :loading="loading" @click="handleReset"> {{ t('reset-password.reset') }} </van-button>
                </div>
                <div class="login-link">
                    {{ t('reset-password.remember') }}<span @click="handleLogin">{{ t('reset-password.login') }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { userApi } from '@/api/user'
import config from '@/config'
const { t } = useI18n()
const router = useRouter()
const loading = ref(false)
const email = ref('')
const handleReset = async () => {
    if (!email.value) {
        showToast(t('reset-password.emailRequired'))
        return
    }
    if (!config.Pattern.Email.test(email.value)) {
        showToast(t('reset-password.emailError'))
        return
    }

    loading.value = true
    try {
        const res = await userApi.updatePassword({ email: email.value })
        showToast(res.msg)
        router.push('/login')
    } catch (error: any) {
        showToast(error.message || '重置失败')
    } finally {
        loading.value = false
    }
}
const handleChange = (value: any) => {
    if (value.key == 'email') {
        email.value = value.value
    }
}

const handleLogin = () => {
    router.push('/login')
}
</script>

<style scoped lang="scss">
.reset-container {
    padding: 40px 0;
}

.reset-button {
    margin-bottom: 20px;

    .van-button {
        height: 44px;
        border-radius: 12px;
        background: var(--main-yellow);
        border: none;
        color: var(--black);
        font-size: var(--font-size-16);
        font-weight: bold;

        :deep(&--loading) {
            opacity: 0.8;
        }
    }
}

.login-link {
    text-align: center;
    font-size: var(--font-size-14);
    color: var(--gray);

    span {
        color: var(--main-yellow);
        margin-left: 4px;
    }
}
</style>
