<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="护栏测试"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="test-dialog">
      <div class="input-section">
        <div class="section-title">测试文本</div>
        <div class="input-hint">每行一条测试文本，系统将检测是否触发禁词</div>
        <el-input
          v-model="testTextsValue"
          type="textarea"
          :rows="5"
          placeholder="请输入测试文本，每行一条&#10;例如：&#10;我们的产品比竞品 A 更好&#10;可以给您赔偿 1000 元&#10;这是正常的回复"
        />
        <div class="input-actions">
          <el-button type="primary" :loading="testing" @click="handleTest">
            <el-icon><Search /></el-icon>
            开始测试
          </el-button>
        </div>
      </div>

      <div v-if="testResult" class="result-section">
        <el-divider content-position="left">测试结果</el-divider>
        
        <div class="result-summary">
          <el-row :gutter="16">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value">{{ testResult.summary.totalTests }}</div>
                <div class="summary-label">总测试数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value" :class="{ 'text-warning': testResult.summary.triggeredCount > 0 }">
                  {{ testResult.summary.triggeredCount }}
                </div>
                <div class="summary-label">触发数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value" :class="{ 'text-danger': testResult.summary.blockedCount > 0 }">
                  {{ testResult.summary.blockedCount }}
                </div>
                <div class="summary-label">拦截数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value" :class="triggerRateClass">
                  {{ (testResult.summary.triggerRate * 100).toFixed(0) }}%
                </div>
                <div class="summary-label">触发率</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="results-list">
          <div class="section-title">详细结果</div>
          <div
            v-for="(result, index) in testResult.results"
            :key="index"
            class="result-item"
            :class="{ 'result-triggered': result.triggered, 'result-blocked': result.blocked }"
          >
            <div class="result-header">
              <el-tag :type="result.blocked ? 'danger' : result.triggered ? 'warning' : 'success'" size="small">
                {{ result.blocked ? '已拦截' : result.triggered ? '已触发' : '正常' }}
              </el-tag>
            </div>
            <div class="result-original">
              <span class="label">原文：</span>
              <span v-html="highlightWords(result.originalText, result.triggeredWords)"></span>
            </div>
            <div v-if="result.triggered" class="result-filtered">
              <span class="label">处理后：</span>
              {{ result.filteredText }}
            </div>
            <div v-if="result.triggeredWords.length > 0" class="result-words">
              <span class="label">触发禁词：</span>
              <el-tag
                v-for="word in result.triggeredWords"
                :key="word.word"
                :type="word.strategy === 'block' ? 'danger' : 'warning'"
                size="small"
                style="margin-right: 4px;"
              >
                {{ word.word }} ({{ getCategoryLabel(word.category) }} - {{ getStrategyLabel(word.strategy) }})
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="$emit('update:visible', false)">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { testGuardrail, type GuardrailTestResponse, type TriggeredWordInfo } from '@/api/guardrail'

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

const testTextsValue = ref('')
const testing = ref(false)
const testResult = ref<GuardrailTestResponse | null>(null)

const triggerRateClass = computed(() => {
  if (!testResult.value) return ''
  const rate = testResult.value.summary.triggerRate
  if (rate >= 0.5) return 'text-danger'
  if (rate >= 0.2) return 'text-warning'
  return 'text-success'
})

const getCategoryLabel = (category: string) => {
  const labels: Record<string, string> = {
    competitor: '竞品',
    sensitive: '敏感',
    political: '政治',
    custom: '自定义'
  }
  return labels[category] || category
}

const getStrategyLabel = (strategy: string) => {
  const labels: Record<string, string> = {
    mask: '掩码',
    replace: '替换',
    block: '拦截'
  }
  return labels[strategy] || strategy
}

const highlightWords = (text: string, triggeredWords: TriggeredWordInfo[]) => {
  if (!triggeredWords || triggeredWords.length === 0) return text
  
  let result = text
  for (const word of triggeredWords) {
    const regex = new RegExp(word.word, 'gi')
    result = result.replace(regex, `<span class="highlight-word">${word.word}</span>`)
  }
  return result
}

const handleTest = async () => {
  const texts = testTextsValue.value
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0)

  if (texts.length === 0) {
    ElMessage.warning('请输入至少一条测试文本')
    return
  }

  testing.value = true
  try {
    const result = await testGuardrail({ testTexts: texts })
    testResult.value = result
    ElMessage.success('测试完成')
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    testing.value = false
  }
}
</script>

<style scoped>
.test-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.input-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.input-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.input-actions {
  margin-top: 12px;
}

.result-section {
  margin-top: 20px;
}

.result-summary {
  margin-bottom: 16px;
}

.summary-item {
  text-align: center;
  padding: 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 6px;
}

.summary-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.summary-value.text-success {
  color: var(--el-color-success);
}

.summary-value.text-warning {
  color: var(--el-color-warning);
}

.summary-value.text-danger {
  color: var(--el-color-danger);
}

.summary-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.results-list {
  margin-top: 16px;
}

.result-item {
  padding: 12px;
  margin-bottom: 12px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background-color: var(--el-bg-color);
}

.result-item.result-triggered {
  border-color: var(--el-color-warning-light-3);
  background-color: var(--el-color-warning-light-9);
}

.result-item.result-blocked {
  border-color: var(--el-color-danger-light-3);
  background-color: var(--el-color-danger-light-9);
}

.result-header {
  margin-bottom: 8px;
}

.result-original,
.result-filtered,
.result-words {
  font-size: 13px;
  margin-bottom: 4px;
  line-height: 1.6;
}

.result-original .label,
.result-filtered .label,
.result-words .label {
  color: var(--el-text-color-secondary);
  margin-right: 4px;
}

:deep(.highlight-word) {
  background-color: var(--el-color-warning-light-5);
  padding: 0 2px;
  border-radius: 2px;
  font-weight: 600;
}
</style>
