<template>
  <view class="chat-page">
    <scroll-view scroll-y="true" class="chat-container" :scroll-into-view="scrollIntoView" scroll-with-animation>
      <view v-for="(msg, index) in messages" :key="index" :id="'msg-' + index" class="message" :class="msg.role">
        <text>{{ msg.content }}</text>
      </view>
    </scroll-view>

    <view class="input-bar">
      <input v-model="inputText" :disabled="loading" class="chat-input" placeholder="请输入你的问题..." @confirm="sendMessage" />
      <button :disabled="loading || !inputText.trim()" @click="sendMessage" class="send-button">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import {
	chartStream
} from '@/api/services/chart.js'

// 响应式数据
const inputText = ref('')
const messages = ref([])
const loading = ref(false)
const scrollIntoView = ref('')

// 发送消息
const sendMessage = () => {
	const content = inputText.value.trim()
	if (!content || loading.value) return

	messages.value.push({ role: 'user', content })
	inputText.value = ''
	scrollToBottom()

	const aiMsg = { role: 'ai', content: '' }
	messages.value.push(aiMsg)
	loading.value = true
	scrollToBottom()

	const requestBody = {
		query: content,
		user: 'test_user_123' // 实际项目中应为真实用户ID
	}

	uni.request({
		url: 'http://localhost:9203/dify/chat/stream', // ⚠️ 换成你自己的后端
		method: 'POST',
		header: {
			'Content-Type': 'application/json'
		},
		data: requestBody,
		success: (res) => {
			const reader = res.data.getReader?.()
			const decoder = new TextDecoder()
			let buffer = ''

			const readStream = () => {
				reader.read().then(({ done, value }) => {
					if (done) {
						loading.value = false
						return
					}

					buffer += decoder.decode(value, { stream: true })
					const events = buffer.split('\n\n')
					buffer = events.pop() // 保留未完成部分

					events.forEach(evt => {
						if (!evt.trim()) return
						const lines = evt.split('\n')
						let eventData = ''

						lines.forEach(line => {
							if (line.startsWith('data:')) {
								eventData = line.replace(/^data:\s*/, '')
							}
						})

						try {
							const json = JSON.parse(eventData)
							if (json.event === 'message') {
								aiMsg.content += json.answer || ''
								scrollToBottom()
							} else if (json.event === 'message_end') {
								loading.value = false
							}
						} catch (e) {
							console.warn('解析流数据失败:', e)
						}
					})

					readStream()
				})
			}

			readStream()
		},
		fail: (err) => {
			loading.value = false
			aiMsg.content = '[请求失败: ' + err.errMsg + ']'
		}
	})
}

const scrollToBottom = () => {
	nextTick(() => {
		scrollIntoView.value = 'msg-' + (messages.value.length - 1)
	})
}
</script>

<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f3f3f3;
}
.chat-container {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  background-color: #f3f3f3;
}
.message {
  margin-bottom: 20rpx;
  padding: 20rpx;
  border-radius: 20rpx;
  max-width: 80%;
  word-break: break-word;
}
.message.user {
  align-self: flex-end;
  background-color: #dfffd6;
}
.message.ai {
  align-self: flex-start;
  background-color: #ffffff;
}
.input-bar {
  display: flex;
  align-items: center;
  padding: 10rpx;
  border-top: 1px solid #ddd;
  background-color: #fff;
}
.chat-input {
  flex: 1;
  padding: 10rpx;
  border: 1px solid #ccc;
  border-radius: 10rpx;
}
.send-button {
  margin-left: 10rpx;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 10rpx;
  padding: 10rpx 20rpx;
}
</style>
