<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>
	import {
		chartStream
	} from '@/api/services/chart.js';
export default {
  data() {
    return {
      inputText: '',
      messages: [],
      loading: false,
      scrollIntoView: ''
    };
  },
  methods: {
    sendMessage() {
      const content = this.inputText.trim();
      if (!content || this.loading) return;

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

      const aiMsg = { role: 'ai', content: '' };
      this.messages.push(aiMsg);
      this.loading = true;
      this.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) {
                this.loading = 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 || '';
                    this.scrollToBottom();
                  } else if (json.event === 'message_end') {
                    this.loading = false;
                  }
                } catch (e) {
                  console.warn('解析流数据失败:', e);
                }
              });

              readStream();
            });
          };

          readStream();
        },
        fail: (err) => {
          this.loading = false;
          aiMsg.content = '[请求失败: ' + err.errMsg + ']';
        }
      });
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollIntoView = 'msg-' + (this.messages.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>
