<!-- =============================================================================
// 企微IT智能服务台 — 坐席工作台主页面（v5.4 拖拽手柄版）
// =============================================================================
// 说明：坐席工作台主页面，三栏布局
// 左栏(280px)：会话列表
// 中栏(flex-1)：对话区
// 右栏(320px)：AI助手面板
// v5.4: 左右栏与中间栏之间添加拖拽手柄，可手动调整栏宽
// ============================================================================= -->

<template>
  <div class="workspace-layout" :data-theme="themeStore.currentTheme">
    <!-- ==================================================================== -->
    <!-- 顶栏组件（置顶） -->
    <!-- ==================================================================== -->
    <TopBar ref="topBarRef" @toggleAssistant="assistantVisible = !assistantVisible" />

    <!-- ==================================================================== -->
    <!-- 三栏区域（顶栏下方，横向排列 + 拖拽手柄） -->
    <!-- ==================================================================== -->
    <div class="workspace-body">
      <!-- 左栏：会话列表 -->
      <aside class="workspace-sidebar" ref="leftSidebarRef">
        <ConversationList />
      </aside>

      <!-- 拖拽手柄：左栏↔中间栏 -->
      <div
        class="resize-handle"
        :class="{ dragging: leftDragging }"
        @mousedown="startLeftResize"
      ></div>

      <!-- 中栏：对话区 / 任务详情视图 -->
      <main class="workspace-main">
        <!-- 聊天视图：当前选中会话且 workspaceView 为 chat -->
        <ChatArea v-if="conversationStore.workspaceView === 'chat' && conversationStore.currentConversation" />
        <!-- 任务详情视图：workspaceView 为 task 且有待办事项 -->
        <TaskDetailView v-else-if="conversationStore.workspaceView === 'task' && todoStore.currentTodoItem" :todo-item="todoStore.currentTodoItem" />
        <!-- 未选中会话时的占位 -->
        <div v-else class="empty-chat-area">
          <el-empty description="请从左侧选择一个会话开始服务" />
        </div>
      </main>

      <!-- 拖拽手柄：中间栏↔右栏 -->
      <div
        v-if="assistantVisible"
        class="resize-handle"
        :class="{ dragging: rightDragging }"
        @mousedown="startRightResize"
      ></div>

      <!-- 右栏：AI助手面板 -->
      <aside v-if="assistantVisible" class="workspace-assistant" ref="rightSidebarRef">
        <AiAssistantPanel />
      </aside>
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref, onMounted, onUnmounted } from 'vue'
import { useConversationStore } from '@/stores/conversation'
import { useAgentStore } from '@/stores/agent'
import { useQuickReplyStore } from '@/stores/quickReply'
import { useThemeStore } from '@/stores/theme'
import { useWebSocket } from '@/composables/useWebSocket'
import { useTheme } from '@/composables/useTheme'
import ConversationList from '@/components/conversation/ConversationList.vue'
import ChatArea from '@/components/chat/ChatArea.vue'
import TaskDetailView from '@/components/chat/TaskDetailView.vue'
import AiAssistantPanel from '@/components/assistant/AiAssistantPanel.vue'
import TopBar from '@/components/layout/TopBar.vue'
import { useTodoStore } from '@/stores/todo'

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

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

/** 坐席 Store */
const agentStore = useAgentStore()

/** 快速回复 Store */
const quickReplyStore = useQuickReplyStore()

/** 主题 Store */
const themeStore = useThemeStore()

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

/** 初始化主题（立即应用已保存的主题） */
useTheme()

/** WebSocket 组合式函数（自动连接 + 断线重连 + 心跳 + 降级） */
const { connect: connectWs, disconnect: disconnectWs } = useWebSocket()

/** TopBar 组件引用 */
const topBarRef = ref<InstanceType<typeof TopBar> | null>(null)

/** 助手面板是否可见（默认可见） */
const assistantVisible = ref(true)

// ===== 拖拽手柄状态 =====
const leftSidebarRef = ref<HTMLElement | null>(null)
const rightSidebarRef = ref<HTMLElement | null>(null)
const leftDragging = ref(false)
const rightDragging = ref(false)

let leftStartX = 0
let leftStartWidth = 0
let rightStartX = 0
let rightStartWidth = 0

// ============================================================================
// 拖拽手柄方法
// ============================================================================

/** 开始左栏拖拽 */
function startLeftResize(e: MouseEvent): void {
  e.preventDefault()
  if (!leftSidebarRef.value) return
  leftDragging.value = true
  leftStartX = e.clientX
  leftStartWidth = leftSidebarRef.value.offsetWidth
  document.addEventListener('mousemove', onLeftResizeMove)
  document.addEventListener('mouseup', onLeftResizeEnd)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

function onLeftResizeMove(e: MouseEvent): void {
  if (!leftDragging.value || !leftSidebarRef.value) return
  const dx = e.clientX - leftStartX
  const newW = Math.max(200, Math.min(500, leftStartWidth + dx))
  leftSidebarRef.value.style.width = newW + 'px'
  leftSidebarRef.value.style.minWidth = newW + 'px'
}

function onLeftResizeEnd(): void {
  leftDragging.value = false
  document.removeEventListener('mousemove', onLeftResizeMove)
  document.removeEventListener('mouseup', onLeftResizeEnd)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

/** 开始右栏拖拽 */
function startRightResize(e: MouseEvent): void {
  e.preventDefault()
  if (!rightSidebarRef.value) return
  rightDragging.value = true
  rightStartX = e.clientX
  rightStartWidth = rightSidebarRef.value.offsetWidth
  document.addEventListener('mousemove', onRightResizeMove)
  document.addEventListener('mouseup', onRightResizeEnd)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

function onRightResizeMove(e: MouseEvent): void {
  if (!rightDragging.value || !rightSidebarRef.value) return
  const dx = rightStartX - e.clientX
  const newW = Math.max(220, Math.min(500, rightStartWidth + dx))
  rightSidebarRef.value.style.width = newW + 'px'
  rightSidebarRef.value.style.minWidth = newW + 'px'
}

function onRightResizeEnd(): void {
  rightDragging.value = false
  document.removeEventListener('mousemove', onRightResizeMove)
  document.removeEventListener('mouseup', onRightResizeEnd)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

// ============================================================================
// 生命周期
// ============================================================================

onMounted(async () => {
  // 初始化主题
  themeStore.initTheme()
  // 初始化坐席信息
  await agentStore.initAuth()
  // 加载快速回复模板
  await quickReplyStore.fetchTemplates()
  // 加载会话列表（DEV 环境下有 Mock 数据兜底）
  await conversationStore.fetchConversations()
  // 自动选中第一个会话（如果没有已选中的会话）
  if (conversationStore.conversations.length > 0 && !conversationStore.currentConversationId) {
    await conversationStore.selectConversation(conversationStore.conversations[0].id)
  }
  // 连接 WebSocket 接收实时更新
  connectWs()
})

onUnmounted(() => {
  // 断开 WebSocket
  disconnectWs()
  // 停止轮询（作为兜底）
  conversationStore.stopAllPolling()
  // 清理拖拽事件
  document.removeEventListener('mousemove', onLeftResizeMove)
  document.removeEventListener('mouseup', onLeftResizeEnd)
  document.removeEventListener('mousemove', onRightResizeMove)
  document.removeEventListener('mouseup', onRightResizeEnd)
})
</script>

<style scoped>
/* 空对话区占位 */
.empty-chat-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
