<!-- =============================================================================
// 企微IT智能服务台 — 会话列表组件（v5.4 无折叠版）
// =============================================================================
// 说明：坐席工作台左侧的会话列表
// 功能：
//   1. 顶部搜索栏 + 快捷筛选标签（全部/待处理/进行中/已完成）
//   2. 扁平会话列表：我的会话 → 同事会话 → 历史会话（无折叠，始终全部展开）
//   3. 底部挂载 TodoPanel
// ============================================================================= -->

<template>
  <div class="conversation-list-root">
    <!-- 搜索栏 -->
    <div class="sidebar-search">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户、关键词..."
        prefix-icon="Search"
        clearable
        size="default"
      />
      <!-- 快捷筛选标签 -->
      <div class="filter-tags">
        <span
          v-for="tag in filterTags"
          :key="tag.key"
          class="filter-tag"
          :class="{ active: activeFilter === tag.key }"
          @click="activeFilter = tag.key"
        >
          {{ tag.label }}
        </span>
      </div>
    </div>

    <!-- 会话列表滚动区（v5.4: 扁平列表，无分类折叠） -->
    <div class="conversation-list-scroll">
      <!-- 加载中 -->
      <div v-if="conversationStore.loadingConversations" class="loading-state">
        <el-icon class="is-loading" :size="20"><Loading /></el-icon>
        <div class="loading-text">加载中...</div>
      </div>

      <!-- 我的会话（始终展开） -->
      <ConversationItem
        v-for="conv in filteredMy"
        :key="conv.id"
        :conversation="conv"
        :active="conv.id === conversationStore.currentConversationId"
        :show-grab="conv.status === 'serving' && !conv.is_mine && !conv.is_collaborator"
        :show-leave="conv.is_collaborator && conv.status === 'serving'"
        section="my"
        @click="conversationStore.selectConversation(conv.id)"
        @grab="handleGrab(conv)"
        @leave="handleLeave(conv)"
      />

      <!-- 同事会话（始终展开） -->
      <ConversationItem
        v-for="conv in filteredColleague"
        :key="conv.id"
        :conversation="conv"
        :active="conv.id === conversationStore.currentConversationId"
        :show-grab="conv.status === 'serving' && !conv.is_mine"
        section="colleague"
        @click="conversationStore.selectConversation(conv.id)"
        @grab="handleGrab(conv)"
      />

      <!-- 历史会话（始终展开） -->
      <ConversationItem
        v-for="conv in filteredHistory"
        :key="conv.id"
        :conversation="conv"
        :active="conv.id === conversationStore.currentConversationId"
        section="history"
        @click="conversationStore.selectConversation(conv.id)"
      />

      <!-- 空状态 -->
      <div
        v-if="!conversationStore.loadingConversations && conversationStore.conversations.length === 0"
        class="empty-state"
      >
        <el-empty description="暂无会话" :image-size="80" />
      </div>
    </div>

    <!-- 底部待办面板 -->
    <TodoPanel />
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useConversationStore } from '@/stores/conversation'
import { useTodoStore } from '@/stores/todo'
import ConversationItem from './ConversationItem.vue'
import TodoPanel from './TodoPanel.vue'
import type { Conversation } from '@/api/conversation'

// ============================================================================
// 筛选标签定义
// ============================================================================
interface FilterTag {
  key: string
  label: string
}

const filterTags: FilterTag[] = [
  { key: 'all', label: '全部' },
  { key: 'pending', label: '待处理' },
  { key: 'active', label: '进行中' },
  { key: 'done', label: '已完成' },
]

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

/** 会话 Store */
const conversationStore = useConversationStore()

/** 待办 Store */
const todoStore = useTodoStore()

/** 搜索关键词 */
const searchKeyword = ref('')

/** 当前筛选标签 */
const activeFilter = ref<string>('all')

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

/**
 * 搜索 + 标签综合过滤函数
 * 同时匹配关键词和筛选标签条件
 */
function applyFilters(conversations: Conversation[]): Conversation[] {
  let result = conversations

  // 关键词过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    result = result.filter(conv =>
      conv.employee_name.toLowerCase().includes(keyword) ||
      conv.department.toLowerCase().includes(keyword) ||
      conv.last_message_summary.toLowerCase().includes(keyword)
    )
  }

  // 标签过滤
  if (activeFilter.value !== 'all') {
    result = result.filter(conv => {
      switch (activeFilter.value) {
        case 'pending':
          return conv.status === 'queued'
        case 'active':
          return conv.status === 'serving' || conv.status === 'ai_handling'
        case 'done':
          return conv.status === 'resolved'
        default:
          return true
      }
    })
  }

  return result
}

/** 我的会话（过滤后） */
const filteredMy = computed(() =>
  applyFilters(conversationStore.myConversations)
)

/** 同事会话（过滤后） */
const filteredColleague = computed(() =>
  applyFilters(conversationStore.colleagueConversations)
)

/** 历史会话（过滤后） */
const filteredHistory = computed(() =>
  applyFilters(conversationStore.historyConversations)
)

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

/**
 * 接手其他坐席的会话
 */
async function handleGrab(conv: Conversation): Promise<void> {
  const agentName = conv.assigned_agent_name || '其他坐席'
  try {
    await ElMessageBox.confirm(
      `确定要接手 ${agentName} 的会话吗？接手后该会话将归您处理。`,
      '接手确认',
      {
        confirmButtonText: '确认接手',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await conversationStore.grabConv(conv.id)
    ElMessage.success('接手成功')
  } catch (error: any) {
    if (error !== 'cancel' && error?.message) {
      ElMessage.error(error.message || '接手失败')
    }
  }
}

/**
 * 退出协作
 */
async function handleLeave(conv: Conversation): Promise<void> {
  const ownerName = conv.assigned_agent_name || '主责坐席'
  try {
    await ElMessageBox.confirm(
      `确定要退出 ${ownerName} 的协作会话吗？`,
      '退出确认',
      {
        confirmButtonText: '确认退出',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await conversationStore.leaveConvCollaboration(conv.id)
    ElMessage.success('已退出协作')
  } catch (error: any) {
    if (error !== 'cancel' && error?.message) {
      ElMessage.error(error.message || '退出失败')
    }
  }
}

// ============================================================================
// 生命周期
// ============================================================================
onMounted(() => {
  todoStore.fetchTodoList()
})
</script>

<style scoped>
/* 根容器 */
.conversation-list-root {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 加载状态 */
.loading-state {
  padding: 20px;
  text-align: center;
}
.loading-text {
  margin-top: 8px;
  color: var(--text-tertiary);
  font-size: 12px;
}

/* 空状态 */
.empty-state {
  padding: 40px 20px;
  text-align: center;
}

/* 快捷筛选标签 */
.filter-tags {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  flex-wrap: wrap;
}

.filter-tag {
  display: inline-flex;
  align-items: center;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  cursor: pointer;
  user-select: none;
  transition: all 0.2s;
  background-color: var(--bg-tertiary);
  color: var(--text-secondary);
  border: 1px solid transparent;
}

.filter-tag:hover {
  background-color: var(--bg-hover);
}

.filter-tag.active {
  background-color: var(--accent-soft);
  color: var(--accent);
  border-color: var(--accent);
}
</style>
