<template>
  <div class="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="header-actions">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 280px;"
            @change="loadStats"
          />
          <el-select
            v-model="filterResponseType"
            placeholder="响应类型"
            clearable
            style="width: 140px;"
            @change="loadStats"
          >
            <el-option label="固定回复" value="fixed" />
            <el-option label="知识库检索" value="rag" />
            <el-option label="话术流程" value="flow" />
            <el-option label="转人工" value="transfer" />
          </el-select>
        </div>
      </div>
    </div>

    <el-row :gutter="20" class="stats-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="总命中次数" :value="stats.totalHits">
            <template #suffix>
              <span class="stat-suffix">次</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="总对话数" :value="stats.totalConversations">
            <template #suffix>
              <span class="stat-suffix">条</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="命中率" :value="(stats.hitRate * 100).toFixed(1)">
            <template #suffix>
              <span class="stat-suffix">%</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" class="rule-stats-card" v-loading="loading">
      <template #header>
        <span>规则命中统计</span>
      </template>
      <el-table :data="stats.rules" stripe style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="ruleName" label="规则名称" min-width="150" />
        <el-table-column prop="hitCount" label="命中次数" width="100" sortable>
          <template #default="{ row }">
            <el-tag type="primary">{{ row.hitCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hitRate" label="命中率" width="100" sortable>
          <template #default="{ row }">
            {{ (row.hitRate * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="avgResponseTime" label="平均响应时间" width="130">
          <template #default="{ row }">
            {{ row.avgResponseTime.toFixed(0) }} ms
          </template>
        </el-table-column>
        <el-table-column prop="responseType" label="响应类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getResponseTagType(row.responseType)" size="small">
              {{ getResponseLabel(row.responseType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastHitTime" label="最后命中时间" width="170">
          <template #default="{ row }">
            {{ row.lastHitTime ? formatTime(row.lastHitTime) : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer
      v-model="drawerVisible"
      :title="`${selectedRuleName} - 命中记录`"
      size="50%"
      direction="rtl"
    >
      <div class="hit-records" v-loading="hitsLoading">
        <el-table :data="hitRecords" stripe style="width: 100%">
          <el-table-column prop="userMessage" label="用户消息" min-width="200" show-overflow-tooltip />
          <el-table-column prop="matchedKeywords" label="匹配关键词" width="150">
            <template #default="{ row }">
              <div class="keyword-tags">
                <el-tag
                  v-for="(kw, idx) in row.matchedKeywords?.slice(0, 2)"
                  :key="idx"
                  size="small"
                  type="success"
                >
                  {{ kw }}
                </el-tag>
                <span v-if="row.matchedKeywords?.length > 2" class="more">
                  +{{ row.matchedKeywords.length - 2 }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="responseType" label="响应类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getResponseTagType(row.responseType)" size="small">
                {{ getResponseLabel(row.responseType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="executionResult" label="执行结果" width="90">
            <template #default="{ row }">
              <el-tag :type="row.executionResult === 'success' ? 'success' : 'danger'" size="small">
                {{ row.executionResult === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hitTime" label="命中时间" width="170">
            <template #default="{ row }">
              {{ formatTime(row.hitTime) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalHits"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="loadHitRecords"
            @current-change="loadHitRecords"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getIntentRuleStats,
  getIntentRuleHits,
  type IntentRuleStatsResponse,
  type IntentRuleHitRecord
} from '@/api/monitoring'

const loading = ref(false)
const hitsLoading = ref(false)
const dateRange = ref<[string, string] | null>(null)
const filterResponseType = ref('')

const stats = ref<IntentRuleStatsResponse>({
  totalHits: 0,
  totalConversations: 0,
  hitRate: 0,
  rules: []
})

const drawerVisible = ref(false)
const selectedRuleId = ref('')
const selectedRuleName = ref('')
const hitRecords = ref<IntentRuleHitRecord[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalHits = ref(0)

const getResponseLabel = (type: string) => {
  const labels: Record<string, string> = {
    fixed: '固定回复',
    rag: '知识库检索',
    flow: '话术流程',
    transfer: '转人工'
  }
  return labels[type] || type
}

const getResponseTagType = (type: string): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const colorMap: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    fixed: '',
    rag: 'success',
    flow: 'warning',
    transfer: 'danger'
  }
  return colorMap[type] || 'info'
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const loadStats = async () => {
  loading.value = true
  try {
    const params: Record<string, string | undefined> = {}
    if (dateRange.value) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    if (filterResponseType.value) {
      params.responseType = filterResponseType.value
    }
    stats.value = await getIntentRuleStats(params)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

const handleRowClick = (row: { ruleId: string; ruleName: string }) => {
  selectedRuleId.value = row.ruleId
  selectedRuleName.value = row.ruleName
  currentPage.value = 1
  loadHitRecords()
  drawerVisible.value = true
}

const loadHitRecords = async () => {
  hitsLoading.value = true
  try {
    const res = await getIntentRuleHits(selectedRuleId.value, {
      page: currentPage.value,
      pageSize: pageSize.value
    })
    hitRecords.value = res.records
    totalHits.value = res.total
  } catch (error) {
    ElMessage.error('加载命中记录失败')
  } finally {
    hitsLoading.value = false
  }
}

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

<style scoped>
.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);
}

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

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

.stat-card {
  text-align: center;
  padding: 12px 0;
}

.stat-suffix {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.rule-stats-card {
  border-radius: 8px;
}

.hit-records {
  padding: 0 20px;
}

.keyword-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
}

.more {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

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