<template>
  <el-card shadow="hover" class="test-panel">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <div class="icon-wrapper">
            <el-icon><Connection /></el-icon>
          </div>
          <span class="header-title">连接测试</span>
        </div>
        <el-tag v-if="testResult" :type="testResult.success ? 'success' : 'danger'" size="small" effect="dark">
          {{ testResult.success ? '连接成功' : '连接失败' }}
        </el-tag>
      </div>
    </template>

    <div class="test-content">
      <div class="test-form-section">
        <div class="section-label">
          <el-icon><Edit /></el-icon>
          <span>测试文本</span>
        </div>
        <el-input
          v-model="testForm.test_text"
          type="textarea"
          :rows="3"
          placeholder="请输入测试文本（可选，默认使用系统预设文本）"
          clearable
          class="test-textarea"
        />
        <el-button
          type="primary"
          size="large"
          :loading="loading"
          :disabled="!config?.provider"
          class="test-button"
          @click="handleTest"
        >
          <el-icon v-if="!loading"><Connection /></el-icon>
          {{ loading ? '测试中...' : '测试连接' }}
        </el-button>
      </div>

      <transition name="result-fade">
        <div v-if="testResult" class="test-result">
          <el-divider />

          <div v-if="testResult.success" class="success-result">
            <div class="result-header">
              <div class="success-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <span class="result-title">{{ testResult.message || '连接成功' }}</span>
            </div>
            <div class="success-details">
              <div class="detail-card">
                <div class="detail-icon">
                  <el-icon><Grid /></el-icon>
                </div>
                <div class="detail-info">
                  <span class="detail-label">向量维度</span>
                  <span class="detail-value">{{ testResult.dimension }}</span>
                </div>
              </div>
              <div v-if="testResult.latency_ms" class="detail-card">
                <div class="detail-icon">
                  <el-icon><Timer /></el-icon>
                </div>
                <div class="detail-info">
                  <span class="detail-label">响应延迟</span>
                  <span class="detail-value">{{ testResult.latency_ms.toFixed(2) }} ms</span>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="error-result">
            <div class="result-header">
              <div class="error-icon">
                <el-icon><CircleClose /></el-icon>
              </div>
              <span class="result-title error">连接失败</span>
            </div>
            <div class="error-message-box">
              <p class="error-text">{{ testResult.error || '未知错误' }}</p>
            </div>
            <div class="troubleshooting">
              <div class="troubleshoot-header">
                <el-icon><Warning /></el-icon>
                <span>排查建议</span>
              </div>
              <ul class="troubleshoot-list">
                <li v-for="(tip, index) in troubleshootingTips" :key="index">
                  <el-icon class="list-icon"><Right /></el-icon>
                  {{ tip }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Connection, Edit, CircleCheck, CircleClose, Timer, Grid, Warning, Right } from '@element-plus/icons-vue'
import { testEmbedding, type EmbeddingConfigUpdate, type EmbeddingTestResult } from '@/api/embedding'

const props = defineProps<{
  config: EmbeddingConfigUpdate | null
}>()

const loading = ref(false)
const testResult = ref<EmbeddingTestResult | null>(null)

const testForm = ref({
  test_text: ''
})

const troubleshootingTips = computed(() => {
  const tips: string[] = []
  const error = testResult.value?.error?.toLowerCase() || ''

  if (error.includes('timeout') || error.includes('超时')) {
    tips.push('检查网络连接是否正常')
    tips.push('确认服务地址是否正确且可访问')
    tips.push('尝试增加请求超时时间')
  } else if (error.includes('auth') || error.includes('unauthorized') || error.includes('认证') || error.includes('api key')) {
    tips.push('检查 API Key 是否正确')
    tips.push('确认 API Key 是否已过期或被禁用')
    tips.push('验证 API Key 是否具有足够的权限')
  } else if (error.includes('connection') || error.includes('连接') || error.includes('refused')) {
    tips.push('确认服务地址（host/port）配置正确')
    tips.push('检查目标服务是否正在运行')
    tips.push('验证防火墙是否允许访问')
  } else if (error.includes('model') || error.includes('模型')) {
    tips.push('确认模型名称是否正确')
    tips.push('检查模型是否已部署或可用')
    tips.push('验证模型配置参数是否符合要求')
  } else {
    tips.push('检查所有配置参数是否正确')
    tips.push('确认服务是否正常运行')
    tips.push('查看服务端日志获取详细错误信息')
  }

  return tips
})

const handleTest = async () => {
  if (!props.config?.provider) {
    return
  }

  loading.value = true
  testResult.value = null

  try {
    const requestData: any = {
      config: props.config
    }
    if (testForm.value.test_text?.trim()) {
      requestData.test_text = testForm.value.test_text.trim()
    }

    const result = await testEmbedding(requestData)
    testResult.value = result
  } catch (error: any) {
    testResult.value = {
      success: false,
      dimension: 0,
      error: error?.message || '请求失败，请检查网络连接'
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.test-panel {
  border-radius: 16px;
  border: none;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.test-panel:hover {
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
  transform: translateY(-4px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 10px;
  color: #ffffff;
  font-size: 20px;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.test-content {
  padding: 8px 0;
}

.test-form-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.section-label .el-icon {
  color: #667eea;
}

.test-textarea {
  border-radius: 10px;
}

.test-textarea :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.test-textarea :deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.test-button {
  align-self: flex-start;
  border-radius: 10px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.test-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.test-button:disabled {
  opacity: 0.6;
}

.test-result {
  animation: fadeIn 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.success-icon,
.error-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 20px;
}

.success-icon {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: #ffffff;
}

.error-icon {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  color: #ffffff;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #67c23a;
}

.result-title.error {
  color: #f56c6c;
}

.success-details {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.detail-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 18px;
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
  border-radius: 12px;
  border: 1px solid #e1f3d8;
}

.detail-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border-radius: 10px;
  color: #ffffff;
  font-size: 18px;
}

.detail-info {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 12px;
  color: #909399;
}

.detail-value {
  font-size: 18px;
  font-weight: 700;
  color: #303133;
}

.error-result {
  animation: shake 0.5s ease-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.error-message-box {
  padding: 14px 16px;
  background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);
  border-radius: 10px;
  border-left: 3px solid #f56c6c;
  margin-bottom: 16px;
}

.error-text {
  margin: 0;
  color: #f56c6c;
  font-size: 14px;
  line-height: 1.6;
}

.troubleshooting {
  padding: 16px;
  background: linear-gradient(135deg, #fdf6ec 0%, #faecd8 100%);
  border-radius: 12px;
  border: 1px solid #faecd8;
}

.troubleshoot-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #e6a23c;
}

.troubleshoot-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.troubleshoot-list li {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  color: #606266;
  font-size: 13px;
  line-height: 1.6;
}

.list-icon {
  margin-top: 4px;
  color: #e6a23c;
  font-size: 12px;
}

.result-fade-enter-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.result-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.result-fade-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.result-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
