<template>
  <div class="chat-container">
    <div class="chat-messages" ref="chatContainer">
      <!-- 历史缓存 -->
      <div v-for="(message, index) in currentMessages" :key="message.messageId" class="message-group">
        <!-- 用户消息 -->
        <div class="message">
          <div class="message-wrapper user">
            <div class="avatar"><span class="emoji">👤</span></div>
            <div class="message-content">
              <div class="message-text-wrapper">
                <div class="message-text">{{ message.question }}</div>
              </div>
              <!-- 改进建议部分 -->
              <div class="evaluation-toggle" @click="chatStore.toggleEvaluation(message.messageId)">
                <span class="evaluation-btn">改进建议</span>
                <span v-if="['pingfen', 'zongjie'].includes(message.respondingType)" class="typing-indicator evaluation-icon">
                    <span></span><span></span><span></span>
                </span>
                <span v-else class="evaluation-icon">{{ message.showEvaluation ? '▼' : '▶' }}</span>
              </div>
              <!-- 评价总结内容 -->
              <div v-if="message.showEvaluation && (message.pingfen || message.zongjie)" class="evaluation-section">
                <div class="evaluation-content">
                  <div class="evaluation-text pingfen" v-html="formatMarkdown(message.pingfen, 'pingfen')"></div>
                  <div class="evaluation-text zongjie" v-html="formatMarkdown(message.zongjie, 'zongjie')"></div>
                  <div v-if="['pingfen', 'zongjie'].includes(message.respondingType)" class="typing-indicator">
                    <span></span><span></span><span></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 回答 -->
        <div class="message">
          <div class="message-wrapper assistant">
            <div class="avatar"><span class="emoji">🤖</span></div>
            <div class="message-content">
              <div class="message-text-wrapper">
                <div class="message-text" v-html="message.kehu"></div>
                  <div v-if="message.respondingType === 'kehu'" class="typing-indicator">
                    <span></span><span></span><span></span>
                  </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="input-area">
      <button class="new-chat-btn" @click="chatStore.startNewChat" :disabled="newChatButtonsDisabled">
        <span class="new-chat-icon">+</span>
        新会话
      </button>
      <textarea
        v-model="messageInput"
        @keyup.enter.exact="sendMessage"
        @keydown.enter.exact.prevent
        placeholder="请输入消息..."
        rows="1"
        ref="messageInputRef"
        @input="adjustTextareaHeight"
      ></textarea>
      <button class="send-btn" @click="sendMessage" :disabled="sendButtonsDisabled">发送</button>
    </div>
    <!-- 添加总结弹窗 -->
    <div v-if="lastMessageWithDafen" class="summary-panel" :class="{ 'summary-panel-collapsed': isSummaryCollapsed }">
      <div class="summary-header" @click="toggleSummary">
        <span class="summary-title">会话总结</span>
        <span class="summary-toggle-icon">{{ isSummaryCollapsed ? '▼' : '▲' }}</span>
      </div>
      <div class="summary-content" v-html="formatMarkdown(lastMessageWithDafen.dafen)"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch, computed, defineOptions } from 'vue'
import { marked } from 'marked'
import * as echarts from 'echarts'
import { useChatStore } from '@/store/chat'

defineOptions({
  name: 'ChatInterface'
})

const chatStore = useChatStore()
const messageInput = ref('')
const messageInputRef = ref(null)
const chatContainer = ref(null)
const scoreChart = ref(null)
const maxRows = 6
const isUserScrolling = ref(false)
const shouldAutoScroll = ref(true)
const lastScrollTop = ref(0)
const lastScrollHeight = ref(0)
const isSummaryCollapsed = ref(false)

// 使用计算属性获取当前会话的消息
const currentMessages = computed(() => {
  return chatStore.currentMessages
})
const sendButtonsDisabled = computed(() => {
  if (!chatStore.currentConversation) return false
  const currentConversation = chatStore.currentConversation
  if (!currentConversation.conversationStatus) return false
  return ['finished', 'typing'].includes(currentConversation.conversationStatus)
})
const newChatButtonsDisabled = computed(() => {
  if (!chatStore.currentConversation) return false
  const currentConversation = chatStore.currentConversation
  if (!currentConversation.conversationStatus) return false
  return ['typing'].includes(currentConversation.conversationStatus)
})

// 获取最后一条包含dafen字段的消息
const lastMessageWithDafen = computed(() => {
  if (!chatStore.currentMessages.length) return null
  // 从后往前查找第一条包含dafen字段的消息
  for (let i = chatStore.currentMessages.length - 1; i >= 0; i--) {
    if (chatStore.currentMessages[i].dafen) {
      return chatStore.currentMessages[i]
    }
  }
  return null
})

// 配置marked选项
marked.setOptions({
  breaks: true,
  gfm: true,
  sanitize: false,
  headerIds: false,
  mangle: false
})

// 检查是否接近底部
const isNearBottom = (threshold = 100) => {
  const container = chatContainer.value
  if (!container) return false
  return container.scrollHeight - container.scrollTop - container.clientHeight < threshold
}

// 监听滚动事件
const handleScroll = () => {
  const container = chatContainer.value
  if (!container) return

  // 检测是否是用户主动滚动
  if (Math.abs(container.scrollTop - lastScrollTop.value) > 10) {
    isUserScrolling.value = true
    // 根据是否接近底部来决定是否恢复自动滚动
    shouldAutoScroll.value = isNearBottom(50)
  }

  lastScrollTop.value = container.scrollTop
  lastScrollHeight.value = container.scrollHeight
}

// 滚动到底部的方法
const scrollToBottom = (force = false) => {
  nextTick(() => {
    const container = chatContainer.value
    if (!container) return

    // 在以下情况下滚动到底部：
    // 1. 强制滚动
    // 2. 允许自动滚动且没有用户滚动操作
    // 3. 用户已经接近底部
    if (force || (shouldAutoScroll.value && !isUserScrolling.value) || isNearBottom(50)) {
      container.scrollTop = container.scrollHeight
      lastScrollTop.value = container.scrollTop
      lastScrollHeight.value = container.scrollHeight
      isUserScrolling.value = false
    }
  })
}

// 监听消息缓存变化
watch(() => chatStore.messageCache, (newCache, oldCache) => {
  if (!oldCache || Object.keys(newCache).length > Object.keys(oldCache).length) {
    scrollToBottom(shouldAutoScroll.value)
  }
}, { deep: true })

// 监听当前会话的消息
watch(() => currentMessages.value, (newMessages, oldMessages) => {
  if (!oldMessages || newMessages.length > oldMessages.length) {
    scrollToBottom(shouldAutoScroll.value)
    return
  }

  // 检查最后一条消息的respondingType
  const lastMessage = newMessages[newMessages.length - 1]
  if (lastMessage && ['kehu', 'pingfen', 'zongjie'].includes(lastMessage.respondingType)) {
    scrollToBottom(true) // 特定类型消息强制滚动
  }
}, { deep: true })

// 监听消息的respondingType变化
watch(() => currentMessages.value?.map(msg => msg.respondingType), (newTypes, oldTypes) => {
  if (!newTypes || !oldTypes) return
  const lastType = newTypes[newTypes.length - 1]
  if (['kehu', 'pingfen', 'zongjie'].includes(lastType)) {
    scrollToBottom(true) // 特定类型消息强制滚动
  }
}, { deep: true })

// 发送消息时滚动到底部
const sendMessage = () => {
  if (!messageInput.value.trim()) return
  chatStore.sendMessage(messageInput.value)
  messageInput.value = ''
  messageInputRef.value.style.height = 'auto'
  shouldAutoScroll.value = true // 发送消息时恢复自动滚动
  scrollToBottom(true)
}

const initChart = () => {
  if (scoreChart.value) {
    const chart = echarts.init(scoreChart.value)
    
    const scoreData = chatStore.score.split(',').map(item => {
      const [name, value] = item.split(':')
      return { name, value: parseFloat(value) }
    })
    
    const option = {
      title: {
        text: '成绩维度分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      radar: {
        indicator: scoreData.map(item => ({
          name: item.name,
          max: 100
        }))
      },
      series: [{
        type: 'radar',
        data: [{
          value: scoreData.map(item => item.value),
          name: '成绩',
          areaStyle: {
            color: 'rgba(76, 175, 80, 0.3)'
          },
          lineStyle: {
            color: '#4CAF50'
          },
          itemStyle: {
            color: '#4CAF50'
          }
        }]
      }]
    }
    
    chart.setOption(option)
    
    const handleResize = () => {
      chart.resize()
    }
    
    window.addEventListener('resize', handleResize)
    
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      chart.dispose()
    })
  }
}

// 格式化聊天内容
const formatMarkdown = (text, tagType) => {
  if (!text) return ''
  return marked.parse(text)
}

const adjustTextareaHeight = () => {
  const textarea = messageInputRef.value
  textarea.style.height = 'auto'
  const newHeight = Math.min(textarea.scrollHeight, maxRows * 24)
  textarea.style.height = newHeight + 'px'
}

const toggleSummary = () => {
  isSummaryCollapsed.value = !isSummaryCollapsed.value
}

onMounted(() => {
  if (chatContainer.value) {
    chatContainer.value.addEventListener('scroll', handleScroll)
    // 初始化时滚动到底部
    scrollToBottom(true)
    shouldAutoScroll.value = true
  }

  if (chatStore.score && scoreChart.value) {
    initChart()
  }
})

onUnmounted(() => {
  // 移除滚动事件监听
  if (chatContainer.value) {
    chatContainer.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: scroll;
  padding: 20px;
  padding-bottom: 120px;
  padding-right: 24px;
  margin-right: -12px;
  position: relative;
  z-index: 1;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch; // 添加iOS滚动优化
  
  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    margin: 4px 0;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    border: 2px solid transparent;
    background-clip: padding-box;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

.message-group {
  margin-bottom: 24px;
}

.message {
  margin-bottom: 16px;
  position: relative;

  .message-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    &.user {
      flex-direction: row-reverse;
      justify-content: flex-start;
      .message-text {
        background-color: #95ec69;
      }
      .message-content {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
      }
    }

    &.assistant {
      flex-direction: row;
      justify-content: flex-start;
      .message-text {
        background-color: #ffffff;
      }
      .message-content {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
    }

    .avatar {
      width: 40px;
      height: 40px;
      flex-shrink: 0;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(0, 0, 0, 0.05);

      .emoji {
        font-size: 20px;
        line-height: 1;
      }
    }
  }
}

.message-content {
  flex: 0 1 auto;
  min-width: 0;
  max-width: 70%;
  word-wrap: break-word;
  position: relative;

  .message-text-wrapper {
    position: relative;
    display: inline-block;
    max-width: 100%;
    
    .message-text {
      min-height: 36px;
      line-height: 1.5;
      font-size: 16px;
      padding: 8px 12px;
      border-radius: 4px;
      white-space: pre-wrap;
      position: relative;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(0, 0, 0, 0.05);
      display: inline-block;
      max-width: 100%;

      &::before {
        content: '';
        position: absolute;
        width: 0;
        height: 0;
        border: 6px solid transparent;
        top: 10px;
      }
    }
  }

  .evaluation-toggle {
    display: flex!important;
    cursor: pointer;
    color: #576b95;
    font-size: 13px;
    margin-top: 8px;
    padding: 6px 12px;
    display: block;
    width: fit-content;
    align-items: center;
    border-radius: 6px;
    background: rgba(87, 107, 149, 0.08);
    transition: all 0.3s ease;
    border: 1px solid rgba(87, 107, 149, 0.1);

    &:hover {
      background: rgba(87, 107, 149, 0.15);
      border-color: rgba(87, 107, 149, 0.2);
    }

    .evaluation-btn {
      padding-right: 4px;
      font-weight: 500;
    }

    .evaluation-icon {
      font-size: 12px;
      transition: transform 0.3s ease;
      
      &.typing-indicator {
        padding: 0;
        display: inline-flex;
        align-items: center;
        gap: 2px;
        
        span {
          width: 4px;
          height: 4px;
          background: #576b95;
          border-radius: 50%;
          animation: bounce 1.4s infinite ease-in-out;
          
          &:nth-child(1) { animation-delay: -0.32s; }
          &:nth-child(2) { animation-delay: -0.16s; }
        }
      }
    }
  }
}

.evaluation-section {
  margin-top: 12px;
  font-size: 14px;
  background: #fff;
  border-radius: 8px;
  overflow: visible;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  max-width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;

  .evaluation-content {
    padding: 16px 24px 16px 16px;
    background: #f8f9fa;
    // max-height: 480px;
    overflow-y: scroll;
    position: relative;
    
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
      display: block;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      margin: 4px 0;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 4px;
      border: 2px solid transparent;
      background-clip: padding-box;

      &:hover {
        background: rgba(0, 0, 0, 0.3);
      }
    }
    
    .evaluation-text {
      opacity: 0.9;
      color: #495057;
      border: none;
      box-shadow: none;
      padding: 0;
      margin-bottom: 12px;
      min-height: unset;
      line-height: 1.6;

      &:last-child {
        margin-bottom: 0;
      }

      :deep(p) {
        margin: 0;
        line-height: 1.6;
      }

      :deep(ul), :deep(ol) {
        margin: 8px 0;
        padding-left: 20px;
      }

      :deep(strong) {
        color: #2c3e50;
        font-weight: 600;
      }

      :deep(em) {
        color: #6c757d;
        font-style: italic;
      }
    }
  }
}

.input-area {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  background: #f5f5f5;
  border-top: 1px solid #e5e5e5;
  align-items: flex-end;
  z-index: 101;

  textarea {
    flex: 1;
    padding: 10px 16px;
    border: 1px solid #eee;
    border-radius: 4px;
    outline: none;
    transition: all 0.3s;
    background: #fff;
    resize: none;
    min-height: 42px;
    max-height: calc(24px * 6);
    line-height: 1.5;

    &:focus {
      border-color: #07c160;
      box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.1);
    }
  }

  button {
    padding: 0 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    height: 42px;
    transition: all 0.3s;
    line-height: 42px;
    border: 1px solid #ddd;
    white-space: nowrap;
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}

.new-chat-btn {
  padding: 0 16px;
  background: #fff;
  color: #333;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  
  &:hover {
    background: #e8e8e8;
    border-color: #ccc;
  }

  &:disabled {
    background: #f5f5f5;
    border-color: #ddd;
    color: #999;
    cursor: not-allowed;
  }

  .new-chat-icon {
    
    font-size: 18px;
    font-weight: bold;
    line-height: 1;
  }
}
.send-btn {
  color: white;
  background: #07c160;
  &:hover {
      background: #06ae56;
    }
}
/* 统一的滚动条样式 */
.chat-messages,
.summary-content,
.evaluation-content {
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    display: block;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    margin: 4px 0;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    border: 2px solid transparent;
    background-clip: padding-box;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

/* 添加媒体查询以适应不同屏幕 */
@media screen and (max-width: 768px) {
  .message-wrapper {
    max-width: 90%;
  }
}

@media screen and (max-width: 480px) {
  .message-wrapper {
    max-width: 95%;
  }
}

.user {
  .message-text {
    background-color: #95ec69;
    border-color: rgba(0, 0, 0, 0.08);

    &::before {
      border-right-color: #95ec69;
      right: 100%;
      transform: scaleX(-1);
    }
  }
}

.assistant {
  .message-text {
    background-color: #ffffff;
    border-color: rgba(0, 0, 0, 0.08);

    &::before {
      border-right-color: #ffffff;
      right: 100%;
    }
  }
}

.typing {
  &::after {
    display: none;
  }
}

.typing-indicator {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  height: 20px;
  
  span {
    width: 4px;
    height: 4px;
    background: #999;
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.evaluation-toggle {
  transition: all 0.3s ease;
}

.evaluation-text {
  position: relative;
  margin-bottom: 12px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.summary-panel {
  position: absolute;
  bottom: 80px;
  left: 20px;
  right: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 100;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-height: 300px;

  &.summary-panel-collapsed {
    max-height: 42px; // 标题栏的高度

    .summary-content {
      opacity: 0;
      transform: translateY(-20px);
      visibility: hidden;
    }
    
    .summary-header {
      border-bottom: none;
    }
  }

  .summary-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    background: #f8f9fa;
    cursor: pointer;
    border-bottom: 1px solid #e9ecef;
    transition: all 0.3s ease;
    flex-shrink: 0;
    height: 42px;

    .summary-title {
      font-weight: 600;
      color: #2c3e50;
      font-size: 15px;
    }

    .summary-toggle-icon {
      color: #6c757d;
      font-size: 14px;
      transition: transform 0.3s ease;
    }
  }

  .summary-content {
    flex: 1;
    min-height: 0;
    max-height: 250px;
    overflow-y: auto;
    padding: 16px;
    background: #fff;
    color: #495057;
    line-height: 1.6;
    font-size: 14px;
    transition: all 0.3s ease;
    opacity: 1;
    transform: translateY(0);
    visibility: visible;

    :deep(p) {
      margin: 0 0 12px 0;
      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(ul), :deep(ol) {
      margin: 8px 0;
      padding-left: 20px;
      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(strong) {
      color: #2c3e50;
      font-weight: 600;
    }

    :deep(em) {
      color: #6c757d;
      font-style: italic;
    }

    :deep(code) {
      background: #f8f9fa;
      padding: 2px 4px;
      border-radius: 4px;
      color: #e83e8c;
      font-family: 'Courier New', Courier, monospace;
    }
  }
}
</style> 