<template>
  <div style="padding: 16px">
    <h2>XMarkdownViewer Demo</h2>

    <div style="margin: 12px 0; padding: 12px; background: #f5f5f5; border-radius: 4px">
      <h4 style="margin: 0 0 8px 0">流式 AI 调用示例</h4>
      <div style="margin-bottom: 8px">
        <input
          v-model="userMessage"
          type="text"
          placeholder="输入消息"
          style="width: 300px; padding: 6px 8px; border: 1px solid #ddd; border-radius: 4px"
          @keyup.enter="sendMessage"
        >
        <button
          type="button"
          style="margin-left: 8px; padding: 6px 16px; background: #1890ff; color: #fff; border: none; border-radius: 4px; cursor: pointer"
          @click="sendMessage"
        >
          发送
        </button>
        <button
          v-if="isStreaming"
          type="button"
          style="margin-left: 8px; padding: 6px 16px; background: #ff4d4f; color: #fff; border: none; border-radius: 4px; cursor: pointer"
          @click="stopMessage"
        >
          停止
        </button>
      </div>
      <div v-if="isStreaming" style="color: #1890ff; font-size: 12px">AI 正在思考中...</div>
    </div>

    <div style="margin: 8px 0; color: #666; font-size: 12px">
      <span v-if="fileName">当前文件：{{ fileName }}（{{ md.length }} 字符）</span>
      <span v-else-if="md">当前内容：流式响应（{{ md.length }} 字符）</span>
      <span v-else>请输入消息并点击发送</span>
    </div>

    <x-markdown-viewer ref="viewer" :markdown="md" />
  </div>
</template>

<script>
import XMarkdownViewer from './XMarkdownViewer.vue'

export default {
  name: 'XMarkdownViewerDemo',
  components: {
    XMarkdownViewer
  },
  data () {
    return {
      md: '',
      fileName: '',
      userMessage: '',
      isStreaming: false,
      currentStream: null
    }
  },
  methods: {
    async sendMessage () {
      const message = this.userMessage.trim()
      if (!message) return

      const viewer = this.$refs.viewer
      if (!viewer || typeof viewer.callAiStream !== 'function') {
        console.warn('[Demo] viewer 不存在或没有 callAiStream 方法')
        return
      }

      // 开始时显示提示
      viewer.receiveMarkdownString('### 思考中，请稍后...\n')
      this.isStreaming = true

      // 调用流式接口
      const stream = viewer.callAiStream(message, {
        onChunk: (text) => {
          viewer.receiveMarkdownString('### 思考中，请稍后...\n\n' + viewer.getStreamContent())
        },
        onEnd: (fullContent) => {
          viewer.receiveMarkdownString(fullContent)
          this.isStreaming = false
        },
        onError: (error) => {
          viewer.receiveMarkdownString('### 抱歉，发生了错误\n\n' + error)
          this.isStreaming = false
        }
      })

      this.currentStream = stream
    },
    stopMessage () {
      if (this.currentStream && typeof this.currentStream.stop === 'function') {
        this.currentStream.stop()
        this.isStreaming = false
      }
    }
  }
}
</script>

