<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>AI Customer Service</h1>
      <p>与 AI 客服进行对话</p>
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.role]"
      >
        <div class="message-content">
          <!-- 思考过程 - 暂时隐藏 -->
          <!-- <div v-if="message.reasoning_content" class="thinking-process">
            <div class="thinking-header">💭 思考过程</div>
            <div class="thinking-content" v-html="formatMessage(message.reasoning_content)"></div>
          </div> -->
          
          <!-- 主要回答 -->
          <div class="main-content" v-html="formatMessage(message.content)"></div>
          
          <!-- 建议问题 -->
          <div v-if="message.follow_up_questions && message.follow_up_questions.length > 0" class="follow-up-questions">
            <div class="questions-header">💡 相关问题</div>
            <div class="questions-list">
              <div 
                v-for="(question, qIndex) in message.follow_up_questions" 
                :key="qIndex"
                class="question-item"
                @click="askFollowUpQuestion(question)"
              >
                {{ question }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="status-container">
      <div class="status-main">{{ status }}</div>
      <div v-if="statusDetails" class="status-details">{{ statusDetails }}</div>
      <div v-if="chatStatus" class="chat-status">
        <span class="status-label">聊天状态:</span>
        <span :class="['status-value', chatStatus]">{{ chatStatus }}</span>
      </div>
    </div>
    
    <div class="chat-input">
      <div class="input-group">
        <input 
          v-model="currentMessage"
          @keypress.enter="sendMessage"
          type="text" 
          placeholder="输入你的消息..." 
          maxlength="1000"
          :disabled="isProcessing"
        >
        <button 
          @click="sendMessage" 
          :disabled="isProcessing || !currentMessage.trim()"
        >
          {{ isProcessing ? '处理中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, computed } from 'vue'
import { marked } from 'marked'
import useCoze from '~/store/coze'
import useUser from '~/store/user'
import { showFailToast } from 'vant'

marked.setOptions({ breaks: true, gfm: true })

const coze = useCoze()
const { store: userStore } = useUser()

const messages = computed(() => coze.store.messages)
const isProcessing = computed(() => coze.store.isProcessing)

const currentMessage = ref('')
const status = ref('就绪')
const chatStatus = ref('')
const statusDetails = ref('')
const messagesContainer = ref<HTMLElement>()

const STATUS_LABELS: Record<string, string> = {
  pending: '消息已发送，等待AI处理...',
  processing: 'AI正在思考和生成回复...',
  in_progress: 'AI正在思考和生成回复...',
  completed: 'AI回复生成完成！',
  failed: 'AI处理失败，请重试'
}

const sendMessage = async () => {
  const text = currentMessage.value.trim()
  if (!text || isProcessing.value) return

  const htyId = userStore.current.hty_id
  if (!htyId) {
    showFailToast('请先登录后再使用 AI 客服')
    return
  }

  currentMessage.value = ''
  status.value = '正在处理...'
  chatStatus.value = ''
  statusDetails.value = ''
  await nextTick()
  scrollToBottom()

  try {
    if (!coze.store.currentSession) {
      status.value = '创建会话中...'
      statusDetails.value = '正在初始化AI会话...'
      const session = await coze.createSession(htyId)
      if (!session) {
        status.value = '创建会话失败'
        statusDetails.value = '请查看上方 Toast 或控制台具体原因'
        return
      }
      statusDetails.value = `会话已创建 (ID: ${session.session_id.slice(-8)})`
    }

    status.value = '发送消息中...'
    statusDetails.value = '正在发送消息到AI服务...'

    const result = await coze.sendMessage(
      coze.store.currentSession!.session_id,
      text,
      false,
      (s, details) => {
        chatStatus.value = s
        statusDetails.value = STATUS_LABELS[s] || details || `状态: ${s}`
        if (details) status.value = `监控中... (${details})`
      }
    )

    if (result) {
      status.value = '对话完成'
      statusDetails.value = '对话成功完成'
      chatStatus.value = 'completed'
    } else {
      status.value = '发送失败'
      statusDetails.value = '消息发送或处理失败'
      chatStatus.value = 'failed'
    }
  } catch (err: any) {
    status.value = '发送失败'
    statusDetails.value = (err?.e ?? err?.message) || '网络错误或服务异常'
    chatStatus.value = 'error'
  }

  await nextTick()
  scrollToBottom()
}

const formatMessage = (content: string) => (content ? marked(content) : '')

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

// 初始化
const initializeChat = async () => {
  // 添加欢迎消息
  coze.addMessage({
    role: 'assistant',
    content: '你好！我是 AI 客服助手，有什么可以帮助你的吗？'
  })
  
  status.value = '就绪'
  await nextTick()
  scrollToBottom()
}

// 处理建议问题点击
const askFollowUpQuestion = async (question: string) => {
  if (isProcessing.value) return
  
  currentMessage.value = question
  await sendMessage()
}

// 清理会话
const cleanupSession = async () => {
  if (coze.store.currentSession) {
    await coze.terminateSession(coze.store.currentSession.session_id)
  }
}

onMounted(() => {
  initializeChat()
})

// 组件卸载时清理
onUnmounted(() => {
  cleanupSession()
})
</script>

<style scoped lang="less">
.chat-container {
  /* 与 App.vue 底部固定 van-tabbar（约 50px）对齐，留出尽量大的对话区 */
  --ai-cs-tabbar-height: 50px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
  box-sizing: border-box;
  min-height: calc(100dvh - var(--ai-cs-tabbar-height) - env(safe-area-inset-bottom, 0px));
  height: calc(100dvh - var(--ai-cs-tabbar-height) - env(safe-area-inset-bottom, 0px));
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  flex-shrink: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  text-align: center;
  
  h1 {
    font-size: 24px;
    margin-bottom: 5px;
    margin: 0;
  }
  
  p {
    opacity: 0.9;
    font-size: 14px;
    margin: 5px 0 0 0;
  }
}

.chat-messages {
  flex: 1;
  min-height: 0;
  padding: 12px 16px;
  overflow-y: auto;
  background: #f8f9fa;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
    
    &:hover {
      background: #a8a8a8;
    }
  }
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  
  &.user {
    justify-content: flex-end;
    
    .message-content {
      background: #007bff;
      color: white;
    }
  }
  
  &.assistant {
    .message-content {
      background: white;
      color: #333;
      border: 1px solid #e9ecef;
      line-height: 1.6;
      
      .thinking-process {
        background: #f8f9fa;
        border-left: 4px solid #6c757d;
        padding: 12px;
        margin-bottom: 12px;
        border-radius: 4px;
        
        .thinking-header {
          font-weight: 600;
          color: #495057;
          margin-bottom: 8px;
          font-size: 14px;
        }
        
        .thinking-content {
          color: #6c757d;
          font-size: 14px;
          font-style: italic;
        }
      }
      
      .main-content {
        margin-bottom: 12px;
        font-size: 20px;
        line-height: 1.8;
      }
      
      .follow-up-questions {
        border-top: 1px solid #e9ecef;
        padding-top: 12px;
        
        .questions-header {
          font-weight: 600;
          color: #495057;
          margin-bottom: 8px;
          font-size: 14px;
        }
        
        .questions-list {
          display: flex;
          flex-direction: column;
          gap: 6px;
          
          .question-item {
            background: #e3f2fd;
            color: #1976d2;
            padding: 8px 12px;
            border-radius: 16px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            border: 1px solid transparent;
            
            &:hover {
              background: #bbdefb;
              border-color: #2196f3;
              transform: translateY(-1px);
            }
          }
        }
      }
      
      :deep(strong) {
        color: #2196f3;
        font-weight: 600;
      }
      
      :deep(em) {
        color: #666;
        font-style: italic;
      }
      
      :deep(ul) {
        margin: 8px 0;
        padding-left: 20px;
        
        li {
          margin: 4px 0;
          list-style-type: disc;
        }
      }
    }
  }
}

.message-content {
  max-width: 90%;
  padding: 24px 32px;
  border-radius: 18px;
  word-wrap: break-word;
  white-space: normal;
  font-size: 16px;
  line-height: 1.8;
}

.status-container {
  flex-shrink: 0;
  text-align: center;
  padding: 8px 16px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  
  .status-main {
    font-size: 14px;
    font-weight: 500;
    color: #495057;
    margin-bottom: 5px;
  }
  
  .status-details {
    font-size: 14px;
    color: #6c757d;
    margin-bottom: 8px;
    line-height: 1.4;
  }
  
  .chat-status {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 12px;
    
    .status-label {
      color: #6c757d;
    }
    
    .status-value {
      padding: 2px 8px;
      border-radius: 12px;
      font-weight: 500;
      text-transform: uppercase;
      font-size: 11px;
      
      &.pending {
        background: #fff3cd;
        color: #856404;
      }
      
      &.processing,
      &.in_progress {
        background: #cce5ff;
        color: #0066cc;
        animation: pulse 1.5s infinite;
      }
      
      &.completed {
        background: #d4edda;
        color: #155724;
      }
      
      &.failed,
      &.error {
        background: #f8d7da;
        color: #721c24;
      }
    }
  }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.6; }
}

.chat-input {
  flex-shrink: 0;
  padding: 12px 16px 14px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.input-group {
  display: flex;
  gap: 10px;
  
  input {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 25px;
    outline: none;
    font-size: 14px;
    
    &:focus {
      border-color: #007bff;
    }
    
    &:disabled {
      background: #f8f9fa;
      cursor: not-allowed;
    }
  }
  
  button {
    padding: 12px 24px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    font-size: 14px;
    transition: background 0.3s;
    
    &:hover:not(:disabled) {
      background: #0056b3;
    }
    
    &:disabled {
      background: #6c757d;
      cursor: not-allowed;
    }
  }
}
</style>