<template>
  <div class="captcha-container">
    <div class="captcha-input-group">
      <el-input
        v-model="captchaInput"
        :placeholder="placeholder"
        :size="size"
        clearable
        @keyup.enter="$emit('verify', { captchaId, captchaText: captchaInput })"
        @input="handleInput"
      />
      <div class="captcha-image-wrapper" @click="refreshCaptcha">
        <img 
          v-if="captchaImage" 
          :src="captchaImage" 
          alt="验证码" 
          class="captcha-image"
        />
        <div v-else class="captcha-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div class="captcha-refresh-hint">
          <el-icon><Refresh /></el-icon>
          <span>点击刷新</span>
        </div>
      </div>
    </div>
    <div class="captcha-actions">
      <el-button 
        type="text" 
        size="small" 
        @click="refreshCaptcha"
        :loading="loading"
      >
        <el-icon><Refresh /></el-icon>
        刷新验证码
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Loading } from '@element-plus/icons-vue'
import api from '@/utils/api'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入验证码'
  },
  size: {
    type: String,
    default: 'large'
  },
  autoRefresh: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'verify', 'refresh'])

// 响应式数据
const captchaInput = ref(props.modelValue)
const captchaImage = ref('')
const captchaId = ref('')
const loading = ref(false)

/**
 * 获取验证码
 */
const getCaptcha = async () => {
  try {
    loading.value = true
    const response = await api.get('/captcha/generate')
    
    if (response.data.success) {
      captchaImage.value = response.data.data.image
      captchaId.value = response.data.data.captchaId
      emit('refresh', { captchaId: captchaId.value })
    } else {
      ElMessage.error(response.data.message || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

/**
 * 刷新验证码
 */
const refreshCaptcha = async () => {
  captchaInput.value = ''
  emit('update:modelValue', '')
  await getCaptcha()
}

/**
 * 处理输入变化
 */
const handleInput = (value) => {
  emit('update:modelValue', value)
}

/**
 * 验证验证码
 * @param {string} inputText 用户输入的验证码
 * @returns {Promise<boolean>} 验证结果
 */
const verifyCaptcha = async (inputText) => {
  if (!captchaId.value) {
    ElMessage.error('请先获取验证码')
    return false
  }
  
  if (!inputText || inputText.trim() === '') {
    ElMessage.error('请输入验证码')
    return false
  }
  
  try {
    const response = await api.post('/captcha/verify', {
      captchaId: captchaId.value,
      captchaText: inputText.trim()
    })
    
    if (response.data.success) {
      return true
    } else {
      ElMessage.error(response.data.message || '验证码错误')
      // 验证失败后刷新验证码
      await refreshCaptcha()
      return false
    }
  } catch (error) {
    console.error('验证验证码失败:', error)
    ElMessage.error('验证验证码失败，请重试')
    await refreshCaptcha()
    return false
  }
}

/**
 * 获取当前验证码信息
 * @returns {Object} 验证码信息
 */
const getCaptchaInfo = () => {
  return {
    captchaId: captchaId.value,
    captchaText: captchaInput.value
  }
}

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  captchaInput.value = newValue
})

// 组件挂载时获取验证码
onMounted(() => {
  if (props.autoRefresh) {
    getCaptcha()
  }
})

// 暴露方法给父组件
defineExpose({
  refreshCaptcha,
  verifyCaptcha,
  getCaptchaInfo
})
</script>

<style scoped>
.captcha-container {
  width: 100%;
}

.captcha-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input-group .el-input {
  flex: 1;
}

.captcha-image-wrapper {
  position: relative;
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s;
  background: #f5f7fa;
}

.captcha-image-wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.captcha-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.captcha-loading .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.captcha-refresh-hint {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 12px;
}

.captcha-image-wrapper:hover .captcha-refresh-hint {
  opacity: 1;
}

.captcha-refresh-hint .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.captcha-actions {
  margin-top: 8px;
  text-align: right;
}

.captcha-actions .el-button {
  padding: 0;
  font-size: 12px;
  color: #909399;
}

.captcha-actions .el-button:hover {
  color: #409eff;
}

.captcha-actions .el-icon {
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .captcha-input-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .captcha-image-wrapper {
    width: 100%;
    max-width: 200px;
    height: 50px;
  }
}
</style>