<!--
=============================================================================
企微IT智能服务台 — 运营总览仪表盘
=============================================================================
说明：管理后台首页仪表盘，展示：
  1. 4个统计卡片（在线坐席、今日会话、平均响应时间、AI命中率）
  2. 待处理事项列表
  3. 系统健康状态
-->
<template>
  <div class="dashboard-page">
    <!-- 页面标题 -->
    <div class="page-title">运营总览</div>
    <div class="page-desc">实时监控服务台运行状态，关键指标一目了然</div>

    <!-- 统计卡片行 -->
    <div class="stats-grid">
      <StatCard
        label="在线坐席"
        :value="overview.online_agents"
        valueColor="var(--success)"
        icon="UserFilled"
        iconColor="var(--success)"
        trend="运行正常"
        trendDirection="up"
      />
      <StatCard
        label="今日会话"
        :value="overview.today_conversations"
        valueColor="var(--accent)"
        icon="ChatDotRound"
        iconColor="var(--accent)"
        :subtitle="'较昨日 +12%'"
        trendDirection="up"
      />
      <StatCard
        label="平均响应时间"
        valueColor="var(--warning)"
        icon="Timer"
        iconColor="var(--warning)"
        trend="较昨日改善"
        trendDirection="down"
      >
        <template #value>
          {{ overview.avg_response_time || '—' }}
        </template>
      </StatCard>
      <StatCard
        label="AI 命中率"
        :value="overview.ai_hit_rate || '—'"
        valueColor="#8b5cf6"
        icon="MagicStick"
        iconColor="#8b5cf6"
        trend="本周 +5%"
        trendDirection="up"
      />
    </div>

    <!-- 双栏布局：待处理事项 + 系统健康 -->
    <div class="two-column">
      <!-- 待处理事项 -->
      <div class="table-wrapper">
        <div class="table-header-row">
          <div class="table-title">待处理事项</div>
          <el-tag type="warning" size="small">
            {{ overview.pending_reviews || 0 }} 项待审
          </el-tag>
        </div>
        <el-table
          :data="pendingItems"
          style="width: 100%"
          :header-cell-style="{ background: 'var(--bg-tertiary)', color: 'var(--text-secondary)', fontSize: '12px' }"
          :cell-style="{ color: 'var(--text-primary)', fontSize: '13px' }"
          row-class-name="dashboard-table-row"
        >
          <el-table-column label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.tagType" size="small" effect="plain">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="内容" prop="content" min-width="200" />
          <el-table-column label="提交人" prop="submitter" width="80" />
          <el-table-column label="时间" prop="time" width="100" />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button size="small" text type="primary" @click="handlePendingAction(row)">
                {{ row.actionText }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 系统健康状态 -->
      <div class="table-wrapper">
        <div class="table-header-row">
          <div class="table-title">系统健康</div>
        </div>
        <div class="health-list">
          <div
            v-for="item in healthItems"
            :key="item.name"
            class="health-item"
          >
            <span class="health-name">{{ item.name }}</span>
            <el-tag :type="item.statusType" size="small" effect="dark">
              {{ item.statusText }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// ==========================================================================
// 依赖导入
// ==========================================================================
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import StatCard from '@/components/StatCard.vue'
import { getDashboardOverview } from '@/api/admin'
import type { DashboardOverview, SystemAlert } from '@/types'

// ==========================================================================
// 路由
// ==========================================================================
const router = useRouter()

// ==========================================================================
// 状态
// ==========================================================================

/** 仪表盘数据 */
const overview = reactive<DashboardOverview>({
  online_agents: 0,
  today_conversations: 0,
  avg_response_time: '—',
  ai_hit_rate: '—',
  pending_reviews: 0,
  system_alerts: [],
  integrations_health: [],
})

/** 加载状态 */
const loading = ref<boolean>(false)

// ==========================================================================
// 待处理事项（基于 system_alerts 构建）
// ==========================================================================
const pendingItems = ref<Array<{
  type: string
  tagType: string
  content: string
  submitter: string
  time: string
  actionText: string
  route: string
}>>([])

// ==========================================================================
// 系统健康状态
// ==========================================================================
const healthItems = ref<Array<{
  name: string
  statusType: string
  statusText: string
}>>([])

// ==========================================================================
// 初始化
// ==========================================================================
onMounted(async () => {
  loading.value = true
  try {
    const response = await getDashboardOverview()
    const data = response.data.data
    Object.assign(overview, data)

    // 构建待处理事项
    buildPendingItems(data.system_alerts || [])

    // 构建系统健康
    buildHealthItems(data.integrations_health || [])
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    // 使用默认 demo 数据
    overview.online_agents = 2
    overview.today_conversations = 47
    overview.avg_response_time = '1.8s'
    overview.ai_hit_rate = '68%'
    overview.pending_reviews = 3

    // Demo 待处理事项
    pendingItems.value = [
      { type: '快速回复', tagType: 'primary', content: 'VPN连接失败排查话术', submitter: '张伟', time: '10分钟前', actionText: '审核', route: '/quick-replies' },
      { type: '知识推荐', tagType: 'warning', content: '打印机脱机问题（同类18次）', submitter: '系统', time: '1小时前', actionText: '处理', route: '/dashboard' },
      { type: '异常告警', tagType: 'danger', content: '坐席王丽会话超时未响应', submitter: '系统', time: '2小时前', actionText: '查看', route: '/monitor' },
    ]

    // Demo 系统健康
    healthItems.value = [
      { name: 'Dify AI 引擎', statusType: 'success', statusText: '正常' },
      { name: 'RAGFlow 知识库', statusType: 'success', statusText: '正常' },
      { name: 'Redis 缓存', statusType: 'success', statusText: '正常' },
      { name: 'PostgreSQL', statusType: 'success', statusText: '正常' },
      { name: 'WebSocket 服务', statusType: 'warning', statusText: '2连接抖动' },
    ]
  } finally {
    loading.value = false
  }
})

// ==========================================================================
// 构建待处理事项
// ==========================================================================
function buildPendingItems(alerts: SystemAlert[]): void {
  pendingItems.value = alerts.map((alert) => ({
    type: alert.type,
    tagType: alert.severity === 'danger' ? 'danger' : alert.severity === 'warning' ? 'warning' : 'primary',
    content: alert.content,
    submitter: alert.submitter || '系统',
    time: alert.time,
    actionText: alert.severity === 'danger' ? '查看' : '处理',
    route: '/dashboard',
  }))
}

// ==========================================================================
// 构建系统健康
// ==========================================================================
function buildHealthItems(integrations: Array<{ system: string; status: string }>): void {
  const statusMap: Record<string, string> = {
    connected: 'success',
    partial: 'warning',
    disconnected: 'info',
    pending: 'info',
  }
  const textMap: Record<string, string> = {
    connected: '正常',
    partial: '部分异常',
    disconnected: '未连接',
    pending: '待确认',
  }
  healthItems.value = integrations.map((item) => ({
    name: item.system,
    statusType: statusMap[item.status] || 'info',
    statusText: textMap[item.status] || item.status,
  }))

  // 如果后端没有返回，添加默认项
  if (healthItems.value.length === 0) {
    healthItems.value = [
      { name: 'Dify AI 引擎', statusType: 'success', statusText: '正常' },
      { name: 'RAGFlow 知识库', statusType: 'success', statusText: '正常' },
      { name: 'Redis 缓存', statusType: 'success', statusText: '正常' },
      { name: 'PostgreSQL', statusType: 'success', statusText: '正常' },
      { name: 'WebSocket 服务', statusType: 'warning', statusText: '2连接抖动' },
    ]
  }
}

// ==========================================================================
// 待处理事项操作
// ==========================================================================
function handlePendingAction(row: { route: string }): void {
  router.push(row.route)
}
</script>

<style scoped>
/* 仪表盘页面 */
.dashboard-page {
  /* 样式使用全局 .stats-grid .two-column 等 */
}

/* 系统健康列表 */
.health-list {
  padding: 16px;
}

.health-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.health-item:last-child {
  margin-bottom: 0;
}

.health-name {
  font-size: 13px;
  color: var(--text-primary);
}
</style>

<style>
/* 仪表盘表格行悬停 */
.dashboard-table-row:hover td {
  background-color: var(--bg-tertiary) !important;
}
</style>
