<template>
  <div class="compare-page">
    <div class="compare-header">
      <a-button @click="router.back()">返回</a-button>
      <h2 style="margin: 0">版本对比</h2>
    </div>

    <div v-if="loading" class="compare-loading">
      <a-spin size="large" />
    </div>

    <div v-else-if="leftReport && rightReport" class="compare-layout">
      <!-- Left version -->
      <div class="compare-panel">
        <div class="compare-panel__header">
          <a-tag color="blue">v{{ leftRecord?.versionNo }}</a-tag>
          <span class="compare-panel__title">{{ leftRecord?.title }}</span>
          <a-tag :color="statusColor(leftRecord?.status || '')">{{ leftRecord?.status }}</a-tag>
        </div>

        <div class="compare-panel__summary" v-if="leftReport.executive_summary">
          <div class="section-label">执行摘要</div>
          <div class="section-content">{{ leftReport.executive_summary }}</div>
        </div>

        <div v-for="section in leftReport.sections || []" :key="section.title" class="compare-panel__section">
          <div class="section-label" :class="{ 'section-label--changed': isSectionChanged(section.title) }">
            {{ section.title }}
            <a-tag v-if="isSectionNew(section.title, 'left')" color="green" size="small">新增</a-tag>
            <a-tag v-else-if="isSectionChanged(section.title)" color="orange" size="small">变更</a-tag>
          </div>
          <div class="section-content">{{ (section.content || '').slice(0, 300) }}{{ (section.content || '').length > 300 ? '...' : '' }}</div>
        </div>
      </div>

      <!-- Right version -->
      <div class="compare-panel">
        <div class="compare-panel__header">
          <a-tag color="blue">v{{ rightRecord?.versionNo }}</a-tag>
          <span class="compare-panel__title">{{ rightRecord?.title }}</span>
          <a-tag :color="statusColor(rightRecord?.status || '')">{{ rightRecord?.status }}</a-tag>
        </div>

        <div class="compare-panel__summary" v-if="rightReport.executive_summary">
          <div class="section-label">执行摘要</div>
          <div class="section-content">{{ rightReport.executive_summary }}</div>
        </div>

        <div v-for="section in rightReport.sections || []" :key="section.title" class="compare-panel__section">
          <div class="section-label" :class="{ 'section-label--changed': isSectionChanged(section.title) }">
            {{ section.title }}
            <a-tag v-if="isSectionNew(section.title, 'right')" color="green" size="small">新增</a-tag>
            <a-tag v-else-if="isSectionChanged(section.title)" color="orange" size="small">变更</a-tag>
          </div>
          <div class="section-content">{{ (section.content || '').slice(0, 300) }}{{ (section.content || '').length > 300 ? '...' : '' }}</div>
        </div>
      </div>
    </div>

    <a-empty v-else description="无法加载版本数据" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchRecordDetail, fetchRecordReport } from '@/api/researchRecords'
import type { ResearchRecordDetail } from '@/types/research'

const route = useRoute()
const router = useRouter()
const loading = ref(true)

const leftRecord = ref<ResearchRecordDetail | null>(null)
const rightRecord = ref<ResearchRecordDetail | null>(null)
const leftReport = ref<Record<string, any> | null>(null)
const rightReport = ref<Record<string, any> | null>(null)

const leftSectionTitles = computed(() =>
  new Set((leftReport.value?.sections || []).map((s: any) => s.title))
)
const rightSectionTitles = computed(() =>
  new Set((rightReport.value?.sections || []).map((s: any) => s.title))
)

function isSectionNew(title: string, side: 'left' | 'right') {
  if (side === 'left') return !rightSectionTitles.value.has(title)
  return !leftSectionTitles.value.has(title)
}

function isSectionChanged(title: string) {
  const leftSection = (leftReport.value?.sections || []).find((s: any) => s.title === title)
  const rightSection = (rightReport.value?.sections || []).find((s: any) => s.title === title)
  if (!leftSection || !rightSection) return false
  return leftSection.content !== rightSection.content
}

function statusColor(status: string) {
  const map: Record<string, string> = {
    draft: 'default', planned: 'blue', running: 'orange',
    completed: 'green', failed: 'red',
  }
  return map[status] || 'default'
}

onMounted(async () => {
  const id = route.params.id as string
  const otherId = route.params.otherId as string

  try {
    const [left, right, leftRep, rightRep] = await Promise.all([
      fetchRecordDetail(id),
      fetchRecordDetail(otherId),
      fetchRecordReport(id),
      fetchRecordReport(otherId),
    ])
    leftRecord.value = left
    rightRecord.value = right
    leftReport.value = leftRep.report
    rightReport.value = rightRep.report
  } catch { /* ignore */ }
  finally { loading.value = false }
})
</script>

<style scoped lang="less">
.compare-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.compare-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.compare-loading {
  display: flex;
  justify-content: center;
  padding: 80px 0;
}

.compare-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  align-items: start;
}

.compare-panel {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #f0f0f0;
  padding: 20px;

  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f5f5f5;
  }

  &__title {
    font-weight: 600;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__summary,
  &__section {
    margin-bottom: 16px;
  }
}

.section-label {
  font-size: 13px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.65);
  margin-bottom: 6px;
  display: flex;
  align-items: center;
  gap: 6px;

  &--changed {
    color: #fa8c16;
  }
}

.section-content {
  font-size: 13px;
  line-height: 1.7;
  color: rgba(0, 0, 0, 0.55);
}
</style>
