<template>
    <mx-submit-layout title="找回密码" :loading="loading" @submit="handleSubmit">
        <uv-form ref="form" :model="model" :rules="rules">
            <mobile-code-fields/>
            <pwd-repeat-fields/>
        </uv-form>
    </mx-submit-layout>
</template>

<script setup>
import {ref} from 'vue'
import {resetCardPassword, sendSmsNoValidationNoToken} from "@/api/login";
import {sleep, toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {useTransfer} from "@/hooks/useTransfer";
import {useProvideFormData} from "@/pages/login/components/hooks/useFormDataInjection";
import {createForgetPwdModelRules} from "@/pages/login/components/hooks/defineFormModels";
import MobileCodeFields from "@/pages/login/components/register-fields/mobile-code-fields.vue";
import PwdRepeatFields from "@/pages/login/components/register-fields/pwd-repeat-fields.vue";
import {useProvideFormRef} from "@/pages/login/components/hooks/useFormRefInjection";
import {useProvideSendSmsFn} from "@/pages/login/components/hooks/useSmsInjection";

const {transferBack} = useTransfer()
const loading = ref(false)

// form and service
const form = ref(null)
const [m, r, modelToCommit] = createForgetPwdModelRules()
const [model, rules] = useProvideFormData(m, r)
useProvideFormRef(form)
useProvideSendSmsFn(async (args) => await handleSendSms(args))

// methods
const handleSendSms = async (events) => {
    await sendSmsNoValidationNoToken({mobile: model.value.mobile, smsType: 1, ...events})
}

const handleSubmit = async () => {
    await form.value.validate()
    if (loading.value) return
    loading.value = true
    try {
        const commit = modelToCommit()
        await resetCardPassword(commit)
        toast('新密码修改成功')
        await sleep(1000)
        transferBack()
    } finally {
        loading.value = false
    }
}
</script>

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