<template>
    <mx-popup-template ref="popup" title="请输入图形验证码" container-class="p-50" mode="bottom" left="" right="确定"
                       closeable @right="handleConfirm">
        <view class="fx-col fx-cen-cen bg-white gap-20">
            <view class="fx-row gap-20">
                <uv-image :src="img" height="50" width="auto" mode="heightFix"/>
                <uv-icon name="reload" size="24" @click="loadCodeImage(true)"/>
            </view>
            <view>
                <uv-input v-model="code" placeholder="请输入上图结果" custom-style="height:32px"/>
            </view>
        </view>
    </mx-popup-template>
</template>

<script setup>
import {ref, nextTick} from 'vue'
import {getCodeImg} from "@/api/login";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {toValue} from "@vueuse/core";

const img = ref('')
const uuid = ref('')
const code = ref('')
const popup = ref(null)

const emits = defineEmits(['complete'])

const loadCodeImage = async function (force) {
    if (!force && uuid.value && img.value) return
    const res = await getCodeImg()
    uuid.value = res.uuid
    img.value = "data:image/gif;base64," + res.img
}

const reset = function () {
    uuid.value = ''
    img.value = ''
    code.value = ''
}

const handleConfirm = function () {
    if (!code.value) {
        return toast('请输入验证码')
    }
    close()
    const data = {code: toValue(code), uuid: toValue(uuid)}
    emits('complete', data)
    nextTick(() => reset())
}

const open = function () {
    loadCodeImage()
    popup.value.open()
}

const close = function () {
    popup.value.close()
}

defineExpose({open, close})
</script>

<style scoped>

</style>