<!-- =============================================================================
// 企微IT智能服务台 — 用户信息栏组件
// =============================================================================
// 说明：替代 ChatArea.vue 中原有的顶部标题栏
// 功能：
//   1. 常驻区（收起状态）：头像+姓名+IT等级+chips+展开箭头
//   2. 展开详情区（6 卡片 3 列 grid）
//   3. 右侧操作按钮（转接/结单/摇人等）
// ============================================================================= -->

<template>
  <div class="user-info-bar">
    <!-- ================================================================== -->
    <!-- 常驻区：点击整行展开/收起 -->
    <!-- ================================================================== -->
    <div class="user-info-bar__persistent" @click="toggleExpand">
      <!-- 左侧：头像 + 姓名 + IT等级 + 箭头 -->
      <div class="user-info-bar__left">
        <!-- 头像 -->
        <div class="user-info-bar__avatar">
          {{ avatarText }}
        </div>

        <!-- 姓名·部门岗位 + IT 等级 -->
        <div class="user-info-bar__name-group">
          <span class="user-info-bar__name">{{ conversation?.employee_name || '未知' }}</span>
          <span
            v-if="conversation?.department || conversation?.position"
            class="user-info-bar__dept"
          >
            · {{ conversation?.department || '' }}{{ conversation?.position ? ' ' + conversation.position : '' }}
          </span>
          <ItLevelBadge :level="employeeItLevel" size="sm" />
        </div>

        <!-- 展开/收起箭头 -->
        <span class="user-info-bar__arrow" :class="{ 'is-expanded': isExpanded }">▶</span>
      </div>

      <!-- 中间：信息 chips -->
      <div class="user-info-bar__chips" @click.stop>
        <!-- 情绪状态 chip -->
        <span
          class="info-chip"
          :class="emotionChipClass"
        >
          😟 {{ emotionLabel }}
        </span>

        <!-- 等待时长 chip -->
        <span class="info-chip info-chip--gray">
          ⏱ {{ waitTimeLabel }}
        </span>

        <!-- 对话轮次 chip -->
        <span class="info-chip info-chip--gray">
          💬 {{ turnCount }}轮
        </span>

        <!-- IT等级 chip -->
        <span class="info-chip info-chip--accent">
          🖥 {{ levelName }} Lv.{{ levelNumber }}
        </span>

        <!-- 重复标记 chip（有重复时才显示） -->
        <span
          v-if="repeatCount > 0"
          class="info-chip info-chip--red"
        >
          🔁 重复×{{ repeatCount }}
        </span>

        <!-- 备注标记 chip（有备注时才显示） -->
        <span
          v-if="hasNotes"
          class="info-chip info-chip--purple"
        >
          📝 备注
        </span>
      </div>

      <!-- 右侧：操作按钮 -->
      <div class="user-info-bar__actions" @click.stop>
        <!-- 接单按钮 -->
        <el-button
          v-if="conversation?.status === 'queued'"
          type="success"
          size="small"
          @click="$emit('assign')"
        >
          <el-icon><Check /></el-icon>
          接单
        </el-button>

        <!-- 置顶/取消置顶 -->
        <el-button
          size="small"
          :type="conversation?.is_pinned ? 'warning' : 'default'"
          @click="$emit('toggle-pin')"
        >
          {{ conversation?.is_pinned ? '取消置顶' : '📌 置顶' }}
        </el-button>

        <!-- 代办/取消代办 -->
        <el-button
          size="small"
          :type="conversation?.is_todo ? 'warning' : 'default'"
          @click="$emit('toggle-todo')"
        >
          {{ conversation?.is_todo ? '取消代办' : '📋 代办' }}
        </el-button>

        <!-- 转接 -->
        <el-dropdown trigger="click" @command="(cmd: string) => $emit('transfer', cmd)">
          <el-button size="small" type="info">
            <el-icon><Sort /></el-icon>
            转接
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="agent in availableAgents"
                :key="agent.user_id"
                :command="agent.user_id"
              >
                {{ agent.name }} ({{ agent.current_load }}/{{ agent.max_load }})
              </el-dropdown-item>
              <el-dropdown-item v-if="availableAgents.length === 0" disabled>
                暂无可用坐席
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 摇人 -->
        <el-button
          v-if="canInviteCollaborator"
          size="small"
          type="primary"
          @click="$emit('invite')"
        >
          🤝 摇人
        </el-button>

        <!-- 结单 -->
        <el-button
          v-if="conversation?.status !== 'resolved'"
          type="danger"
          size="small"
          @click="$emit('resolve')"
        >
          <el-icon><CircleClose /></el-icon>
          结单
        </el-button>
      </div>
    </div>

    <!-- ================================================================== -->
    <!-- 展开详情区（6 卡片 3 列 grid） -->
    <!-- ================================================================== -->
    <div
      class="user-info-bar__detail"
      :class="{ 'is-expanded': isExpanded }"
    >
      <div class="user-info-bar__detail-inner">
        <!-- 卡片 1: 情绪状态 -->
        <div class="detail-card">
          <div class="detail-card__header">情绪状态</div>
          <div class="detail-card__body">
            <div class="detail-card__emotion">
              <span class="detail-card__emotion-emoji">{{ emotionEmoji }}</span>
              <span class="detail-card__emotion-text">{{ emotionLabel }}</span>
            </div>
            <div class="detail-card__desc">{{ emotionDesc }}</div>
          </div>
        </div>

        <!-- 卡片 2: 会话详情 -->
        <div class="detail-card">
          <div class="detail-card__header">会话详情</div>
          <div class="detail-card__body">
            <div class="detail-card__stat">
              <span class="detail-card__stat-icon">⏱</span>
              <span>等待时长：<strong>{{ waitTimeLabel }}</strong></span>
            </div>
            <div class="detail-card__stat">
              <span class="detail-card__stat-icon">💬</span>
              <span>对话轮次：<strong>{{ turnCount }} 轮</strong></span>
            </div>
          </div>
        </div>

        <!-- 卡片 3: 问题分析 -->
        <div class="detail-card">
          <div class="detail-card__header">问题分析</div>
          <div class="detail-card__body">
            <div class="detail-card__stat">
              <span class="detail-card__stat-icon">🔁</span>
              <span>{{ repeatCount > 0 ? '重复问题' : '非重复问题' }}</span>
            </div>
            <div class="detail-card__stat">
              <span>7天内反馈：<strong>{{ weekFeedbackCount }} 次</strong></span>
            </div>
          </div>
        </div>

        <!-- 卡片 4: IT技能等级 -->
        <div class="detail-card">
          <div class="detail-card__header">IT技能等级</div>
          <div class="detail-card__body">
            <div class="detail-card__level-row">
              <ItLevelBadge :level="employeeItLevel" size="md" />
              <span class="detail-card__level-name">{{ levelName }} Lv.{{ levelNumber }}</span>
              <el-button
                size="small"
                type="primary"
                link
                @click.stop="showItLevelSelector = !showItLevelSelector"
              >
                调整
              </el-button>
            </div>
            <div class="detail-card__level-desc">{{ levelDesc }}</div>

            <!-- IT 等级选择器下拉 -->
            <div
              v-if="showItLevelSelector"
              class="it-level-selector"
              @click.stop
            >
              <div
                v-for="(info, key) in IT_LEVEL_MAP"
                :key="key"
                class="it-level-selector__item"
                :class="{ 'is-active': employeeItLevel === key }"
                @click="handleItLevelChange(key)"
              >
                <ItLevelBadge :level="key" size="sm" />
                <span>{{ info.name }} Lv.{{ info.lv }}</span>
                <span v-if="employeeItLevel === key" class="it-level-selector__check">✓</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 卡片 5: 历史工单 -->
        <div class="detail-card">
          <div class="detail-card__header">历史工单</div>
          <div class="detail-card__body">
            <div class="detail-card__stat">
              <span>30天内工单：<strong>{{ monthlyTicketCount }}</strong></span>
            </div>
            <div class="detail-card__stat">
              <span>类型分布：{{ ticketTypeDistribution }}</span>
            </div>
          </div>
        </div>

        <!-- 卡片 6: 其他备注 -->
        <div class="detail-card">
          <div class="detail-card__header">其他备注</div>
          <div class="detail-card__body">
            <div v-if="notesText" class="detail-card__notes">
              {{ notesText }}
            </div>
            <div v-else class="detail-card__notes detail-card__notes--empty">
              暂无备注
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Sort, CircleClose } from '@element-plus/icons-vue'
import ItLevelBadge from './ItLevelBadge.vue'
import { updateEmployeeItLevel } from '@/api/troubleshooting'
import type { Conversation } from '@/api/conversation'

// ============================================================================
// Props & Emits
// ============================================================================

interface AgentInfo {
  user_id: string
  name: string
  current_load: number
  max_load: number
}

interface Props {
  /** 当前会话 */
  conversation: Conversation | null
  /** 可用坐席列表 */
  availableAgents: AgentInfo[]
  /** 是否可以摇人 */
  canInviteCollaborator: boolean
}

const props = withDefaults(defineProps<Props>(), {
  availableAgents: () => [],
  canInviteCollaborator: false,
})

interface Emits {
  (e: 'assign'): void
  (e: 'resolve'): void
  (e: 'toggle-pin'): void
  (e: 'toggle-todo'): void
  (e: 'transfer', agentId: string): void
  (e: 'invite'): void
}

// emit 已声明但未使用（保留以备将来扩展）
defineEmits<Emits>()

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

/** 是否展开详情 */
const isExpanded = ref(false)

/** 是否显示 IT 等级选择器 */
const showItLevelSelector = ref(false)

/** 员工 IT 等级（本地状态，可由坐席调整） */
const employeeItLevel = ref('silver')

/** 员工备注（本地 Mock） */
const employeeNotes = ref<Record<string, any>>({})

// ============================================================================
// 等级元数据
// ============================================================================

const IT_LEVEL_MAP: Record<string, { name: string; lv: number; desc: string }> = {
  bronze:   { name: '青铜', lv: 1, desc: 'IT基础薄弱，需要详细指导' },
  silver:   { name: '白银', lv: 2, desc: '能完成基本操作，需协助复杂问题' },
  gold:     { name: '黄金', lv: 3, desc: '熟悉常见操作，可独立解决一般问题' },
  platinum: { name: '铂金', lv: 4, desc: '熟练使用办公软件，能自助排查常见故障' },
  diamond:  { name: '钻石', lv: 5, desc: '具备一定技术能力，能理解技术解释' },
  star:     { name: '星耀', lv: 6, desc: 'IT能力较强，可自行解决大部分问题' },
  king:     { name: '王者', lv: 7, desc: 'IT达人级别，仅少数问题需协助' },
}

// ============================================================================
// 计算属性
// ============================================================================

/** 头像文字（取姓名前两个字） */
const avatarText = computed(() => {
  const name = props.conversation?.employee_name || '?'
  return name.slice(0, 2)
})

/** 情绪标签 */
const emotionLabel = computed(() => {
  const state = props.conversation?.emotion_state || 'normal'
  const map: Record<string, string> = {
    normal: '正常',
    worried: '担忧',
    angry: '愤怒',
    urgent: '紧急',
  }
  return map[state] || '正常'
})

/** 情绪 emoji */
const emotionEmoji = computed(() => {
  const state = props.conversation?.emotion_state || 'normal'
  const map: Record<string, string> = {
    normal: '😊',
    worried: '😟',
    angry: '😡',
    urgent: '🔴',
  }
  return map[state] || '😊'
})

/** 情绪描述 */
const emotionDesc = computed(() => {
  const state = props.conversation?.emotion_state || 'normal'
  const map: Record<string, string> = {
    normal: '情绪平稳，正常沟通',
    worried: '语气急促，连续追问进度',
    angry: '措辞激烈，多次表达不满',
    urgent: '问题严重影响工作，要求立即处理',
  }
  return map[state] || '情绪平稳'
})

/** 情绪 chip 样式 */
const emotionChipClass = computed(() => {
  const state = props.conversation?.emotion_state || 'normal'
  if (state === 'normal') return 'info-chip--gray'
  if (state === 'angry' || state === 'urgent') return 'info-chip--red'
  return 'info-chip--yellow'
})

/** 等待时长标签 */
const waitTimeLabel = computed(() => {
  // 从会话创建时间计算等待时长
  const createdAt = props.conversation?.created_at
  if (!createdAt) return '0分钟'
  const diffMs = Date.now() - new Date(createdAt).getTime()
  const diffMin = Math.floor(diffMs / 60000)
  if (diffMin < 60) return `${diffMin}分钟`
  const hours = Math.floor(diffMin / 60)
  const mins = diffMin % 60
  return `${hours}小时${mins}分钟`
})

/** 对话轮次（从消息数估算） */
const turnCount = computed(() => {
  const tags = props.conversation?.tags
  return (tags?.repeat_count || 0) + 1
})

/** 重复次数 */
const repeatCount = computed(() => {
  return props.conversation?.tags?.repeat_count || 0
})

/** 是否有备注 */
const hasNotes = computed(() => {
  return Object.keys(employeeNotes.value).length > 0
})

/** 备注文本 */
const notesText = computed(() => {
  const notes = employeeNotes.value
  const parts: string[] = []
  if (notes.pregnant) parts.push('孕妇')
  if (notes.disabled) parts.push('残疾/行动不便')
  if (notes.preference) parts.push(notes.preference)
  if (notes.custom) parts.push(notes.custom)
  return parts.join('；') || ''
})

/** 等级名称 */
const levelName = computed(() => {
  return IT_LEVEL_MAP[employeeItLevel.value]?.name || '白银'
})

/** 等级编号 */
const levelNumber = computed(() => {
  return IT_LEVEL_MAP[employeeItLevel.value]?.lv || 2
})

/** 等级描述 */
const levelDesc = computed(() => {
  return IT_LEVEL_MAP[employeeItLevel.value]?.desc || ''
})

/** 7天内反馈次数（Mock） */
const weekFeedbackCount = computed(() => {
  return props.conversation?.tags?.repeat_count || 0
})

/** 30天内工单数量（Mock） */
const monthlyTicketCount = computed(() => {
  return Math.floor(Math.random() * 5) + 1
})

/** 工单类型分布（Mock） */
const ticketTypeDistribution = computed(() => {
  return 'VPN 2次，邮箱 1次'
})

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

/**
 * 切换展开/收起
 */
function toggleExpand(): void {
  isExpanded.value = !isExpanded.value
  // 收起时关闭 IT 等级选择器
  if (!isExpanded.value) {
    showItLevelSelector.value = false
  }
}

/**
 * 调整 IT 等级
 *
 * @param level - 新等级
 */
async function handleItLevelChange(level: string): Promise<void> {
  const employeeId = props.conversation?.employee_id
  if (!employeeId) {
    ElMessage.warning('无法获取员工信息')
    return
  }

  try {
    await updateEmployeeItLevel(employeeId, level)
    employeeItLevel.value = level
    showItLevelSelector.value = false
    ElMessage.success(`IT 等级已调整为 ${IT_LEVEL_MAP[level]?.name || level}`)
  } catch (error) {
    console.error('更新 IT 等级失败:', error)
    // 降级：即使 API 失败也本地更新
    employeeItLevel.value = level
    showItLevelSelector.value = false
  }
}

// ============================================================================
// 监听会话切换
// ============================================================================

/** 当会话变化时重置状态 */
function resetForNewConversation(): void {
  isExpanded.value = false
  showItLevelSelector.value = false
  // 从 conversation 初始化 IT 等级
  if (props.conversation) {
    employeeItLevel.value = props.conversation.level || 'silver'
  }
}

// 暴露给父组件
defineExpose({ resetForNewConversation })
</script>

<style scoped>
/* 主容器 */
.user-info-bar {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

/* 常驻区 */
.user-info-bar__persistent {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  cursor: pointer;
  gap: 12px;
  transition: background 0.2s;
}

.user-info-bar__persistent:hover {
  background: var(--bg-hover);
}

/* 左侧区域 */
.user-info-bar__left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

/* 头像 */
.user-info-bar__avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: var(--bg-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 600;
  flex-shrink: 0;
}

/* 姓名组 */
.user-info-bar__name-group {
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-info-bar__name {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.user-info-bar__dept {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 展开箭头 */
.user-info-bar__arrow {
  font-size: 10px;
  color: var(--text-tertiary);
  transition: transform 0.35s ease;
  cursor: pointer;
}

.user-info-bar__arrow.is-expanded {
  transform: rotate(90deg);
}

/* 信息 chips */
.user-info-bar__chips {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  min-width: 0;
  overflow-x: auto;
}

/* chip 通用样式 */
.info-chip {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 11px;
  white-space: nowrap;
  flex-shrink: 0;
}

.info-chip--gray {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  border: 1px solid var(--border-light);
}

.info-chip--yellow {
  background: var(--warning-soft);
  color: var(--color-warning);
  border: 1px solid var(--warning-soft);
}

.info-chip--red {
  background: var(--danger-soft);
  color: var(--color-danger);
  border: 1px solid var(--danger-soft);
}

.info-chip--purple {
  background: var(--purple-soft);
  color: var(--purple);
  border: 1px solid var(--purple-soft);
}

.info-chip--accent {
  background: var(--bg-accent-soft);
  color: var(--accent);
  border: 1px solid var(--accent);
}

/* 右侧操作按钮 */
.user-info-bar__actions {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

/* 展开详情区 */
.user-info-bar__detail {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.35s ease;
}

.user-info-bar__detail.is-expanded {
  max-height: 600px;
}

.user-info-bar__detail-inner {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  padding: 12px 20px 16px;
}

/* 详情卡片 */
.detail-card {
  background: var(--bg-tertiary);
  border-radius: var(--radius-lg);
  padding: 14px 16px;
}

.detail-card__header {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.detail-card__body {
  font-size: 13px;
  color: var(--text-primary);
  line-height: 1.6;
}

/* 情绪展示 */
.detail-card__emotion {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}

.detail-card__emotion-emoji {
  font-size: 20px;
}

.detail-card__emotion-text {
  font-weight: 600;
}

.detail-card__desc {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 统计行 */
.detail-card__stat {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.detail-card__stat-icon {
  font-size: 14px;
}

/* 等级行 */
.detail-card__level-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.detail-card__level-name {
  font-weight: 600;
}

.detail-card__level-desc {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-bottom: 4px;
}

/* IT 等级选择器 */
.it-level-selector {
  margin-top: 8px;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-secondary);
  box-shadow: var(--shadow-md);
  max-height: 240px;
  overflow-y: auto;
}

.it-level-selector__item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 12px;
  color: var(--text-primary);
  transition: background 0.15s;
}

.it-level-selector__item:hover {
  background: var(--bg-hover);
}

.it-level-selector__item.is-active {
  background: var(--bg-accent-soft);
  color: var(--accent);
  font-weight: 600;
}

.it-level-selector__check {
  margin-left: auto;
  color: var(--accent);
}

/* 备注文本 */
.detail-card__notes {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.5;
  white-space: pre-line;
}

.detail-card__notes--empty {
  color: var(--text-placeholder);
  font-style: italic;
}

/* 响应式：小屏2列 */
@media (max-width: 1200px) {
  .user-info-bar__detail-inner {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
