<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="flex space-x-3">
    <view class="flex-1 rounded-xl border-2 border-gray-200 bg-gray-50 px-4 py-3 transition-all focus-within:border-blue-500 focus-within:bg-white">
      <input
        v-model="code"
        type="number"
        placeholder="请输入验证码"
        maxlength="6"
        class="h-8 w-full border-none bg-transparent text-base text-gray-900 outline-none placeholder:text-gray-400"
      />
    </view>
    <view
      class="min-w-28 flex items-center justify-center whitespace-nowrap rounded-xl bg-blue-600 px-4 py-3 text-sm text-white font-medium transition-all active:scale-95"
      :class="{ 'cursor-not-allowed bg-gray-400 opacity-60': disabled }"
      @click="disabled ? null : sendCode()"
    >
      {{ codeText }}
    </view>
  </view>
</template>
