<template>
    <mx-form-item v-model="model[propMobile]" :prop="propMobile" :label="labelMobile"/>
    <mx-form-item v-model="model[propCode]" :prop="propCode" :label="labelCode">
        <template #suffix>
            <mx-count-down :text="labelSend" :validate-block="validateMobile" @click="handleSend"/>
        </template>
    </mx-form-item>
    <code-input-popup ref="popup" @complete="handleComplete"/>
</template>

<script setup>
import {ref} from 'vue';
import {useInjectFormData} from "@/pagesOther/pages/login/components/hooks/useFormDataInjection";
import {useInjectFormRef} from "@/pagesOther/pages/login/components/hooks/useFormRefInjection";
import {useInjectSendSmsFn} from "@/pagesOther/pages/login/components/hooks/useSmsInjection";
import {useUserStore} from "@/hooks/useUserStore";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {createPropDefine} from "@/utils";
import CodeInputPopup from "@/pagesOther/pages/login/components/code-input-popup.vue";

const props = defineProps({
    propMobile: createPropDefine('mobile'),
    propCode: createPropDefine('smsCode'),
    labelMobile: createPropDefine('手机号码'),
    labelCode: createPropDefine('验证码'),
    labelSend: createPropDefine('获取')
})

const [model] = useInjectFormData()
const {form} = useInjectFormRef()
const {sendSmsFn} = useInjectSendSmsFn()

// code input
const popup = ref(null)
const {isLogin} = useUserStore()
let codeInputResolve = null, codeInputReject = null

const validateMobile = async () => {
    form.value.clearValidate()
    await form.value.validate([props.propMobile])
    if (!isLogin.value) {
        popup.value.open()
        return new Promise((resolve, reject) => {
            codeInputResolve = resolve
            codeInputReject = reject
        })
    } else {
        // login state - send directly
        handleComplete({})
    }
}

const handleSend = async () => {
    // sendSmsFn() // sendSmsFn move into validateBlock caused by code input
    toast(`${props.labelCode}已发送`)
}

const handleComplete = (events) => {
    sendSmsFn(events).then(codeInputResolve).catch(codeInputReject)
}
</script>

<style scoped>

</style>