<!-- =============================================================================
// 企微IT智能服务台 — 用户信息面板组件
// =============================================================================
// 说明：显示当前会话员工的详细信息
// 功能：
//   1. 员工基本信息（部门/职位/机构）
//   2. VIP 标记
//   3. 历史咨询模式（如"近30天3次VPN问题"）
//   4. 坐席备注区（可添加/编辑/删除备注）
// ============================================================================= -->

<template>
  <div class="user-info-panel">
    <!-- 加载中 -->
    <div v-if="!conversation" class="empty-hint">
      请先选择一个会话
    </div>

    <template v-else>
      <!-- ================================================================ -->
      <!-- 员工基本信息 -->
      <!-- ================================================================ -->
      <div class="section-block">
        <div class="user-header">
          <!-- 头像 -->
          <div class="user-avatar">
            {{ conversation.employee_name?.charAt(conversation.employee_name.length - 1) || '?' }}
          </div>
          <div>
            <div class="user-name">
              {{ conversation.employee_name || '未知' }}
              <!-- VIP 标记 -->
              <el-tag v-if="conversation.is_vip" type="danger" size="small" effect="dark" style="margin-left: 4px;">
                VIP
              </el-tag>
            </div>
            <div class="user-id">
              {{ conversation.employee_id }}
            </div>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="info-card">
          <el-descriptions :column="1" size="small" border>
            <el-descriptions-item label="部门">
              {{ conversation.department || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="岗位">
              {{ conversation.position || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="等级">
              {{ conversation.level || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="紧急度">
              <div class="urgency-stars">
                <span
                  v-for="i in 5"
                  :key="i"
                  class="urgency-star"
                  :class="{ empty: i > conversation.urgency_score }"
                >★</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- ================================================================ -->
      <!-- 历史咨询模式 -->
      <!-- ================================================================ -->
      <div class="section-block">
        <div class="section-label">
          📊 历史咨询模式
        </div>
        <div class="info-card">
          <!-- 从 tags 中推断历史模式 -->
          <div v-if="conversation.tags?.repeat_count && conversation.tags.repeat_count > 0" style="margin-bottom: 4px;">
            <el-tag size="small" type="warning">🔄 追问 {{ conversation.tags.repeat_count }} 轮</el-tag>
          </div>
          <div v-if="conversation.tags?.emotion && conversation.tags.emotion !== 'neutral'" style="margin-bottom: 4px;">
            <el-tag size="small" type="danger">
              {{ emotionHistoryLabel }}
            </el-tag>
          </div>
          <div v-if="conversation.tags?.hand_raise" style="margin-bottom: 4px;">
            <el-tag size="small" type="warning">🙋 已要求转人工</el-tag>
          </div>
          <!-- 无特殊标记 -->
          <div
            v-if="(!conversation.tags?.repeat_count || conversation.tags.repeat_count === 0)
              && (!conversation.tags?.emotion || conversation.tags.emotion === 'neutral')
              && !conversation.tags?.hand_raise"
            class="no-tag-hint"
          >
            暂无特殊咨询模式标记
          </div>
        </div>
      </div>

      <!-- ================================================================ -->
      <!-- 坐席备注区 -->
      <!-- ================================================================ -->
      <div>
        <div class="note-header">
          <span class="section-label">📝 坐席备注</span>
          <el-button type="primary" size="small" text @click="showAddNote">
            <el-icon><Plus /></el-icon>
            添加
          </el-button>
        </div>

        <!-- 备注列表 -->
        <div v-if="notes.length > 0">
          <div
            v-for="note in notes"
            :key="note.id"
            class="note-item"
          >
            <!-- 备注内容 -->
            <div class="note-content">{{ note.content }}</div>
            <!-- 备注元信息 -->
            <div class="note-meta">
              <span class="note-time">{{ formatNoteTime(note.created_at) }}</span>
              <div style="display: flex; gap: 4px;">
                <el-button type="warning" size="small" text @click="showEditNote(note)">编辑</el-button>
                <el-button type="danger" size="small" text @click="handleDeleteNote(note)">删除</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 无备注 -->
        <div v-else class="empty-hint">暂无备注</div>
      </div>

      <!-- ================================================================ -->
      <!-- 添加/编辑备注弹窗 -->
      <!-- ================================================================ -->
      <el-dialog v-model="noteDialogVisible" :title="isEditingNote ? '编辑备注' : '添加备注'" width="400px">
        <el-input
          v-model="noteContent"
          type="textarea"
          :rows="4"
          placeholder="输入备注内容..."
        />
        <template #footer>
          <el-button @click="noteDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="noteSubmitting" @click="handleNoteSubmit">确定</el-button>
        </template>
      </el-dialog>
    </template>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useConversationStore } from '@/stores/conversation'
import { useAgentStore } from '@/stores/agent'
import {
  getAgentNotes,
  createAgentNote,
  updateAgentNote,
  deleteAgentNote,
} from '@/api/quickReply'
import type { AgentNote } from '@/api/quickReply'

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

const conversationStore = useConversationStore()
const agentStore = useAgentStore()

/** 当前会话 */
const conversation = computed(() => conversationStore.currentConversation)

/** 备注列表 */
const notes = ref<AgentNote[]>([])

/** 备注弹窗是否可见 */
const noteDialogVisible = ref(false)

/** 是否编辑模式 */
const isEditingNote = ref(false)

/** 正在编辑的备注ID */
const editingNoteId = ref('')

/** 备注内容 */
const noteContent = ref('')

/** 是否正在提交备注 */
const noteSubmitting = ref(false)

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

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

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

/**
 * 加载备注列表
 */
async function loadNotes(): Promise<void> {
  if (!conversation.value) return
  try {
    const data = await getAgentNotes(conversation.value.employee_id)
    notes.value = data.items
  } catch (error) {
    console.error('获取备注失败:', error)
  }
}

/**
 * 显示添加备注弹窗
 */
function showAddNote(): void {
  isEditingNote.value = false
  editingNoteId.value = ''
  noteContent.value = ''
  noteDialogVisible.value = true
}

/**
 * 显示编辑备注弹窗
 */
function showEditNote(note: AgentNote): void {
  isEditingNote.value = true
  editingNoteId.value = note.id
  noteContent.value = note.content
  noteDialogVisible.value = true
}

/**
 * 提交备注（新增或编辑）
 */
async function handleNoteSubmit(): Promise<void> {
  if (!noteContent.value.trim()) {
    ElMessage.warning('请输入备注内容')
    return
  }

  noteSubmitting.value = true
  try {
    if (isEditingNote.value) {
      // 编辑
      await updateAgentNote(editingNoteId.value, noteContent.value.trim())
      ElMessage.success('备注已更新')
    } else {
      // 新增
      if (!conversation.value) return
      await createAgentNote(
        conversation.value.id,
        agentStore.userId,
        noteContent.value.trim()
      )
      ElMessage.success('备注已添加')
    }
    noteDialogVisible.value = false
    // 重新加载备注
    await loadNotes()
  } catch (error) {
    console.error('保存备注失败:', error)
  } finally {
    noteSubmitting.value = false
  }
}

/**
 * 删除备注
 */
async function handleDeleteNote(note: AgentNote): Promise<void> {
  try {
    await ElMessageBox.confirm('确定要删除此备注吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteAgentNote(note.id)
    ElMessage.success('备注已删除')
    await loadNotes()
  } catch {
    // 用户取消
  }
}

/**
 * 格式化备注时间
 */
function formatNoteTime(timeStr: string): string {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}/${day} ${hours}:${minutes}`
}

// ============================================================================
// 监听
// ============================================================================

// 切换会话时重新加载备注
watch(
  () => conversationStore.currentConversationId,
  () => {
    loadNotes()
  },
  { immediate: true }
)
</script>

<style scoped>
/* 面板容器 */
.user-info-panel {
  padding: 12px;
}

/* 空提示文字 */
.empty-hint {
  text-align: center;
  padding: 12px 20px;
  color: var(--text-tertiary);
  font-size: 12px;
}

/* 区块间距 */
.section-block {
  margin-bottom: 16px;
}

/* 区块标题 */
.section-label {
  font-weight: 500;
  color: var(--text-primary);
  font-size: 13px;
  margin-bottom: 8px;
}

/* 用户头部：头像+名称 */
.user-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

/* 头像 */
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--accent);
  color: var(--bg-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  flex-shrink: 0;
}

/* 用户名 */
.user-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 15px;
}

/* 用户ID */
.user-id {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 信息卡片（浅色背景区块） */
.info-card {
  background-color: var(--bg-tertiary);
  border-radius: 6px;
  padding: 12px;
}

/* 无标记提示 */
.no-tag-hint {
  color: var(--text-tertiary);
  font-size: 12px;
}

/* 备注头部 */
.note-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

/* 备注条目 */
.note-item {
  padding: 8px 12px;
  margin-bottom: 6px;
  border-radius: 6px;
  background-color: var(--bg-tertiary);
  border-left: 3px solid var(--accent);
}

/* 备注内容 */
.note-content {
  font-size: 13px;
  color: var(--text-primary);
  line-height: 1.5;
}

/* 备注元信息 */
.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

/* 备注时间 */
.note-time {
  font-size: 11px;
  color: var(--text-placeholder);
}
</style>
