<!-- =============================================================================
// 企微IT智能服务台 — 待办事项面板组件
// =============================================================================
// 说明：左栏底部挂载的待办面板
// 功能：
//   1. 显示待办列表（优先级圆点 + 文本 + 类型标签 + 时间）
//   2. 点击条目 → todoStore.selectTodoItem + workspaceView = 'task'
//   3. 底部显示坐席在线统计
// ============================================================================= -->

<template>
  <div class="todo-panel">
    <!-- 标题行 -->
    <div class="todo-header">
      <span class="todo-title">📋 待办事项</span>
      <span v-if="todoStore.urgentCount > 0" class="todo-urgent-badge">
        {{ todoStore.urgentCount }}
      </span>
    </div>

    <!-- 待办列表 -->
    <div class="todo-list">
      <div
        v-for="item in todoStore.pendingTodos"
        :key="item.id"
        class="todo-item"
        :class="{ 'todo-item-active': todoStore.currentTodoItem?.id === item.id }"
        @click="handleTodoClick(item)"
      >
        <!-- 优先级圆点 -->
        <span
          class="todo-priority-dot"
          :class="`priority-${item.priority}`"
        ></span>
        <!-- 文本 -->
        <span class="todo-text text-ellipsis">{{ item.title }}</span>
        <!-- 类型标签 -->
        <span class="todo-type-tag" :class="`type-${item.type}`">
          {{ typeLabel(item.type) }}
        </span>
        <!-- 时间 -->
        <span class="todo-time">{{ formatTodoTime(item.created_at) }}</span>
        <!-- v5.4: 上报人缩略头像 -->
        <div
          class="ki-avatar"
          :class="todoAvatarColor(item)"
          :title="todoAvatarTitle(item)"
        >
          {{ todoAvatarText(item) }}
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="todoStore.pendingTodos.length === 0 && !todoStore.loading" class="todo-empty">
        暂无待办
      </div>
    </div>

    <!-- 底部坐席在线统计 -->
    <div class="todo-footer">
      <span class="agent-stat">
        <span class="agent-dot dot-online"></span>
        <span>{{ onlineAgents }} 在线</span>
      </span>
      <span class="agent-stat">
        <span class="agent-dot dot-busy"></span>
        <span>{{ busyAgents }} 忙碌</span>
      </span>
      <span class="agent-stat">
        <span class="agent-dot dot-offline"></span>
        <span>{{ offlineAgents }} 离线</span>
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref } from 'vue'
import { useTodoStore } from '@/stores/todo'
import { useConversationStore } from '@/stores/conversation'
import { getAgentStats } from '@/mock/data'
import type { TodoItemData } from '@/api/todo'

// ============================================================================
// Store
// ============================================================================
const todoStore = useTodoStore()
const conversationStore = useConversationStore()

// ============================================================================
// 坐席在线统计（从 mock 数据计算，后续接入 agentStore 实时数据）
// ============================================================================
const stats = getAgentStats()
const onlineAgents = ref(stats.onlineAgents)
const busyAgents = ref(stats.busyAgents)
const offlineAgents = ref(stats.offlineAgents)

// ============================================================================
// 方法
// ============================================================================

/** 类型标签文字映射 */
function typeLabel(type: string): string {
  const map: Record<string, string> = {
    ticket: '工单',
    approval: '审批',
    device: '设备',
  }
  return map[type] || type
}

/** 格式化待办时间 */
function formatTodoTime(timeStr: string): string {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMin = Math.floor(diffMs / 60000)

  if (diffMin < 1) return '刚刚'
  if (diffMin < 60) return `${diffMin}分钟前`
  if (date.toDateString() === now.toDateString()) {
    return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }
  return `${date.getMonth() + 1}/${date.getDate()}`
}

/** 点击待办条目 */
function handleTodoClick(item: TodoItemData): void {
  todoStore.selectTodoItem(item)
  conversationStore.workspaceView = 'task'
}

// ============================================================================
// v5.4: 待办缩略头像辅助函数
// ============================================================================

const KI_COLORS = ['ka-blue', 'ka-green', 'ka-orange', 'ka-purple', 'ka-red'] as const

/** 根据标题 hash 分配头像颜色 */
function kiColorIndex(str: string): number {
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0
  }
  return Math.abs(hash) % KI_COLORS.length
}

/** 缩略头像文字（取标题中第一个中文或部门首字） */
function todoAvatarText(item: TodoItemData): string {
  const title = item.title || ''
  // 提取标题中" - "后面的部门名首字
  const dashIdx = title.indexOf(' - ')
  if (dashIdx >= 0) {
    const dept = title.substring(0, dashIdx).trim()
    return dept.charAt(dept.length - 1)
  }
  return title.charAt(0)
}

/** 缩略头像颜色 */
function todoAvatarColor(item: TodoItemData): string {
  return KI_COLORS[kiColorIndex(item.title || 'default')]
}

/** 缩略头像 hover 提示 */
function todoAvatarTitle(item: TodoItemData): string {
  const title = item.title || ''
  const dashIdx = title.indexOf(' - ')
  if (dashIdx >= 0) {
    return title.substring(0, dashIdx).trim()
  }
  return title
}
</script>

<style scoped>
/* 面板容器 */
.todo-panel {
  border-top: 1px solid var(--border-color);
  max-height: 220px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  background-color: var(--bg-secondary);
}

/* 标题行 */
.todo-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border-light);
  flex-shrink: 0;
}

.todo-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
}

.todo-urgent-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 16px;
  padding: 0 5px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 700;
  background-color: var(--color-danger);
  color: var(--bg-secondary);
}

/* 待办列表 */
.todo-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 待办条目 */
.todo-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.todo-item:hover {
  background-color: var(--bg-hover);
}

.todo-item-active {
  background-color: var(--bg-accent-soft);
}

/* 优先级圆点 */
.todo-priority-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
}

.todo-priority-dot.priority-urgent {
  background-color: var(--color-danger);
}

.todo-priority-dot.priority-high {
  background-color: var(--color-warning);
}

.todo-priority-dot.priority-normal {
  background-color: var(--text-placeholder);
}

/* 文本 */
.todo-text {
  flex: 1;
  font-size: 12px;
  color: var(--text-primary);
  min-width: 0;
}

/* 类型标签 */
.todo-type-tag {
  font-size: 9px;
  padding: 1px 5px;
  border-radius: 3px;
  line-height: 1.4;
  font-weight: 500;
  flex-shrink: 0;
  border: 1px solid;
}

/* 工单 — 蓝色 */
.todo-type-tag.type-ticket {
  color: var(--accent);
  background-color: var(--accent-soft);
  border-color: color-mix(in srgb, var(--accent) 30%, transparent);
}

/* 审批 — 紫色 */
.todo-type-tag.type-approval {
  color: var(--purple);
  background-color: var(--purple-soft);
  border-color: color-mix(in srgb, var(--purple) 30%, transparent);
}

/* 设备 — 橙色 */
.todo-type-tag.type-device {
  color: var(--color-warning);
  background-color: var(--warning-soft);
  border-color: color-mix(in srgb, var(--color-warning) 30%, transparent);
}

/* 时间 */
.todo-time {
  font-size: 10px;
  color: var(--text-placeholder);
  flex-shrink: 0;
  white-space: nowrap;
}

/* 空状态 */
.todo-empty {
  padding: 12px;
  text-align: center;
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 底部坐席统计 */
.todo-footer {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 6px 12px;
  border-top: 1px solid var(--border-light);
  flex-shrink: 0;
}

.agent-stat {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: var(--text-tertiary);
}

/* 状态圆点 */
.agent-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
}

.dot-online {
  background-color: var(--color-success);
}

.dot-busy {
  background-color: var(--color-warning);
}

.dot-offline {
  background-color: var(--text-placeholder);
}
</style>
