<template>
  <!-- ================================================================== -->
  <!-- 坐席绩效统计页面 — 按坐席维度展示服务数据                            -->
  <!-- ================================================================== -->
  <div class="agent-performance">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 280px"
        @change="loadPerformance"
      />
      <el-button type="primary" :icon="Refresh" @click="loadPerformance">刷新</el-button>
    </div>

    <!-- 绩效表格 -->
    <el-table :data="agents" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="name" label="坐席姓名" width="120" />
      <el-table-column prop="status" label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)" size="small">
            {{ statusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="80">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'info'" size="small">
            {{ row.role === 'admin' ? '组长' : '坐席' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="skill_tags" label="技能标签" min-width="150">
        <template #default="{ row }">
          <el-tag v-for="tag in (row.skill_tags || [])" :key="tag" size="small" class="skill-tag">
            {{ tag }}
          </el-tag>
          <span v-if="!row.skill_tags?.length" style="color: #909399">—</span>
        </template>
      </el-table-column>
      <el-table-column prop="current_load" label="当前负载" width="90" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.current_load >= row.max_load ? '#f56c6c' : '#303133' }">
            {{ row.current_load }}/{{ row.max_load }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="total_conversations" label="总会话数" width="100" align="center" sortable />
      <el-table-column prop="resolved_conversations" label="已结单" width="90" align="center" sortable />
      <el-table-column prop="resolution_rate" label="结单率" width="90" align="center">
        <template #default="{ row }">
          <span :style="{ color: rateColor(row.resolution_rate) }">
            {{ row.resolution_rate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="today_conversations" label="今日会话" width="100" align="center" sortable />
    </el-table>

    <!-- 汇总统计 -->
    <div class="summary-bar">
      <el-descriptions :column="4" border size="small">
        <el-descriptions-item label="坐席总数">{{ agents.length }}</el-descriptions-item>
        <el-descriptions-item label="在线坐席">{{ agents.filter(a => a.status === 'online').length }}</el-descriptions-item>
        <el-descriptions-item label="总会话数">{{ totalConversations }}</el-descriptions-item>
        <el-descriptions-item label="总结单数">{{ totalResolved }}</el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script setup lang="ts">
// =============================================================================
// 坐席绩效统计页面逻辑
// =============================================================================
import { ref, computed, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { getAgentPerformance } from '@/api/admin'
import { ElMessage } from 'element-plus'

// ---------- 状态 ----------
const loading = ref(false)
const agents = ref<any[]>([])
const dateRange = ref<[string, string] | null>(null)

// ---------- 计算属性 ----------
const totalConversations = computed(() =>
  agents.value.reduce((sum, a) => sum + (a.total_conversations || 0), 0)
)
const totalResolved = computed(() =>
  agents.value.reduce((sum, a) => sum + (a.resolved_conversations || 0), 0)
)

// ---------- 数据加载 ----------
async function loadPerformance() {
  loading.value = true
  try {
    const params: any = {}
    if (dateRange.value) {
      params.date_from = dateRange.value[0]
      params.date_to = dateRange.value[1]
    }

    const { data } = await getAgentPerformance(params)
    if (data.code === 0) {
      agents.value = data.data.items || []
    }
  } catch (err: any) {
    ElMessage.error('加载绩效数据失败')
  } finally {
    loading.value = false
  }
}

// ---------- 工具函数 ----------
function statusTagType(status: string): '' | 'success' | 'warning' | 'info' | 'danger' {
  const map: Record<string, '' | 'success' | 'warning' | 'info' | 'danger'> = {
    online: 'success',
    busy: 'warning',
    offline: 'info',
  }
  return map[status] || 'info'
}

function statusLabel(status: string): string {
  const map: Record<string, string> = {
    online: '在线',
    busy: '忙碌',
    offline: '离线',
  }
  return map[status] || status
}

function rateColor(rate: string): string {
  if (rate === '—') return '#909399'
  const num = parseInt(rate)
  if (num >= 80) return '#67c23a'
  if (num >= 50) return '#e6a23c'
  return '#f56c6c'
}

// ---------- 生命周期 ----------
onMounted(() => loadPerformance())
</script>

<style scoped>
.agent-performance {
  padding: 0;
}

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.skill-tag {
  margin-right: 4px;
  margin-bottom: 2px;
}

.summary-bar {
  margin-top: 20px;
}
</style>
