<template>
  <!-- #ifdef H5 -->
  <teleport to="body">
  <!-- #endif -->
  <!-- #ifdef MP-WEIXIN -->
  <root-portal externalClass="theme-ie">
  <!-- #endif -->
    <uv-popup ref="popupRef" mode="bottom" :close-on-click-overlay="false" :closeable="true" :round="16">
      <view class="theme-ie w-auto box-border px-40 pt-100 pb-60 bg-white">
        <ie-image :src="captchaImage" custom-class="w-fit h-104 mx-auto" mode="heightFix" @click="debounceGetImage" />
        <ie-input v-model="codeModelValue" custom-class="mt-40" type="number" :maxlength="3" placeholder="请输入验证码" />
        <ie-button custom-class="mt-40" @click="handleSubmit">确定</ie-button>
      </view>
    </uv-popup>
    <!-- #ifdef MP-WEIXIN -->
    </root-portal>
    <!-- #endif -->
  <!-- #ifdef H5 -->
  </teleport>
  <!-- #endif -->
</template>
<script lang="ts" setup>
import { getCaptchaImage } from '@/api/modules/system';
import { useDebounce } from '@/hooks/useDebounce';
const codeModelValue = defineModel('code', {
  type: String as PropType<string | undefined>,
  default: undefined
});
const uuidModelValue = defineModel('uuid', {
  type: String as PropType<string>,
  default: ''
});
const captchaImage = ref('');
const popupRef = ref();

const getImage = async () => {
  const { uuid, img } = await getCaptchaImage();
  captchaImage.value = 'data:image/gif;base64,' + img;
  uuidModelValue.value = uuid;
}
const debounceGetImage = useDebounce(getImage, 300);
const open = async () => {
  codeModelValue.value = undefined;
  try {
    uni.$ie.showLoading();
    await getImage();
    uni.$ie.hideLoading();
  } catch (error) {
    uni.$ie.hideLoading();
    uni.$ie.showToast('获取验证码失败');
  }
  popupRef.value.open();
}
const close = () => {
  popupRef.value.close();
}

const emit = defineEmits(['valid']);
const handleSubmit = () => {
  if (!codeModelValue.value) {
    uni.$ie.showToast('请输入验证码');
    return;
  }
  emit('valid', {
    code: codeModelValue.value,
    uuid: uuidModelValue.value
  });
}

defineExpose({
  open,
  close,
  changeImage: getImage
});
</script>
<style lang="scss" scoped></style>