<script setup lang="ts">
import type { PropType } from 'vue';

import { onMounted, ref } from 'vue';

import { useVModel } from '@vueuse/core';

const props = defineProps({
  api: {
    type: Function as PropType<(params: any) => Promise<unknown>>,
    default: null,
  },
  uuidField: {
    type: String,
    default: 'uuid',
  },
  base64Field: {
    type: String,
    default: 'base64',
  },
  prefix: {
    type: String,
    default: 'data:image/png;base64,',
  },
  value: {
    type: String,
    default: '',
  },
  params: {
    type: Object,
    default: () => {
      return {};
    },
  },
  immediate: {
    type: Boolean,
    default: true,
  },
});
const emit = defineEmits(['update:modelValue']);

const modelValue = useVModel(props, 'value', emit, {
  defaultValue: props.value,
  passive: true,
});

const base64 = ref<string>('');
const fetch = () => {
  props.api?.(props.params).then((res: any) => {
    modelValue.value = res[props.uuidField];
    base64.value = `${props.prefix}${res[props.base64Field]}`;
    emit('update:modelValue', res[props.uuidField]);
  });
};
onMounted(() => {
  if (props.immediate) {
    fetch();
  }
});

defineExpose({
  resume: fetch,
});
</script>
<template>
  <div class="m-captcha">
    <img :src="base64" @click="fetch" />
  </div>
</template>
<style lang="less" scoped></style>
