<template>
    <cwg-page-wrapper>
        <view class="reset-container">
            <view class="reset-form">
                <cwg-input v-model:value="email" type="text" fkey="email" label="邮箱" :clearable="true"
                    placeholder="请输入邮箱" :rules="[
                        { required: true, message: '请输入邮箱' },
                        { pattern: config.Pattern.Email, message: '请输入正确的邮箱格式' },
                    ]" @change="handleChange">
                    <template #left-icon1>
                        <cwg-icon name="email-outline" :size="20" color="#000" />
                    </template>
                </cwg-input>
                <view class="reset-button cwg-button">
                    <u-button type="primary" block :loading="loading" @click="handleReset">{{ t('forget.forget')
                    }}</u-button>
                </view>
                <view class="login-link">
                    {{ t('signin.forget') }}<text @click="handleLogin">{{ t('newSignin.item7') }}</text>
                </view>
            </view>
        </view>
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import useRouter from '@/hooks/useRouter'
import { userApi } from '@/api/user'
import config from '@/config'

const { t } = useI18n()
const router = useRouter()
const loading = ref(false)
const email = ref('')

async function handleReset() {
    if (!email.value) {
        uni.showToast({ title: t('vaildate.email.empty'), icon: 'none' })
        return
    }
    if (!config.Pattern.Email.test(email.value)) {
        uni.showToast({ title: t('vaildate.email.format'), icon: 'none' })
        return
    }

    loading.value = true
    try {
        const res = await userApi.updatePassword({ email: email.value })
        uni.showToast({ title: res.msg || '成功', icon: 'none' })
        router.push('/pages/login/index')
    }
    catch (error: any) {
        uni.showToast({ title: error.message || '重置失败', icon: 'none' })
    }
    finally {
        loading.value = false
    }
}

function handleChange(value: any) {
    if (value.key == 'email') {
        email.value = value.value
    }
}

function handleLogin() {
    router.push('/pages/login/index')
}
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.reset-container {
    padding: px2rpx(40) 0;
}

.reset-button {
    margin-bottom: px2rpx(20);

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

    :deep(u-button--loading) {
        opacity: 0.8;
    }
}

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

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