<!--
 * @Author: wyd
 * @Date: 2024-03
 * @LastEditors: wyd
 * @LastEditTime: 2024-04
 * @Description: 验证码
-->

<script setup lang="ts">
import { watch, ref, onMounted } from 'vue'
import { getCaptchaImageApi } from '@/api/login'
const props = defineProps({
  modelValue: String
})
const emit = defineEmits(['getCaptchaInfo', 'update:modelValue'])
const form = {
  code: '',
  uuid: '',
  captchaEnabled: true
}
watch(
  () => props.modelValue,
  (val, pre) => {
    form.code = props.modelValue || ''
  }
)
// 更新code
const codeChange = () => {
  emit('update:modelValue', form.code)
  emit('getCaptchaInfo', form)
}
const imgPath = ref('')
// 获取验证码图片
const getCaptchaImage = () => {
  getCaptchaImageApi({ isWeb: false }).then((res) => {
    form.captchaEnabled = res.data.captchaEnabled
    form.uuid = res.data.uuid
    if (res.data.captchaEnabled) {
      imgPath.value = 'data:image/jpeg;base64,' + res.data.img
    }
    emit('getCaptchaInfo', form)
  })
}
onMounted(() => {
  getCaptchaImage()
})
defineExpose({ getCaptchaImage })
</script>

<template>
  <view class="flex j-sb a-center">
    <uni-easyinput type="text" v-model="form.code" placeholder="请输入验证码" @change="codeChange" />
    <image :src="imgPath" mode="aspectFill" class="capcha-img ml10" @tap="getCaptchaImage" />
  </view>
</template>

<style lang="scss" scoped>
.capcha-img {
  width: 100px;
  height: 35px;
  border-radius: 4px;
}
</style>
