<template>
  <view class="ai-chat-panel" v-if="visible">
    <view class="panel-header">
      <text class="panel-title">AI 药典助手</text>
      <button class="close-btn" size="mini" @click="close">✕</button>
    </view>
    <scroll-view class="panel-body" scroll-y :scroll-top="scrollTop">
      <view v-for="(msg, idx) in messages" :key="idx" class="chat-item">
        <view :class="msg.role === 'user' ? 'chat-user' : 'chat-ai'">
          <view v-if="msg.thinking" class="thinking">
            <view class="think-dot"></view>
            <text>{{ msg.thinking }}</text>
          </view>
          <rich-text :nodes="renderMarkdown(msg.content)"></rich-text>
        </view>
      </view>
    </scroll-view>
    <!-- 媒体预览 -->
    <view v-if="pendingMedia" class="media-preview">
      <image v-if="pendingMedia.type==='image'" :src="pendingMedia.preview" mode="aspectFit" class="preview-thumb"/>
      <text class="preview-name">{{ pendingMedia.type==='video'?'🎬':'📷' }} {{ pendingMedia.name }}</text>
      <text class="preview-remove" @click="pendingMedia=null">✕</text>
    </view>
    <view class="panel-input">
      <text class="mini-media-btn" @click="pickImage">📷</text>
      <text class="mini-media-btn" @click="pickVideo">🎬</text>
      <input
        v-model="input"
        class="mini-input"
        :placeholder="pendingMedia?(pendingMedia.type==='video'?'视频已就绪，输入问题...':'图片已就绪，输入问题...'):'问关于这个药品...'"
        @confirm="send"
      />
    </view>
  </view>
  <view v-else class="ai-trigger" @click="visible = true">
    <text class="trigger-icon">💊</text>
    <text class="trigger-text">问 AI</text>
  </view>
</template>

<script>
import { chatStream } from '@/api/ai.js'

export default {
  name: 'AiChatPanel',
  props: {
    drugName: { type: String, default: '' }
  },
  data() {
    return {
      visible: false,
      messages: [],
      input: '',
      streaming: false,
      conversationId: '',
      scrollTop: 0,
      pendingMedia: null
    }
  },
  watch: {
    visible(val) {
      if (val && this.drugName && this.messages.length === 0) {
        this.input = '请介绍' + this.drugName + '的适应症、用法用量和注意事项'
      }
    }
  },
  methods: {
    close() { this.visible = false },

    pickImage() {
      uni.chooseImage({
        count: 1, sizeType: ['compressed'],
        success: (res) => {
          const path = res.tempFilePaths[0]
          this.fileToBase64(path, 'image', (b64, info) => {
            this.pendingMedia = { type: 'image', base64: b64, mime: info.mime, name: info.name, preview: path }
          })
        }
      })
    },
    pickVideo() {
      uni.chooseVideo({
        maxDuration: 60, compressed: true,
        success: (res) => {
          const path = res.tempFilePath
          this.fileToBase64(path, 'video', (b64, info) => {
            this.pendingMedia = { type: 'video', base64: b64, mime: info.mime, name: info.name, preview: path }
          })
        }
      })
    },
    fileToBase64(path, type, cb) {
      const fs = uni.getFileSystemManager()
      try {
        const data = fs.readFileSync(path, 'base64')
        const name = path.split('/').pop() || (type === 'video' ? 'video.mp4' : 'photo.jpg')
        const mime = type === 'video' ? 'video/mp4' : 'image/jpeg'
        cb(data, { mime, name })
      } catch (e) {
        uni.showToast({ title: '读取文件失败', icon: 'none' })
      }
    },

    renderMarkdown(content) {
      if (!content) return ''
      let h = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      h = h.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
      var secs = '结论|详细说明|注意事项|来源明细|适应症|适应证|用法与用量|禁忌|不良反应|副作用|药理|贮藏|特殊人群|安全提醒|通用药学知识|来源汇总|AI 声明|AI声明|来源说明|免责声明'
      h = h.replace(new RegExp('(?<![【])】\\s*(' + secs + ')', 'g'), '【$1】')
      h = h.replace(new RegExp('(?<![【])(' + secs + ')】', 'g'), '【$1】')
      h = h.replace(/\n\n+/g, '</p><p>')
      h = h.replace(/\n/g, '<br>')
      // 段落标题：吞掉紧跟的 <br>
      h = h.replace(/【(.+?)】(?:<br>)?/g, '<p style="font-size:30rpx;color:#002FA7;font-weight:bold;margin:14rpx 0 2rpx">【$1】</p>')
      // 去掉标题 <p> 前后的 <br>
      h = h.replace(/<br><p style="font-size:30rpx/g, '<p style="font-size:30rpx')
      h = h.replace(/<\/p><br>/g, '</p>')
      // markdown 链接 [文字](url) → <a>
      h = h.replace(/\[([^\]]+)\]\((https?:\/\/[^\s<>)]+)\)/g, '<a href="$2" style="color:#002FA7;text-decoration:underline">$1</a>')
      // 纯 URL 自动转可点击链接
      h = h.replace(/(?<!href=")(?<!href=')(https?:\/\/[^\s<>]+)/g, '<a href="$1" style="color:#002FA7;text-decoration:underline;word-break:break-all">$1</a>')
      return '<div style="font-size:28rpx;line-height:1.8;color:#1a1a2e;word-break:break-all">' + h + '</div>'
    },

    async send() {
      const text = this.input.trim()
      const media = this.pendingMedia
      if (!text && !media) return
      if (this.streaming) return
      this.input = ''
      this.pendingMedia = null
      this.streaming = true

      let userDisplay = text
      if (media) {
        userDisplay = (media.type === 'video' ? '🎬 [视频] ' : '📷 [图片] ') + (text || '请分析')
      }
      this.messages.push({ role: 'user', content: userDisplay })
      const idx = this.messages.length
      this.messages.push({ role: 'assistant', content: '', thinking: '正在分析...' })
      this.scrollBottom()

      const reqBody = { message: text, conversation_id: this.conversationId }
      if (media) {
        reqBody.media_type = media.type
        reqBody.media_base64 = media.base64
        reqBody.media_mime = media.mime
      }
      await chatStream(
        reqBody,
        {
          onIntent: (d) => { this.messages[idx].intent = d },
          onStatus: (d) => { this.messages[idx].thinking = d; this.scrollBottom() },
          onToken: (d) => { this.messages[idx].thinking = ''; this.messages[idx].content += d; this.scrollBottom() },
          onMeta: (meta) => { if (meta.cid) this.conversationId = meta.cid },
          onDone: () => { this.messages[idx].thinking = '' },
          onError: (err) => { this.messages[idx].content = err.message || '服务暂不可用' }
        }
      )
      this.streaming = false
    },

    scrollBottom() {
      this.$nextTick(() => { this.scrollTop = 999999 })
    }
  }
}
</script>

<style scoped>
.ai-chat-panel {
  position: fixed; right: 0; bottom: 0; width: 90vw; max-width: 500rpx; height: 60vh;
  background: #fff; border-radius: 16rpx 16rpx 0 0; box-shadow: 0 -4rpx 20rpx rgba(0,0,0,.12);
  display: flex; flex-direction: column; z-index: 999;
}
.panel-header {
  display: flex; justify-content: space-between; align-items: center;
  padding: 16rpx 24rpx; background: #002FA7; color: #fff; border-radius: 16rpx 16rpx 0 0;
}
.panel-title { font-size: 28rpx; font-weight: 600; }
.close-btn { background: rgba(255,255,255,.2); border: none; color: #fff; border-radius: 8rpx; }
.panel-body { flex: 1; padding: 16rpx; overflow-y: auto; }
.chat-item { margin-bottom: 16rpx; }
.chat-user { text-align: right; color: #002FA7; background: #E8EDF8; padding: 10rpx 16rpx; border-radius: 12rpx 12rpx 4rpx 12rpx; font-size: 26rpx; display: inline-block; max-width: 80%; }
.chat-ai { text-align: left; background: #F5F6FA; padding: 10rpx 16rpx; border-radius: 4rpx 12rpx 12rpx 12rpx; font-size: 26rpx; color: #1a1a2e; border-left: 4rpx solid #002FA7; word-break: break-all; }
.thinking { color: #888; font-size: 22rpx; display: flex; align-items: center; margin-bottom: 6rpx; }
.think-dot { width: 10rpx; height: 10rpx; border-radius: 50%; background: #002FA7; margin-right: 8rpx; animation: pulse 1s infinite; }
@keyframes pulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: .4; transform: scale(.7); } }
.media-preview { display: flex; align-items: center; padding: 8rpx 16rpx; background: #fafafa; gap: 8rpx; }
.preview-thumb { width: 60rpx; height: 60rpx; border-radius: 6rpx; flex-shrink: 0; }
.preview-name { font-size: 22rpx; color: #888; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.preview-remove { font-size: 24rpx; color: #C41E3A; padding: 4rpx; }

.panel-input { display: flex; align-items: center; padding: 12rpx 16rpx; border-top: 1rpx solid #eee; gap: 6rpx; }
.mini-media-btn { font-size: 32rpx; padding: 4rpx; min-width: 44rpx; text-align: center; flex-shrink: 0; }
.mini-input { flex: 1; height: 64rpx; background: #F5F6FA; border-radius: 32rpx; padding: 0 20rpx; font-size: 26rpx; }
.ai-trigger {
  position: fixed; right: 24rpx; bottom: 120rpx; width: 96rpx; height: 96rpx;
  background: linear-gradient(135deg, #002FA7, #1a3fbf); border-radius: 50%;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0,47,167,.35); z-index: 99;
}
.trigger-icon { font-size: 36rpx; }
.trigger-text { font-size: 20rpx; color: #fff; margin-top: 2rpx; }
</style>
