<template>
    <mx-popup-template ref="popup" :loading="loading" keep title="变更手机号" left="取消" right="保存"
                       @left="close" @right="handleSubmit">
        <uv-form ref="form" :model="model" :rules="rules">
            <mobile-code-fields label-mobile="新手机号码"/>
        </uv-form>
    </mx-popup-template>
</template>

<script setup>
import {ref} from 'vue'
import {sendSms} from "@/api/login";
import {updatePhonenumber} from "@/api/system/user";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {useUserStore} from "@/hooks/useUserStore";
import MobileCodeFields from "@/pages/login/components/register-fields/mobile-code-fields.vue";
import {createChangePhoneModelRules} from "@/pages/login/components/hooks/defineFormModels";
import {useProvideFormData} from "@/pages/login/components/hooks/useFormDataInjection";
import {useProvideFormRef} from "@/pages/login/components/hooks/useFormRefInjection";
import {useProvideSendSmsFn} from "@/pages/login/components/hooks/useSmsInjection";

const {GetInfo} = useUserStore()
const loading = ref(false)

// form data and service
const form = ref(null)
const popup = ref(null)
const [m, r, modelToCommit] = createChangePhoneModelRules()
const [model, rules] = useProvideFormData(m, r)
useProvideFormRef(form)
useProvideSendSmsFn(() => handleSendSms())

// methods
const handleSendSms = function () {
    return sendSms({mobile: model.value.mobile, smsType: 1})
}

const handleSubmit = async function () {
    await form.value.validate()
    loading.value = true
    try {
        const commit = modelToCommit()
        await updatePhonenumber(commit)
        toast('手机号变更成功')
        form.value.resetFields()
        await GetInfo()
    } finally {
        loading.value = false
    }
}

const open = function () {
    popup.value.open()
}
const close = function () {
    form.value.clearValidate()
    popup.value.close()
}

defineExpose({open, close})

</script>

<style scoped>

</style>