<!--
=============================================================================
企微IT智能服务台 — 会话监控页
=============================================================================
说明：实时查看坐席工作状态、会话队列、异常告警
  阶段二功能，当前为 Demo 预览
  顶部统计卡片 + 实时会话表格
-->
<template>
  <div class="monitor-page">
    <!-- 页面标题 -->
    <div class="page-title">会话监控</div>
    <div class="page-desc">
      实时查看坐席工作状态、会话队列、异常告警。阶段二功能，当前为 Demo 预览。
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        label="进行中会话"
        :value="stats.in_progress"
        valueColor="var(--accent)"
        icon="ChatLineSquare"
        iconColor="var(--accent)"
      />
      <StatCard
        label="等待中"
        :value="stats.queued"
        valueColor="var(--warning)"
        icon="Clock"
        iconColor="var(--warning)"
      />
      <StatCard
        label="今日已结单"
        :value="stats.resolved_today"
        valueColor="var(--success)"
        icon="CircleCheckFilled"
        iconColor="var(--success)"
      />
      <StatCard
        label="异常告警"
        :value="stats.alerts"
        valueColor="var(--danger)"
        icon="WarningFilled"
        iconColor="var(--danger)"
      />
    </div>

    <!-- 实时会话表格 -->
    <div class="table-wrapper">
      <div class="table-header-row">
        <div class="table-title">实时会话</div>
        <el-tag type="primary" size="small">Demo 预览</el-tag>
      </div>
      <el-table
        :data="sessions"
        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="monitor-table-row"
        v-loading="loading"
        element-loading-text="正在加载会话数据..."
      >
        <el-table-column label="会话ID" width="80">
          <template #default="{ row }">
            <span class="session-id">{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工" min-width="160">
          <template #default="{ row }">
            <span>{{ row.employee_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="坐席" width="100">
          <template #default="{ row }">
            <span>{{ row.assigned_agent_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="持续时长" width="100">
          <template #default="{ row }">
            <span>{{ formatDuration(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="紧急度" width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.urgency_score || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getSessionStatusTag(row.status)" size="small">
              {{ getSessionStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
// ==========================================================================
// 依赖导入
// ==========================================================================
import { ref, reactive, onMounted } from 'vue'
import StatCard from '@/components/StatCard.vue'
import { getMonitorSessions } from '@/api/admin'
import type { MonitorSession, MonitorStats } from '@/types'

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

const stats = reactive<MonitorStats>({
  in_progress: 0,
  queued: 0,
  resolved_today: 0,
  alerts: 0,
})

const sessions = ref<MonitorSession[]>([])

// ==========================================================================
// 初始化
// ==========================================================================
onMounted(async () => {
  loading.value = true
  try {
    const response = await getMonitorSessions()
    const data = response.data.data
    Object.assign(stats, data.stats)
    sessions.value = data.items
  } catch {
    // 使用 Demo 数据
    stats.in_progress = 5
    stats.queued = 0
    stats.resolved_today = 42
    stats.alerts = 1

    sessions.value = [
      { id: '#C042', employee_name: '李明 (EMP101)', status: 'serving', assigned_agent_name: '宋献', urgency_score: 8, created_at: new Date(Date.now() - 5 * 60000).toISOString(), last_message_summary: '电脑无法开机' },
      { id: '#C041', employee_name: '赵刚 (EMP205)', status: 'serving', assigned_agent_name: '宋献', urgency_score: 14, created_at: new Date(Date.now() - 12 * 60000).toISOString(), last_message_summary: 'VPN连接失败' },
      { id: '#C040', employee_name: '孙芳 (EMP312)', status: 'timeout', assigned_agent_name: '王丽', urgency_score: 6, created_at: new Date(Date.now() - 8 * 60000).toISOString(), last_message_summary: '打印机脱机' },
      { id: '#C039', employee_name: '周磊 (EMP088)', status: 'serving', assigned_agent_name: '宋献', urgency_score: 4, created_at: new Date(Date.now() - 3 * 60000).toISOString(), last_message_summary: '邮箱登录失败' },
      { id: '#C038', employee_name: '吴婷 (EMP156)', status: 'ai_chatting', assigned_agent_name: 'AI 助手', urgency_score: 2, created_at: new Date(Date.now() - 1 * 60000).toISOString(), last_message_summary: '密码重置请求' },
    ]
  } finally {
    loading.value = false
  }
})

// ==========================================================================
// 辅助方法
// ==========================================================================

/** 格式化持续时长 */
function formatDuration(session: MonitorSession): string {
  try {
    const created = new Date(session.created_at).getTime()
    const now = Date.now()
    const diffMs = now - created
    const minutes = Math.floor(diffMs / 60000)
    const seconds = Math.floor((diffMs % 60000) / 1000)
    return `${minutes}分${seconds}秒`
  } catch {
    return '-'
  }
}

/** 会话状态标签类型 */
function getSessionStatusTag(status: string): string {
  switch (status) {
    case 'serving': return 'success'
    case 'timeout': return 'warning'
    case 'ai_chatting': return 'primary'
    case 'queued': return 'info'
    default: return 'info'
  }
}

/** 会话状态文本 */
function getSessionStatusText(status: string): string {
  switch (status) {
    case 'serving': return '进行中'
    case 'timeout': return '超时未响应'
    case 'ai_chatting': return 'AI 对话中'
    case 'queued': return '等待中'
    default: return status
  }
}
</script>

<style scoped>
/* 页面 */
.monitor-page {
  /* 样式使用全局 .stats-grid .table-wrapper 等 */
}

/* 会话ID */
.session-id {
  font-family: 'SF Mono', 'Fira Code', monospace;
  color: var(--accent);
}
</style>

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