<template>
  <view :class="['detail-page', elderClass]">
    <Loading v-if="loading" text="加载中..." />
    <view v-else-if="!analysis" class="empty-wrap"><text class="empty-text">报告不存在</text></view>
    <template v-else>
      <view class="detail-card">
        <text class="detail-type">{{ TYPE_LABELS[analysis.analysis_type] || analysis.analysis_type }}</text>
        <view class="detail-meta">
          <text class="meta-item">模型: {{ analysis.model_used }}</text>
          <text class="meta-item">{{ new Date(analysis.created_at).toLocaleString('zh-CN') }}</text>
        </view>
        <view v-if="isAutoAnalysis" class="auto-badge">
          <text class="auto-badge-text">系统自动分析</text>
        </view>
      </view>
      <view v-if="isTrendAnalysis" class="trend-tip-card">
        <text class="trend-tip-text">趋势分析基于最小二乘法线性回归和 2 倍标准差异常检测。R² 越接近 1 表示趋势拟合越好。</text>
      </view>
      <view class="content-card">
        <rich-text class="report-content" :nodes="htmlContent" />
      </view>
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getAiAnalysisDetail, type AiAnalysisItem } from '@/services/ai-analysis'
import { useElderClass } from '@/composables/useElderClass'
import Loading from '@/components/Loading.vue'

const TYPE_LABELS: Record<string, string> = {
  lab_report_interpretation: '化验单解读', health_trend_analysis: '趋势分析',
  personalized_checkup_plan: '体检方案', report_summary_generation: '报告摘要',
}

function sanitizeHtml(html: string): string {
  return html
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
    .replace(/<\/?(?:iframe|object|embed|form|input|textarea|style)\b[^>]*>/gi, '')
    .replace(/<\/?(?:link|meta)\b[^>]*>/gi, '')
    .replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
}

function markdownToHtml(md: string): string {
  const escaped = sanitizeHtml(md)
  return escaped
    .replace(/^### (.+)$/gm, '<h3>$1</h3>')
    .replace(/^## (.+)$/gm, '<h2>$1</h2>')
    .replace(/^# (.+)$/gm, '<h1>$1</h1>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/^- (.+)$/gm, '<li>$1</li>')
    .replace(/(<li>[\s\S]*?<\/li>)/g, '<ul>$1</ul>')
    .replace(/\n\n/g, '<br/><br/>')
    .replace(/\n/g, '<br/>')
}

const { elderClass } = useElderClass()
const analysis = ref<AiAnalysisItem | null>(null)
const loading = ref(true)

const htmlContent = computed(() => analysis.value?.result_content ? markdownToHtml(analysis.value.result_content) : '<p>暂无分析结果</p>')
const isTrendAnalysis = computed(() => analysis.value?.analysis_type === 'trend')
const isAutoAnalysis = computed(() => (analysis.value?.result_metadata as Record<string, unknown>)?.auto_analysis === true)

onLoad((query) => {
  const id = query?.id || ''
  if (!id) { loading.value = false; return }
  getAiAnalysisDetail(id).then(data => { analysis.value = data }).catch(() => uni.showToast({ title: '加载失败', icon: 'none' })).finally(() => { loading.value = false })
})
</script>

<style lang="scss" scoped>
.detail-page { min-height: 100vh; background: $bg; padding: 24px; }
.empty-wrap { @include flex-center; padding: 120px 0; }
.empty-text { font-size: var(--tk-font-body); color: $tx3; }
.detail-card { @include card; margin-bottom: 16px; }
.detail-type { font-size: var(--tk-font-title); font-weight: 600; color: $tx; display: block; margin-bottom: 8px; }
.detail-meta { display: flex; gap: 16px; }
.meta-item { font-size: var(--tk-font-cap); color: $tx3; }
.auto-badge { display: inline-block; margin-top: 8px; padding: 2px 10px; background: rgba($pri, 0.1); border-radius: 4px; }
.auto-badge-text { font-size: var(--tk-font-micro); color: $pri; }
.trend-tip-card { @include card; margin-bottom: 16px; background: rgba(250,173,20,0.08); }
.trend-tip-text { font-size: var(--tk-font-cap); color: $tx2; line-height: 1.6; }
.content-card { @include card; }
.report-content { font-size: var(--tk-font-body); line-height: 1.8; color: $tx; }
</style>
