<!-- =============================================================================
// 企微IT智能服务台 — 会话列表项组件（v5.4 头像+圆点+缩略头像）
// =============================================================================
// 说明：单个会话项的展示
// 包含：头像(渐变色) + 新消息圆点(3色) + 姓名 + 标签 + 优先级图标
//      + 最后消息摘要 + 紧急度星级 + 处理对象缩略头像
// 已结单会话名字变灰、半透明
// 置顶显示📌图标，代办显示📋图标
// ============================================================================= -->

<template>
  <div
    class="conversation-item"
    :class="{
      active: active,
      resolved: conversation.status === 'resolved',
      'other-agent': !conversation.is_mine && conversation.status === 'serving',
    }"
    @click="$emit('click')"
  >
    <!-- 头像（含新消息圆点） -->
    <div class="conv-avatar-wrap">
      <div class="conversation-avatar" :class="avatarColorClass">
        {{ avatarText }}
      </div>
      <!-- 新消息圆点：有新消息时显示，3色区分优先级 -->
      <span
        v-if="hasNewMessage"
        class="new-msg-dot"
        :class="newMsgDotClass"
        :title="newMsgDotTitle"
      ></span>
    </div>

    <!-- 信息区 -->
    <div class="conversation-info">
      <!-- 第一行：姓名 + 标签 + 优先级图标 -->
      <div class="conversation-name">
        <!-- 置顶图标 -->
        <span v-if="conversation.is_pinned" title="已置顶">📌</span>
        <!-- 代办图标 -->
        <span v-if="conversation.is_todo" title="代办">📋</span>
        <!-- 姓名 -->
        <span class="text-ellipsis">{{ conversation.employee_name || '未知' }}</span>
        <!-- VIP标签 -->
        <span v-if="conversation.is_vip" class="tag-badge tag-badge-vip">VIP</span>
        <!-- 招手标签 -->
        <span v-if="conversation.tags?.hand_raise" class="tag-badge tag-badge-hand-raise">招手</span>
        <!-- 需介入标签 -->
        <span v-if="conversation.tags?.need_intervene" class="tag-badge tag-badge-need-intervene">🔔需介入</span>
        <!-- 情绪标签 -->
        <span
          v-if="conversation.tags?.emotion && conversation.tags.emotion !== 'neutral'"
          class="tag-badge"
          :class="emotionBadgeClass"
        >
          {{ emotionLabel }}
        </span>
        <!-- 其他坐席姓名标签 -->
        <span
          v-if="conversation.assigned_agent_name && !conversation.is_mine && conversation.status === 'serving'"
          class="tag-badge tag-badge-agent"
        >
          {{ conversation.assigned_agent_name }}
        </span>
        <!-- 优先级图标组（右侧排列） -->
        <span class="priority-icons">
          <span
            v-for="pi in visiblePriorityIcons"
            :key="pi.key"
            class="priority-icon"
            :class="pi.cssClass"
            :title="pi.title"
            :style="{ backgroundColor: pi.bg }"
          >
            {{ pi.icon }}
          </span>
        </span>
      </div>

      <!-- 第二行：最后消息摘要 + 时间 -->
      <div class="conversation-summary-row">
        <span class="conversation-summary">{{ conversation.last_message_summary || '暂无消息' }}</span>
        <span class="conversation-time">{{ formatTime }}</span>
      </div>

      <!-- 第三行：紧急度 + 接手按钮 -->
      <div class="conversation-meta">
        <!-- 紧急度星级 -->
        <div class="urgency-stars">
          <span
            v-for="i in 5"
            :key="i"
            class="urgency-star"
            :class="{ empty: i > conversation.urgency_score }"
          >★</span>
        </div>
        <!-- 接手按钮（仅其他坐席的会话显示） -->
        <el-button
          v-if="showGrab && conversation.can_grab"
          type="primary"
          size="small"
          link
          class="grab-btn"
          @click.stop="$emit('grab')"
        >
          接手
        </el-button>
        <!-- 退出按钮（仅协作会话显示） -->
        <el-button
          v-if="showLeave"
          type="danger"
          size="small"
          link
          class="leave-btn"
          @click.stop="$emit('leave')"
        >
          退出
        </el-button>
      </div>
    </div>

    <!-- 处理对象缩略头像（右侧） -->
    <div
      v-if="showTargetAvatar"
      class="conv-target-avatar"
      :class="targetAvatarColorClass"
      :title="targetAvatarTitle"
    >
      {{ targetAvatarText }}
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { computed } from 'vue'
import type { Conversation } from '@/api/conversation'

// ============================================================================
// 优先级图标配置
// ============================================================================
interface PriorityIconDef {
  key: string
  icon: string
  cssClass: string
  bg: string
  highThreshold?: number
  title: string
}

const PRIORITY_ICONS: PriorityIconDef[] = [
  {
    key: 'is_blocking',
    icon: '⛔',
    cssClass: 'pi-blocked',
    bg: 'var(--color-danger)',
    title: '阻断性问题',
  },
  {
    key: 'impact_scope',
    icon: '👥',
    cssClass: 'pi-impact',
    bg: 'var(--color-warning)',
    highThreshold: 5,
    title: '影响范围广',
  },
  {
    key: 'role_level',
    icon: '⭐',
    cssClass: 'pi-role',
    bg: 'var(--purple)',
    title: '高角色等级',
  },
  {
    key: 'is_repeat',
    icon: '🔁',
    cssClass: 'pi-repeat',
    bg: 'var(--color-warning)',
    title: '重复问题',
  },
]

// ============================================================================
// 头像渐变色映射（根据姓名首字 hash 分配颜色）
// ============================================================================
const AVATAR_COLORS = ['av-blue', 'av-green', 'av-orange', 'av-purple', 'av-red', 'av-teal', 'av-pink'] as const
const TARGET_COLORS = ['ta-blue', 'ta-green', 'ta-orange', 'ta-purple', 'ta-red', 'ta-teal', 'ta-pink'] as const

/** 根据字符串计算颜色索引（稳定的 hash） */
function colorIndex(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) % AVATAR_COLORS.length
}

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

interface Props {
  /** 会话对象 */
  conversation: Conversation
  /** 是否为当前选中的会话 */
  active: boolean
  /** 是否显示接手按钮（其他坐席会话区传入 true） */
  showGrab?: boolean
  /** 是否显示退出按钮（协作会话区传入 true） */
  showLeave?: boolean
  /** 会话所属分区: my/colleague/history（影响缩略头像显示逻辑） */
  section?: string
}

const props = withDefaults(defineProps<Props>(), {
  showGrab: false,
  showLeave: false,
  section: 'my',
})

defineEmits<{
  click: []
  grab: []
  leave: []
}>()

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

/** 头像文字（取姓名最后一个字） */
const avatarText = computed(() => {
  const name = props.conversation.employee_name
  if (!name) return '?'
  return name.charAt(name.length - 1)
})

/** 头像渐变色 CSS 类 */
const avatarColorClass = computed(() => {
  const name = props.conversation.employee_name || 'unknown'
  return AVATAR_COLORS[colorIndex(name)]
})

/** 是否有新消息（基于未读数或状态判断） */
const hasNewMessage = computed(() => {
  // 排队中/招手/需介入 = 有新消息
  if (props.conversation.status === 'queued') return true
  if (props.conversation.tags?.hand_raise) return true
  if (props.conversation.tags?.need_intervene) return true
  // 已结单 = 无新消息
  if (props.conversation.status === 'resolved') return false
  // 其他活跃会话默认显示普通蓝色圆点
  return props.conversation.status === 'serving'
})

/** 新消息圆点 CSS 类（紧急红/普通蓝/低优灰） */
const newMsgDotClass = computed(() => {
  // 紧急情况（招手/阻断性/需介入/愤怒）= 红色
  if (
    props.conversation.tags?.hand_raise ||
    props.conversation.is_blocking ||
    props.conversation.tags?.need_intervene ||
    props.conversation.tags?.emotion === 'angry' ||
    props.conversation.tags?.emotion === 'urgent'
  ) {
    return 'dot-urgent'
  }
  // 已结单 = 无圆点
  if (props.conversation.status === 'resolved') return ''
  // 排队中 = 蓝色
  if (props.conversation.status === 'queued') return 'dot-normal'
  // 普通服务中 = 蓝色
  return 'dot-normal'
})

/** 圆点 hover 提示文字 */
const newMsgDotTitle = computed(() => {
  if (newMsgDotClass.value === 'dot-urgent') return '紧急新消息'
  if (newMsgDotClass.value === 'dot-normal') return '有新消息'
  return '新消息'
})

/** 是否显示右侧处理对象缩略头像 */
const showTargetAvatar = computed(() => {
  // 历史会话不显示缩略头像
  if (props.section === 'history') return false
  // 我的会话和同事会话都显示
  return true
})

/** 缩略头像文字 */
const targetAvatarText = computed(() => {
  if (props.section === 'colleague') {
    // 同事会话：显示坐席姓名最后字
    return props.conversation.assigned_agent_name
      ? props.conversation.assigned_agent_name.charAt(props.conversation.assigned_agent_name.length - 1)
      : '?'
  }
  // 我的会话：显示员工姓名最后字
  const name = props.conversation.employee_name
  return name ? name.charAt(name.length - 1) : '?'
})

/** 缩略头像颜色 */
const targetAvatarColorClass = computed(() => {
  if (props.section === 'colleague') {
    const name = props.conversation.assigned_agent_name || 'unknown'
    return TARGET_COLORS[colorIndex(name)]
  }
  const name = props.conversation.employee_name || 'unknown'
  return TARGET_COLORS[colorIndex(name)]
})

/** 缩略头像 hover 提示 */
const targetAvatarTitle = computed(() => {
  if (props.section === 'colleague') {
    return `坐席：${props.conversation.assigned_agent_name || '未知'}`
  }
  return props.conversation.employee_name || '未知'
})

/** 情绪标签的 CSS 类 */
const emotionBadgeClass = computed(() => {
  const emotion = props.conversation.tags?.emotion
  if (emotion === 'urgent') return 'tag-badge-emotion-urgent'
  if (emotion === 'angry') return 'tag-badge-emotion-angry'
  if (emotion === 'worried') return 'tag-badge-emotion-worried'
  return ''
})

/** 情绪标签文字 */
const emotionLabel = computed(() => {
  const emotionMap: Record<string, string> = {
    urgent: '🔴紧急',
    angry: '😡愤怒',
    worried: '😟担忧',
  }
  return emotionMap[props.conversation.tags?.emotion || ''] || ''
})

/** 格式化时间显示 */
const formatTime = computed(() => {
  const timeStr = props.conversation.last_message_at
  if (!timeStr) return ''

  const date = new Date(timeStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMin = Math.floor(diffMs / 60000)

  // 1分钟内：刚刚
  if (diffMin < 1) return '刚刚'
  // 1小时内：X分钟前
  if (diffMin < 60) return `${diffMin}分钟前`
  // 今天：显示时间 HH:mm
  if (date.toDateString() === now.toDateString()) {
    return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }
  // 昨天：昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) return '昨天'
  // 更早：MM/DD
  return `${date.getMonth() + 1}/${date.getDate()}`
})

/**
 * 可见的优先级图标列表
 * 根据会话属性动态计算哪些图标应该显示
 */
const visiblePriorityIcons = computed(() => {
  const result: Array<PriorityIconDef & { title: string }> = []
  const conv = props.conversation

  for (const def of PRIORITY_ICONS) {
    let visible = false
    let title = def.title

    switch (def.key) {
      case 'is_blocking':
        visible = !!conv.is_blocking
        break
      case 'impact_scope':
        // impact_scope >= highThreshold(5) 时显示
        visible = (conv.impact_scope || 0) >= (def.highThreshold || 5)
        if (visible) {
          title = `影响范围: ${conv.impact_scope}人`
        }
        break
      case 'role_level':
        // 高等级用户 (level 包含总监/VP/C* 等关键词) 时显示
        visible = isHighRoleLevel(conv)
        break
      case 'is_repeat':
        // 重复追问 (repeat_count >= 3) 时显示
        visible = (conv.tags?.repeat_count || 0) >= 3
        if (visible) {
          title = `重复追问: ${conv.tags.repeat_count}次`
        }
        break
    }

    if (visible) {
      result.push({ ...def, title })
    }
  }

  return result
})

/**
 * 判断是否为高角色等级
 * 基于员工 level 字段判断是否包含总监/VP/CXO 等高级别关键词
 */
function isHighRoleLevel(conv: Conversation): boolean {
  const highLevelKeywords = ['总监', 'VP', 'CIO', 'CTO', 'CFO', 'CEO', '总裁', '副总', '高级总监']
  const level = conv.level || ''
  return highLevelKeywords.some(kw => level.includes(kw))
}
</script>

<style scoped>
/* 其他坐席会话样式：稍微灰色 */
.conversation-item.other-agent {
  opacity: 0.8;
}

.conversation-item.other-agent .conversation-avatar {
  opacity: 0.8;
}

/* 摘要行（含时间和文本） */
.conversation-summary-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 2px;
}

.conversation-summary-row .conversation-summary {
  flex: 1;
  min-width: 0;
}

.conversation-summary-row .conversation-time {
  flex-shrink: 0;
  font-size: 10px;
  color: var(--text-placeholder);
}

/* 接手按钮样式 */
.grab-btn {
  font-size: 12px;
  padding: 0 4px;
  margin-left: auto;
  white-space: nowrap;
}

/* 退出按钮样式 */
.leave-btn {
  font-size: 12px;
  padding: 0 4px;
  margin-left: auto;
  white-space: nowrap;
}

/* 优先级图标组 */
.priority-icons {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  margin-left: auto;
  flex-shrink: 0;
}

/* 优先级图标 — 16×16px 圆角方块 */
.priority-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  border-radius: 3px;
  font-size: 8px;
  line-height: 1;
  flex-shrink: 0;
}

/* 阻断性图标闪烁提示 */
.priority-icon.pi-blocked {
  animation: pi-blink 2s ease-in-out infinite;
}

@keyframes pi-blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.6; }
}
</style>
