<script setup lang="ts">
import { ref, watch } from 'vue'
import { authGetCodeUsingGet } from '@/service'

interface Props {
  phone: string
}

interface Emits {
  (e: 'update:code', code: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态管理
const code = ref('')
const disabled = ref(false)
const countdown = ref(0)
const codeText = ref('获取验证码')

// 监听验证码变化
watch(code, (newCode) => {
  emit('update:code', newCode)
})

// 发送验证码
async function sendCode() {
  if (!props.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(props.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
    })
    return
  }

  try {
    await authGetCodeUsingGet({
      params: { phone: props.phone },
    })

    uni.showToast({
      title: '验证码已发送',
      icon: 'success',
    })

    // 开始倒计时
    startCountdown()
  }
  catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none',
    })
  }
}

// 开始倒计时
function startCountdown() {
  disabled.value = true
  countdown.value = 60

  const timer = setInterval(() => {
    countdown.value--
    codeText.value = `${countdown.value}s后重发`

    if (countdown.value <= 0) {
      clearInterval(timer)
      disabled.value = false
      codeText.value = '获取验证码'
    }
  }, 1000)
}

// 重新获取验证码的提示
function handleNoCode() {
  uni.showModal({
    title: '提示',
    content: '如果您收不到验证码，请检查手机号是否正确，或联系客服获取帮助。',
    showCancel: false,
  })
}
</script>

<template>
  <view class="space-y-2">
    <text class="block text-sm text-gray-700 font-medium">验证码</text>
    <view class="flex space-x-3">
      <wd-input
        v-model="code"
        placeholder="请输入验证码"
        type="number"
        :maxlength="6"
        clearable
        class="flex-1"
      />
      <wd-button
        type="primary"
        size="small"
        :disabled="disabled"
        class="h-10 whitespace-nowrap px-4 text-xs"
        @click="sendCode"
      >
        {{ codeText }}
      </wd-button>
    </view>
  </view>
</template>
