<script setup lang="ts">
import { debounce } from 'lodash-es'
import { onBeforeMount, ref } from 'vue'
import { getCaptcha } from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'Captcha' })

const emit = defineEmits(['change'])
const base64 = ref('')
const spinning = ref<boolean>(true)
const userStore = useUserStore()

const fetchCaptcha = debounce(async () => {
  spinning.value = true

  try {
    const token = await userStore.getCaptchaToken('math')
    const data = await getCaptcha(token)
    const u8a = new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), '')
    const src = `data:image/png;base64, ${btoa(u8a)}`
    base64.value = src
    emit('change')
  }
  catch (error) {
    console.error(error)
  }
  finally {
    spinning.value = false
  }
}, 300)

onBeforeMount(() => {
  fetchCaptcha()
})
</script>

<template>
  <div>
    <n-spin :show="spinning">
      <img
        title="点击刷新" :src="base64" :style="{ width: '93px', height: '54px', cursor: 'pointer' }"
        @click="fetchCaptcha"
      >
    </n-spin>
  </div>
</template>
