<template>
  <div class="chat-course-container">
    <div class="content-wrapper">
      <div class="chat-header">
        <el-button link @click="goBack">
          <el-icon :size="20"><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-info">
          <h2 class="course-title">{{ courseInfo.title }}</h2>
          <span class="powered-by">
            <el-icon><Connection /></el-icon>
            智能对话助手
          </span>
        </div>
        <el-button link @click="clearChat">
          <el-icon><Delete /></el-icon>
          清空对话
        </el-button>
      </div>

      <div class="chat-main">
      <!-- 对话区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div class="welcome-message" v-if="messages.length === 0">
          <el-icon :size="48" color="#667eea"><ChatDotRound /></el-icon>
          <h3>与课程智能对话</h3>
          <p>我已经加载了《{{ courseInfo.title }}》的全部知识内容</p>
          <p>您可以问我任何关于这门课程的问题</p>
          
          <div class="quick-questions">
            <h4>快速提问：</h4>
            <div class="question-chips">
              <el-tag 
                v-for="question in quickQuestions" 
                :key="question"
                @click="askQuestion(question)"
                effect="plain"
                class="question-chip"
              >
                {{ question }}
              </el-tag>
            </div>
          </div>
        </div>

        <div 
          v-for="(message, index) in messages" 
          :key="index"
          class="message-item"
          :class="message.role"
        >
          <div class="message-avatar">
            <el-avatar :size="36">
              {{ message.role === 'user' ? 'ME' : 'AI' }}
            </el-avatar>
          </div>
          
          <div class="message-content">
            <div 
              class="message-text" 
              v-if="!message.loading"
              v-html="message.role === 'assistant' ? renderMarkdown(message.content) : escapeHtml(message.content)"
            ></div>
            <div class="message-loading" v-else>
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
            
            <div class="message-actions" v-if="message.role === 'assistant'">
              <el-button link size="small" @click="copyMessage(message.content)">
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
              <el-button link size="small" @click="likeMessage(index)">
                <el-icon><component :is="message.liked ? 'StarFilled' : 'Star'" /></el-icon>
                {{ message.liked ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-wrapper">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            placeholder="输入您的问题..."
            @keydown.enter="handleEnterKey"
            :disabled="isLoading"
          />
          <el-button 
            type="primary" 
            circle
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
            @click="sendMessage"
          >
            <el-icon v-if="!isLoading"><Promotion /></el-icon>
          </el-button>
        </div>
        <div class="input-tips">
          <span>按 Enter 发送，Shift + Enter 换行</span>
          <span>已加载课程知识库</span>
        </div>
      </div>
      </div>
    </div>

    <!-- 侧边栏 -->
    <div class="chat-sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-toggle" @click="toggleSidebar">
        <el-icon><component :is="sidebarCollapsed ? 'Expand' : 'Fold'" /></el-icon>
      </div>
      
      <div class="sidebar-content" v-show="!sidebarCollapsed">
        <div class="history-section">
          <h3 class="section-title">
            <span>对话历史</span>
            <el-button link size="small" @click="loadConversations" :loading="loadingConversations">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </h3>
          <div class="history-list" v-loading="loadingConversations">
            <div 
              v-if="conversations.length === 0 && !loadingConversations"
              class="empty-history"
            >
              <el-empty description="暂无历史对话" :image-size="60" />
            </div>
            <div 
              v-else
              class="history-item" 
              v-for="item in conversations" 
              :key="item.id"
              :class="{ active: item.id === conversationId }"
              @click="loadConversationMessages(item)"
            >
              <div class="history-title">{{ item.name || '未命名对话' }}</div>
              <div class="history-time">{{ formatTimestamp(item.updated_at) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { courseChatApi, type CourseChatEvent } from '@/api/courseChat'
import { getCourseDetail } from '@/api/trainee'

const router = useRouter()
const route = useRoute()

// 课程信息
const courseInfo = ref({
  title: '加载中...',
  id: route.query.courseId as string || '1'
})

// Dify 会话 ID（由前端管理，每次进入页面重新创建）
const conversationId = ref<string>('')
// const abortController = ref<AbortController | null>(null) // Unused

// 历史对话相关
const conversations = ref<any[]>([])
const loadingConversations = ref(false)

// 快速提问
const quickQuestions = ref([
  '这门课程的核心内容是什么？',
  '如何提升客户沟通技巧？',
  '处理客户异议的最佳方法是什么？',
  '成功销售的关键要素有哪些？'
])

// 消息列表
const messages = ref<any[]>([])

// 输入消息
const inputMessage = ref('')

// 加载状态
const isLoading = ref(false)

// 侧边栏状态
const sidebarCollapsed = ref(false)

// 消息容器引用
const messagesContainer = ref<HTMLElement>()

/**
 * Markdown 渲染
 */
const renderMarkdown = (content: string): string => {
  try {
    const html = marked(content) as string
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Markdown 渲染失败:', error)
    return escapeHtml(content)
  }
}

/**
 * HTML 转义（用户消息）
 */
const escapeHtml = (text: string): string => {
  const div = document.createElement('div')
  div.textContent = text
  return div.innerHTML
}

/**
 * 格式化时间戳
 */
const formatTimestamp = (timestamp: number): string => {
  const date = new Date(timestamp * 1000)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 小于7天
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  
  // 显示完整日期
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 返回
 */
const goBack = () => {
  router.back()
}

/**
 * 清空对话
 */
const clearChat = () => {
  messages.value = []
  conversationId.value = ''  // 清空会话ID，下次发送消息会创建新会话
  ElMessage.success('对话已清空')
}

/**
 * 快速提问
 */
const askQuestion = (question: string) => {
  inputMessage.value = question
  sendMessage()
}

/**
 * 处理回车键
 */
const handleEnterKey = (event: KeyboardEvent) => {
  // Shift + Enter：换行（默认行为）
  if (event.shiftKey) {
    return
  }
  
  // Enter：发送消息
  event.preventDefault()
  if (inputMessage.value.trim() && !isLoading.value) {
    sendMessage()
  }
}

/**
 * 发送消息
 */
const sendMessage = async () => {
  const content = inputMessage.value.trim()
  if (!content) return

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content,
    timestamp: new Date()
  })

  // 清空输入
  inputMessage.value = ''

  // 添加AI加载消息
  const aiMessageIndex = messages.value.length
  messages.value.push({
    role: 'assistant',
    content: '',
    loading: true,
    timestamp: new Date()
  })

  // 滚动到底部
  await scrollToBottom()

  // 调用Dify API发送消息
  isLoading.value = true
  
  try {
    // 调用 Dify 对话流 API
    const stream = await courseChatApi.sendMessage({
      course_id: parseInt(courseInfo.value.id),
      query: content,
      conversation_id: conversationId.value || undefined
    })

    const reader = stream.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        break
      }

      // 解码并处理 SSE 数据
      buffer += decoder.decode(value, { stream: true })
      
      // 按行分割
      const lines = buffer.split('\n')
      buffer = lines.pop() || '' // 保留最后一个不完整的行
      
      for (const line of lines) {
        if (!line.trim() || !line.startsWith('data: ')) {
          continue
        }

        try {
          const data = JSON.parse(line.slice(6)) as CourseChatEvent
          
          // 处理不同的事件类型
          switch (data.event) {
            case 'conversation_started':
              // 保存 conversation_id 用于后续对话
              if (data.conversation_id) {
                conversationId.value = data.conversation_id
                console.log('会话已创建:', data.conversation_id)
              }
              break
            
            case 'message_chunk':
              // 逐字显示（打字机效果）
              if (data.chunk) {
                // 移除 loading 状态
                messages.value[aiMessageIndex].loading = false
                // 追加文本块
                messages.value[aiMessageIndex].content += data.chunk
                await scrollToBottom()
              }
              break
            
            case 'message_end':
              // 消息结束
              isLoading.value = false
              messages.value[aiMessageIndex].loading = false
              console.log('消息接收完成')
              break
            
            case 'error':
              // 错误处理
              throw new Error(data.message || '发送消息失败')
          }
        } catch (parseError) {
          console.warn('解析 SSE 事件失败:', parseError, line)
        }
      }
    }
  } catch (error: any) {
    isLoading.value = false
    messages.value[aiMessageIndex] = {
      role: 'assistant',
      content: '抱歉，发送消息时出现错误。请稍后重试。',
      loading: false,
      timestamp: new Date(),
      liked: false,
      isError: true
    }
    ElMessage.error(error.message || '发送消息失败')
    console.error('发送消息错误:', error)
  }
}


/**
 * 复制消息
 */
const copyMessage = (content: string) => {
  navigator.clipboard.writeText(content)
  ElMessage.success('已复制到剪贴板')
}

/**
 * 收藏消息
 */
const likeMessage = (index: number) => {
  messages.value[index].liked = !messages.value[index].liked
  ElMessage.success(messages.value[index].liked ? '已收藏' : '取消收藏')
}

/**
 * 切换侧边栏
 */
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

/**
 * 加载历史对话列表
 */
const loadConversations = async () => {
  try {
    loadingConversations.value = true
    const data = await courseChatApi.getConversations()
    conversations.value = data
    console.log('历史对话列表已加载:', conversations.value.length)
  } catch (error: any) {
    console.error('加载历史对话失败:', error)
    ElMessage.error('加载历史对话失败：' + (error.message || '未知错误'))
  } finally {
    loadingConversations.value = false
  }
}

/**
 * 加载历史对话消息
 */
const loadConversationMessages = async (conversation: any) => {
  try {
    console.log('载入对话:', conversation.name, conversation.id)
    
    // 加载消息
    const data = await courseChatApi.getMessages(conversation.id)
    
    // 清空当前消息
    messages.value = []
    
    // 转换并显示历史消息
    data.forEach((msg: any) => {
      // 用户消息
      messages.value.push({
        role: 'user',
        content: msg.query,
        timestamp: new Date(msg.created_at * 1000)
      })
      
      // AI 回复
      messages.value.push({
        role: 'assistant',
        content: msg.answer,
        timestamp: new Date(msg.created_at * 1000),
        liked: false
      })
    })
    
    // 设置当前 conversation_id
    conversationId.value = conversation.id
    
    // 滚动到底部
    await scrollToBottom()
    
    ElMessage.success(`已载入对话：${conversation.name || '未命名对话'}`)
  } catch (error: any) {
    console.error('载入对话消息失败:', error)
    ElMessage.error('载入对话失败：' + (error.message || '未知错误'))
  }
}

/**
 * 滚动到底部
 */
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 加载课程详情
const loadCourseInfo = async () => {
  try {
    const courseId = parseInt(courseInfo.value.id)
    if (isNaN(courseId) || courseId <= 0) {
      console.warn('无效的课程ID:', courseInfo.value.id)
      courseInfo.value.title = '未知课程'
      return
    }
    const res: any = await getCourseDetail(courseId)
    console.log('课程详情API响应:', res)
    
    // 兼容不同的响应格式
    // 格式1: { code: 200, data: { name: "...", ... } }
    // 格式2: 直接返回课程对象 { name: "...", ... }
    let courseData = res
    if (res.code !== undefined && res.data) {
      // 标准响应格式
      if (res.code === 200) {
        courseData = res.data
      } else {
        console.warn('获取课程详情失败:', res.message || '未知错误')
        courseInfo.value.title = '未知课程'
        return
      }
    }
    
    // 从课程数据中提取名称
    const courseName = courseData?.title || courseData?.name
    if (courseName) {
      courseInfo.value.title = courseName
      console.log('课程详情已加载:', courseInfo.value.title)
    } else {
      console.warn('课程数据中缺少名称字段:', courseData)
      courseInfo.value.title = '未命名课程'
    }
  } catch (error: any) {
    console.error('加载课程详情失败:', error)
    courseInfo.value.title = '未知课程'
  }
}

// 初始化
onMounted(async () => {
  console.log('与课程对话页面已加载，course_id:', courseInfo.value.id)
  
  // 并行加载课程详情和历史对话，减少等待时间
  await Promise.all([
    loadCourseInfo(),
    loadConversations()
  ])
  
  // Dify 会话由第一次发送消息时自动创建
})

// 清理
onUnmounted(() => {
  // 清理工作（如需要）
  conversationId.value = ''
})
</script>

<style lang="scss" scoped>
.chat-course-container {
  height: 100%;
  display: flex;
  flex-direction: row;
  background: #f5f7fa;
  overflow: hidden;

  // 主内容区域包装器
  > .content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0;
    min-width: 0;
  }

  .chat-header {
    flex-shrink: 0;
    height: 60px;
    background: white;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    z-index: 10;

    .header-info {
      text-align: center;

      .course-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .powered-by {
        font-size: 12px;
        color: #909399;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0;

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 24px;
      min-height: 0;
      height: 100%;

      .welcome-message {
        text-align: center;
        padding: 24px;
        max-width: 800px;
        margin: 0 auto;

        h3 {
          font-size: 20px;
          font-weight: 600;
          color: #333;
          margin: 12px 0 8px;
        }

        p {
          font-size: 14px;
          color: #666;
          margin-bottom: 4px;
        }

        .quick-questions {
          margin-top: 20px;

          h4 {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 16px;
          }

          .question-chips {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 12px;

            .question-chip {
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                color: #667eea;
                border-color: #667eea;
                transform: translateY(-2px);
              }
            }
          }
        }
      }

      .message-item {
        display: flex;
        gap: 12px;
        margin-bottom: 24px;

        &.assistant {
          .message-content {
            background: white;
            border: 1px solid #ebeef5;
          }
        }

        &.user {
          flex-direction: row-reverse;

          .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
          }
        }

        .message-avatar {
          flex-shrink: 0;
        }

        .message-content {
          max-width: 70%;
          padding: 12px 16px;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

          .message-text {
            font-size: 15px;
            line-height: 1.6;
            white-space: pre-wrap;
            
            // Markdown 样式
            :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
              margin-top: 16px;
              margin-bottom: 8px;
              font-weight: 600;
            }
            
            :deep(h1) { font-size: 1.5em; }
            :deep(h2) { font-size: 1.3em; }
            :deep(h3) { font-size: 1.1em; }
            
            :deep(p) {
              margin: 8px 0;
            }
            
            :deep(ul), :deep(ol) {
              margin: 8px 0;
              padding-left: 24px;
            }
            
            :deep(li) {
              margin: 4px 0;
            }
            
            :deep(code) {
              background: rgba(0, 0, 0, 0.06);
              padding: 2px 6px;
              border-radius: 3px;
              font-family: 'Consolas', 'Monaco', monospace;
              font-size: 0.9em;
            }
            
            :deep(pre) {
              background: #f6f8fa;
              padding: 12px;
              border-radius: 6px;
              overflow-x: auto;
              margin: 8px 0;
              
              code {
                background: none;
                padding: 0;
              }
            }
            
            :deep(blockquote) {
              border-left: 3px solid #667eea;
              padding-left: 12px;
              margin: 8px 0;
              color: #666;
            }
            
            :deep(a) {
              color: #667eea;
              text-decoration: none;
              
              &:hover {
                text-decoration: underline;
              }
            }
            
            :deep(table) {
              border-collapse: collapse;
              width: 100%;
              margin: 8px 0;
              
              th, td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
              }
              
              th {
                background: #f6f8fa;
                font-weight: 600;
              }
            }
          }

          .message-loading {
            display: flex;
            gap: 4px;
            padding: 8px 0;

            .dot {
              width: 8px;
              height: 8px;
              background: #909399;
              border-radius: 50%;
              animation: loading 1.4s ease-in-out infinite;

              &:nth-child(2) {
                animation-delay: 0.2s;
              }

              &:nth-child(3) {
                animation-delay: 0.4s;
              }
            }
          }

          .message-actions {
            display: flex;
            gap: 16px;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid #ebeef5;

            .el-button {
              font-size: 12px;
              color: #909399;

              &:hover {
                color: #667eea;
              }
            }
          }
        }
      }
    }

    .chat-input {
      flex-shrink: 0;
      background: white;
      border-top: 1px solid #ebeef5;
      padding: 16px 24px;
      z-index: 1;

      .input-wrapper {
        display: flex;
        gap: 12px;
        align-items: flex-end;

        .el-textarea {
          flex: 1;

          :deep(.el-textarea__inner) {
            border-radius: 20px;
            padding: 12px 20px;
            resize: none;
          }
        }

        .el-button {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;
          width: 40px;
          height: 40px;
        }
      }

      .input-tips {
        display: flex;
        justify-content: space-between;
        margin-top: 8px;
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .chat-sidebar {
    flex-shrink: 0;
    width: 300px;
    background: white;
    border-left: 1px solid #ebeef5;
    transition: all 0.3s;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;

    &.collapsed {
      width: 40px;
    }

    .sidebar-toggle {
      position: absolute;
      left: -20px;
      top: 50%;
      transform: translateY(-50%);
      width: 40px;
      height: 40px;
      background: white;
      border: 1px solid #ebeef5;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f5f7fa;
      }
    }

    .sidebar-content {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 24px;
      min-height: 0;
      height: 100%;

      .section-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 16px;
      }

      .history-section {
        .history-list {
          .empty-history {
            padding: 20px 0;
          }
          
          .history-item {
            padding: 12px;
            background: #f5f7fa;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;

            &:hover {
              background: #e6e8eb;
              transform: translateX(-4px);
            }
            
            &.active {
              background: #e6e8f0;
              border-color: #667eea;
              
              .history-title {
                color: #667eea;
                font-weight: 600;
              }
            }

            .history-title {
              font-size: 14px;
              color: #333;
              margin-bottom: 4px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .history-time {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }
  }
}

@keyframes loading {
  0%, 60%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  30% {
    transform: scale(1.3);
    opacity: 0.5;
  }
}

// 响应式
@media (max-width: 768px) {
  .chat-course-container {
    .chat-header {
      right: 0;
    }

    .chat-main {
      margin-right: 0;
    }

    .chat-sidebar {
      position: fixed;
      width: 80%;
      max-width: 300px;
      transform: translateX(100%);

      &:not(.collapsed) {
        transform: translateX(0);
      }

      .sidebar-toggle {
        left: -40px;
      }
    }

    .message-item {
      .message-content {
        max-width: 85% !important;
      }
    }
  }
}
</style>
