<template>
  <view :class="['ie-sms text-primary text-30', customClass]" @click="handleSend">{{ smsTip }}</view>
  <ie-captcha ref="captchaRef" v-model:code="code" v-model:uuid="uuid" @valid="handleValid" />
</template>
<script lang="ts" setup>
import { useAppConfig } from '@/hooks/useAppConfig';
import { useSms } from '@/hooks/useSms';
import IeCaptcha from './ie-captcha.vue';
import { EnumSmsApiType, EnumSmsType } from '@/common/enum';
import { SmsRequestDTO } from '@/types/user';
import { validatePhone } from '@/hooks/useValidation';
const sms = useSms();
const { smsTip, isCountingDown, smsIsSending } = sms;
const appConfig = useAppConfig();
defineOptions({
  virtualHost: true,
})
const props = defineProps({
  phone: {
    type: String,
    default: '',
    required: true
  },
  smsApiType: {
    type: String as PropType<EnumSmsApiType>,
    default: EnumSmsApiType.NO_VALIDATION_NO_TOKEN
  },
  smsType: {
    type: String as PropType<EnumSmsType>,
    default: EnumSmsType.CODE
  },
  customClass: {
    type: String,
    default: ''
  },
  beforeSend: {
    type: Function,
    default: () => true
  }
});

const captchaRef = ref();
const uuid = ref('');
const code = ref<string>('');

const handleValid = (data: { code: string; uuid: string }) => {
  handleSubmit();
}

const handleSubmit = () => {
  if (appConfig.isSmsCaptchaEnable.value && !code.value) {
    uni.$ie.showToast('请输入验证码');
    return;
  }
  uni.$ie.showLoading();
  const params: SmsRequestDTO = {
    mobile: props.phone,
    smsType: props.smsType,
    uuid: uuid.value,
    code: code.value
  };
  sms.sendSms(props.smsApiType, params).then(res => {
    uni.$ie.hideLoading();
    if (res.success) {
      captchaRef.value.close();
      uni.$ie.showToast('短信发送成功');
      emit('send', props.phone, code.value, uuid.value);
    } else if (res.error.msg === '手机号已存在') {
      captchaRef.value.close();
    } else {
      captchaRef.value.changeImage();
    }
  }).catch((err) => {
    uni.$ie.hideLoading();
  });
}

const emit = defineEmits<{
  send: [phone: string, code: string, uuid: string]
}>()

const handleSend = async () => {
  if (props.beforeSend && !props.beforeSend()) {
    return;
  }
  if (!props.phone) {
    uni.$ie.showToast('请输入手机号');
    return;
  }
  if (!validatePhone(props.phone)) {
    uni.$ie.showToast('请输入正确的手机号');
    return;
  }
  if (smsIsSending.value || isCountingDown.value) {
    return;
  }
  if (appConfig.isSmsCaptchaEnable.value) {
    captchaRef.value.open();
  } else {
    handleSubmit();
  }
}

onLoad(() => {
  sms.init();
});
</script>
<style lang="scss" scoped></style>