<template>
  <div class="guardrail-monitoring-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">输出护栏监控</h1>
          <p class="page-desc">查看护栏拦截统计和禁词触发记录。</p>
        </div>
        <div class="filter-section">
          <el-select v-model="filterCategory" placeholder="按类别筛选" clearable @change="loadStats">
            <el-option label="竞品" value="competitor" />
            <el-option label="敏感" value="sensitive" />
            <el-option label="政治" value="political" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </div>
      </div>
    </div>

    <el-row :gutter="16" class="summary-cards">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-warning-light-9);">
              <el-icon :size="24" color="var(--el-color-warning)"><Warning /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ stats.totalTriggers }}</div>
              <div class="summary-label">总触发次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-danger-light-9);">
              <el-icon :size="24" color="var(--el-color-danger)"><CircleClose /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ stats.totalBlocks }}</div>
              <div class="summary-label">总拦截次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-info-light-9);">
              <el-icon :size="24" color="var(--el-color-info)"><DataAnalysis /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ (stats.blockRate * 100).toFixed(2) }}%</div>
              <div class="summary-label">拦截率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16">
      <el-col :span="16">
        <el-card shadow="hover" class="word-table-card" v-loading="loading">
          <template #header>
            <span>禁词统计列表</span>
          </template>
          <el-table :data="stats.words" stripe style="width: 100%">
            <el-table-column prop="word" label="禁词" min-width="120" />
            <el-table-column prop="category" label="类别" width="100">
              <template #default="{ row }">
                <el-tag :type="getCategoryType(row.category)" size="small">
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="strategy" label="策略" width="80">
              <template #default="{ row }">
                {{ getStrategyLabel(row.strategy) }}
              </template>
            </el-table-column>
            <el-table-column prop="hitCount" label="命中次数" width="100" sortable />
            <el-table-column prop="blockCount" label="拦截次数" width="100" sortable />
            <el-table-column prop="lastHitAt" label="最近命中" width="160">
              <template #default="{ row }">
                {{ formatDate(row.lastHitAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="row.strategy === 'block'"
                  type="primary"
                  link
                  size="small"
                  @click="showBlocks(row)"
                >
                  详情
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="category-card">
          <template #header>
            <span>类别分布</span>
          </template>
          <div class="category-list">
            <div
              v-for="(count, category) in stats.categoryBreakdown"
              :key="category"
              class="category-item"
            >
              <div class="category-label">
                <el-tag :type="getCategoryType(category)" size="small">
                  {{ getCategoryLabel(category) }}
                </el-tag>
              </div>
              <div class="category-bar">
                <el-progress
                  :percentage="getCategoryPercentage(category)"
                  :color="getCategoryColor(category)"
                  :stroke-width="12"
                  :show-text="false"
                />
              </div>
              <div class="category-count">{{ count }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      v-model="blocksDialogVisible"
      :title="`拦截记录 - ${currentWord}`"
      width="700px"
      destroy-on-close
    >
      <el-table :data="blocks" v-loading="blocksLoading" stripe>
        <el-table-column prop="sessionId" label="会话ID" min-width="180" />
        <el-table-column prop="originalText" label="原始文本" min-width="200">
          <template #default="{ row }">
            <el-text truncated>{{ row.originalText }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="filteredText" label="处理后" min-width="150">
          <template #default="{ row }">
            <el-text truncated>{{ row.filteredText }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="blockedAt" label="拦截时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.blockedAt) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="blocksPage"
          :page-size="20"
          :total="blocksTotal"
          layout="total, prev, pager, next"
          @current-change="loadBlocks"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Warning, CircleClose, DataAnalysis } from '@element-plus/icons-vue'
import { getGuardrailStats, getGuardrailBlocks, type GuardrailStatsResponse, type GuardrailBlockRecord } from '@/api/monitoring'

const loading = ref(false)
const filterCategory = ref('')
const stats = ref<GuardrailStatsResponse>({
  totalBlocks: 0,
  totalTriggers: 0,
  blockRate: 0,
  words: [],
  categoryBreakdown: {
    competitor: 0,
    sensitive: 0,
    political: 0,
    custom: 0
  }
})

const blocksDialogVisible = ref(false)
const blocksLoading = ref(false)
const currentWordId = ref('')
const currentWord = ref('')
const blocks = ref<GuardrailBlockRecord[]>([])
const blocksPage = ref(1)
const blocksTotal = ref(0)

const formatDate = (dateStr: string | null) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

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

const getCategoryType = (category: string) => {
  const types: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    competitor: 'danger',
    sensitive: 'warning',
    political: 'danger',
    custom: 'info'
  }
  return types[category] || 'info'
}

const getCategoryColor = (category: string) => {
  const colors: Record<string, string> = {
    competitor: '#F56C6C',
    sensitive: '#E6A23C',
    political: '#F56C6C',
    custom: '#909399'
  }
  return colors[category] || '#909399'
}

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

const getCategoryPercentage = computed(() => {
  return (category: string) => {
    const total = stats.value.totalTriggers
    if (total === 0) return 0
    return (stats.value.categoryBreakdown[category] / total) * 100
  }
})

const loadStats = async () => {
  loading.value = true
  try {
    const params: Record<string, string> = {}
    if (filterCategory.value) {
      params.category = filterCategory.value
    }
    stats.value = await getGuardrailStats(params)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

const showBlocks = (word: GuardrailStatsResponse['words'][0]) => {
  currentWordId.value = word.wordId
  currentWord.value = word.word
  blocksPage.value = 1
  blocksDialogVisible.value = true
  loadBlocks()
}

const loadBlocks = async () => {
  blocksLoading.value = true
  try {
    const res = await getGuardrailBlocks(currentWordId.value, {
      page: blocksPage.value,
      pageSize: 20
    })
    blocks.value = res.data
    blocksTotal.value = res.total
  } catch (error) {
    ElMessage.error('加载拦截记录失败')
  } finally {
    blocksLoading.value = false
  }
}

onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.guardrail-monitoring-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.title-section {
  flex: 1;
  min-width: 300px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.summary-cards {
  margin-bottom: 24px;
}

.summary-card {
  display: flex;
  align-items: center;
  gap: 16px;
}

.summary-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-content {
  flex: 1;
}

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

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

.word-table-card,
.category-card {
  border-radius: 8px;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-label {
  width: 70px;
}

.category-bar {
  flex: 1;
}

.category-count {
  width: 50px;
  text-align: right;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
