<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>
          <text v-html="renderMarkdown(msg.content)"></text>
        </view>
      </view>
    </scroll-view>
    <view class="panel-input">
      <input
        v-model="input"
        class="mini-input"
        placeholder="问关于这个药品..."
        @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
    }
  },
  watch: {
    visible(val) {
      if (val && this.drugName && this.messages.length === 0) {
        this.input = '请介绍' + this.drugName + '的适应症、用法用量和注意事项'
      }
    }
  },
  methods: {
    close() { this.visible = false },

    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 = '结论|详细说明|注意事项|来源明细|适应症|适应证|用法与用量|禁忌|不良反应|副作用|药理|贮藏|特殊人群|安全提醒|通用药学知识|来源汇总'
      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>')
      h = h.replace(/【(.+?)】/g, '<h3>【$1】</h3>')
      return '<p>' + h + '</p>'
    },

    async send() {
      const text = this.input.trim()
      if (!text || this.streaming) return
      this.input = ''
      this.streaming = true

      this.messages.push({ role: 'user', content: text })
      const idx = this.messages.length
      this.messages.push({ role: 'assistant', content: '', thinking: '正在分析...' })
      this.scrollBottom()

      await chatStream(
        { message: text, conversation_id: this.conversationId },
        {
          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: () => { this.messages[idx].content = '服务暂不可用' }
        }
      )
      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); } }
.panel-input { padding: 12rpx 16rpx; border-top: 1rpx solid #eee; }
.mini-input { 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>
