<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { reportApi } from '@/api/service-monitor'
import type { CompareResult } from '@/types/service-monitor'

const route = useRoute()
const router = useRouter()

const reportIdA = route.params.reportIdA as string
const reportIdB = route.params.reportIdB as string

const loading = ref(false)
const error = ref('')
const data = ref<CompareResult | null>(null)

// Export menu
const showExportMenu = ref(false)

function toggleExport() {
  showExportMenu.value = !showExportMenu.value
}

function getExportUrl(format: 'md' | 'html') {
  return `/api/service-monitor/reports/${reportIdA}/compare/${reportIdB}/export?format=${format}`
}

// Format
function formatTime(timeStr: string | undefined) {
  if (!timeStr) return '-'
  return timeStr.replace('T', ' ').slice(0, 16)
}

// Total diffs
const totalDiffs = computed(() => {
  if (!data.value) return 0
  const s = data.value.diff_summary
  return s.new_abnormal + s.recovered + s.value_changed + s.new_items + s.removed_items
})

// View report
function viewReportA() {
  router.push({ name: 'MonitorReportDetail', params: { reportId: reportIdA } })
}

function goBack() {
  router.push({ name: 'MonitorReports' })
}

// Load data
async function loadData() {
  loading.value = true
  error.value = ''
  try {
    const res = await reportApi.compareReports(reportIdA, reportIdB)
    if (res.success && res.data) {
      data.value = res.data
    } else {
      error.value = '加载对比数据失败'
    }
  } catch (e: any) {
    error.value = e?.message || '请求失败'
  } finally {
    loading.value = false
  }
}

// Module group collapse state
const expandedModules = ref<Set<string>>(new Set())

function toggleModule(key: string) {
  if (expandedModules.value.has(key)) {
    expandedModules.value.delete(key)
  } else {
    expandedModules.value.add(key)
  }
}

function isModuleExpanded(key: string) {
  return expandedModules.value.has(key)
}

// Auto expand all groups initially
function initExpandedState() {
  if (!data.value) return
  const types = ['new_abnormal', 'recovered', 'value_changed', 'new_items', 'removed_items'] as const
  types.forEach(type => {
    const groups = data.value?.diff_details[type] || []
    groups.forEach(g => {
      expandedModules.value.add(`${type}-${g.module_id}`)
    })
  })
}

onMounted(async () => {
  await loadData()
  initExpandedState()
})
</script>

<template>
  <div class="page-compare" v-loading="loading">
    <!-- Error state -->
    <div v-if="error" class="error-box">
      <div class="error-icon">❌</div>
      <div class="error-msg">{{ error }}</div>
      <el-button type="primary" @click="goBack" style="margin-top: 16px;">返回报告列表</el-button>
    </div>

    <!-- Data loaded -->
    <template v-else-if="data">
      <!-- Header -->
      <div class="compare-head">
        <div class="compare-meta">
          <h2>📊 报告对比</h2>
          <div class="sub">
            {{ data.report_a.target_name }} ·
            {{ formatTime(data.report_a.created_at) }} vs {{ formatTime(data.report_b.created_at) }}
          </div>
        </div>
        <div class="compare-actions">
          <div class="export-wrap" @click.stop>
            <el-button type="primary" @click="toggleExport">
              ⬇ 导出对比 ▾
            </el-button>
            <div v-if="showExportMenu" class="export-menu">
              <a :href="getExportUrl('md')" target="_blank">导出 Markdown</a>
              <a :href="getExportUrl('html')" target="_blank">导出 HTML</a>
            </div>
          </div>
          <el-button @click="viewReportA">查看基准报告</el-button>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </div>

      <!-- Report info table -->
      <el-card class="info-card">
        <table class="info-table">
          <tr>
            <th></th>
            <th>基准报告</th>
            <th>对比报告</th>
          </tr>
          <tr>
            <td class="col-label">报告ID</td>
            <td>{{ data.report_a.id }}</td>
            <td>{{ data.report_b.id }}</td>
          </tr>
          <tr>
            <td class="col-label">时间</td>
            <td>{{ formatTime(data.report_a.created_at) }}</td>
            <td>{{ formatTime(data.report_b.created_at) }}</td>
          </tr>
          <tr>
            <td class="col-label">总项数</td>
            <td>{{ data.report_a.total_items }}</td>
            <td>{{ data.report_b.total_items }}</td>
          </tr>
          <tr>
            <td class="col-label">正常</td>
            <td>{{ data.report_a.normal_count }}</td>
            <td>{{ data.report_b.normal_count }}</td>
          </tr>
          <tr>
            <td class="col-label">警告</td>
            <td>{{ data.report_a.warning_count }}</td>
            <td>{{ data.report_b.warning_count }}</td>
          </tr>
          <tr>
            <td class="col-label">严重</td>
            <td>{{ data.report_a.critical_count }}</td>
            <td>{{ data.report_b.critical_count }}</td>
          </tr>
        </table>
      </el-card>

      <!-- Diff summary cards -->
      <div class="diff-summary">
        <div class="diff-card dc-abnormal">
          <div class="icon">⚠️</div>
          <div class="count">{{ data.diff_summary.new_abnormal }}</div>
          <div class="label">新增异常</div>
        </div>
        <div class="diff-card dc-recovered">
          <div class="icon">✅</div>
          <div class="count">{{ data.diff_summary.recovered }}</div>
          <div class="label">恢复正常</div>
        </div>
        <div class="diff-card dc-changed">
          <div class="icon">📊</div>
          <div class="count">{{ data.diff_summary.value_changed }}</div>
          <div class="label">值变化</div>
        </div>
        <div class="diff-card dc-new">
          <div class="icon">➕</div>
          <div class="count">{{ data.diff_summary.new_items }}</div>
          <div class="label">新增检测项</div>
        </div>
        <div class="diff-card dc-removed">
          <div class="icon">➖</div>
          <div class="count">{{ data.diff_summary.removed_items }}</div>
          <div class="label">消失检测项</div>
        </div>
      </div>

      <!-- No diff -->
      <div v-if="totalDiffs === 0" class="no-diff">
        <div class="no-diff-icon">🎉</div>
        <div>两份报告无差异，所有检测项状态一致</div>
      </div>

      <!-- Diff sections -->
      <template v-else>
        <!-- New Abnormal -->
        <template v-if="data.diff_details.new_abnormal?.length">
          <div class="diff-section">
            <div class="diff-section-title">
              ⚠️ 新增异常
              <span class="badge badge-abnormal">{{ data.diff_summary.new_abnormal }}</span>
            </div>
            <div v-for="group in data.diff_details.new_abnormal" :key="'new_abnormal-' + group.module_id" class="module-group" :class="{ open: isModuleExpanded('new_abnormal-' + group.module_id) }">
              <div class="module-header" @click="toggleModule('new_abnormal-' + group.module_id)">
                <span class="module-toggle">▶</span>
                <span class="module-name">{{ group.module_name }}</span>
                <span class="module-count">{{ group.items.length }} 项</span>
              </div>
              <div class="module-body">
                <div v-for="(item, idx) in group.items" :key="idx" class="diff-row">
                  <div class="item-name tag-abnormal">{{ item.name }}</div>
                  <div class="item-value">{{ item.value_a }}</div>
                  <div class="item-value tag-abnormal">{{ item.value_b }}</div>
                  <div class="item-change tag-abnormal">{{ item.change_desc }}</div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- Recovered -->
        <template v-if="data.diff_details.recovered?.length">
          <div class="diff-section">
            <div class="diff-section-title">
              ✅ 恢复正常
              <span class="badge badge-recovered">{{ data.diff_summary.recovered }}</span>
            </div>
            <div v-for="group in data.diff_details.recovered" :key="'recovered-' + group.module_id" class="module-group" :class="{ open: isModuleExpanded('recovered-' + group.module_id) }">
              <div class="module-header" @click="toggleModule('recovered-' + group.module_id)">
                <span class="module-toggle">▶</span>
                <span class="module-name">{{ group.module_name }}</span>
                <span class="module-count">{{ group.items.length }} 项</span>
              </div>
              <div class="module-body">
                <div v-for="(item, idx) in group.items" :key="idx" class="diff-row">
                  <div class="item-name tag-recovered">{{ item.name }}</div>
                  <div class="item-value">{{ item.value_a }}</div>
                  <div class="item-value tag-recovered">{{ item.value_b }}</div>
                  <div class="item-change tag-recovered">{{ item.change_desc }}</div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- Value Changed -->
        <template v-if="data.diff_details.value_changed?.length">
          <div class="diff-section">
            <div class="diff-section-title">
              📊 值变化
              <span class="badge badge-changed">{{ data.diff_summary.value_changed }}</span>
            </div>
            <div v-for="group in data.diff_details.value_changed" :key="'value_changed-' + group.module_id" class="module-group" :class="{ open: isModuleExpanded('value_changed-' + group.module_id) }">
              <div class="module-header" @click="toggleModule('value_changed-' + group.module_id)">
                <span class="module-toggle">▶</span>
                <span class="module-name">{{ group.module_name }}</span>
                <span class="module-count">{{ group.items.length }} 项</span>
              </div>
              <div class="module-body">
                <div v-for="(item, idx) in group.items" :key="idx" class="diff-row">
                  <div class="item-name tag-changed">{{ item.name }}</div>
                  <div class="item-value">{{ item.value_a }}</div>
                  <div class="item-value">{{ item.value_b }}</div>
                  <div class="item-change tag-changed">{{ item.change_desc }}</div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- New Items -->
        <template v-if="data.diff_details.new_items?.length">
          <div class="diff-section">
            <div class="diff-section-title">
              ➕ 新增检测项
              <span class="badge badge-new">{{ data.diff_summary.new_items }}</span>
            </div>
            <div v-for="group in data.diff_details.new_items" :key="'new_items-' + group.module_id" class="module-group" :class="{ open: isModuleExpanded('new_items-' + group.module_id) }">
              <div class="module-header" @click="toggleModule('new_items-' + group.module_id)">
                <span class="module-toggle">▶</span>
                <span class="module-name">{{ group.module_name }}</span>
                <span class="module-count">{{ group.items.length }} 项</span>
              </div>
              <div class="module-body">
                <div v-for="(item, idx) in group.items" :key="idx" class="diff-row">
                  <div class="item-name tag-new">{{ item.name }}</div>
                  <div class="item-value">-</div>
                  <div class="item-value">{{ item.value_b }}</div>
                  <div class="item-change tag-new">新增检测项</div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- Removed Items -->
        <template v-if="data.diff_details.removed_items?.length">
          <div class="diff-section">
            <div class="diff-section-title">
              ➖ 消失检测项
              <span class="badge badge-removed">{{ data.diff_summary.removed_items }}</span>
            </div>
            <div v-for="group in data.diff_details.removed_items" :key="'removed_items-' + group.module_id" class="module-group" :class="{ open: isModuleExpanded('removed_items-' + group.module_id) }">
              <div class="module-header" @click="toggleModule('removed_items-' + group.module_id)">
                <span class="module-toggle">▶</span>
                <span class="module-name">{{ group.module_name }}</span>
                <span class="module-count">{{ group.items.length }} 项</span>
              </div>
              <div class="module-body">
                <div v-for="(item, idx) in group.items" :key="idx" class="diff-row">
                  <div class="item-name tag-removed">{{ item.name }}</div>
                  <div class="item-value">{{ item.value_a }}</div>
                  <div class="item-value">-</div>
                  <div class="item-change tag-removed">消失检测项</div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </template>
    </template>
  </div>
</template>

<style scoped lang="scss">
.page-compare {
  padding: 0 0 40px;
}

.compare-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
  flex-wrap: wrap;
  gap: 12px;
}

.compare-meta h2 {
  font-size: 20px;
  color: $gray-900;
  margin-bottom: 4px;
}

.compare-meta .sub {
  font-size: 13px;
  color: $gray-500;
}

.compare-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.export-wrap {
  position: relative;
}

.export-menu {
  position: absolute;
  right: 0;
  top: 44px;
  background: #fff;
  border: 1px solid $gray-200;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  z-index: 10;

  a {
    display: block;
    padding: 10px 20px;
    font-size: 14px;
    color: $gray-700;
    text-decoration: none;

    &:hover {
      background: $gray-50;
    }
  }
}

.info-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
}

.info-table {
  width: 100%;
  border-collapse: collapse;

  th {
    background: $gray-50;
    padding: 10px 16px;
    text-align: left;
    font-weight: 600;
    color: $gray-700;
    border-bottom: 1px solid $gray-200;
  }

  td {
    padding: 10px 16px;
    border-bottom: 1px solid $gray-100;
    font-size: 14px;
    color: $gray-900;
  }

  tr:last-child td {
    border-bottom: none;
  }

  .col-label {
    width: 100px;
    color: $gray-500;
    font-weight: 500;
  }
}

.diff-summary {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  margin-bottom: 24px;
}

.diff-card {
  background: #fff;
  border-radius: 12px;
  padding: 18px;
  text-align: center;
  border: 1px solid $gray-200;

  .icon {
    font-size: 20px;
    margin-bottom: 4px;
  }

  .count {
    font-size: 28px;
    font-weight: 700;
  }

  .label {
    font-size: 13px;
    color: $gray-500;
    margin-top: 4px;
  }
}

.dc-abnormal {
  border-color: #ffccc7;
  background: #fff0f0;
  .count { color: #cf1322; }
}
.dc-recovered {
  border-color: #b7eb8f;
  background: #f0fff0;
  .count { color: #389e0d; }
}
.dc-changed {
  border-color: #ffe58f;
  background: #fffbe6;
  .count { color: #d48806; }
}
.dc-new {
  border-color: #91d5ff;
  background: #e6f7ff;
  .count { color: #096dd9; }
}
.dc-removed {
  border-color: #d9d9d9;
  background: #f5f5f5;
  .count { color: #8c8c8c; }
}

.no-diff {
  text-align: center;
  padding: 40px 20px;
  color: $gray-500;
  font-size: 15px;

  .no-diff-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }
}

.error-box {
  text-align: center;
  padding: 40px 20px;

  .error-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  .error-msg {
    color: $red;
    font-size: 16px;
    font-weight: 600;
  }
}

.diff-section {
  margin-bottom: 20px;
}

.diff-section-title {
  font-size: 16px;
  font-weight: 700;
  color: $gray-900;
  margin: 0 0 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 8px;
  border-bottom: 2px solid $gray-200;
}

.badge {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 600;
}

.badge-abnormal { background: #fff0f0; color: #cf1322; }
.badge-recovered { background: #f0fff0; color: #389e0d; }
.badge-changed { background: #fffbe6; color: #d48806; }
.badge-new { background: #e6f7ff; color: #096dd9; }
.badge-removed { background: #f5f5f5; color: #8c8c8c; }

.module-group {
  background: #fff;
  border-radius: 12px;
  border: 1px solid $gray-200;
  margin-bottom: 10px;
  overflow: hidden;

  .module-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 18px;
    cursor: pointer;
    user-select: none;

    &:hover {
      background: $gray-50;
    }
  }

  .module-toggle {
    font-size: 12px;
    color: $gray-500;
    transition: transform 0.2s;
    flex-shrink: 0;
  }

  &.open .module-toggle {
    transform: rotate(90deg);
  }

  .module-name {
    font-weight: 700;
    color: $gray-900;
    flex: 1;
  }

  .module-count {
    font-size: 12px;
    color: $gray-500;
  }

  .module-body {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.35s ease;
  }

  &.open .module-body {
    max-height: 5000px;
  }
}

.diff-row {
  display: grid;
  grid-template-columns: 2fr 1.2fr 1.2fr 1.5fr;
  gap: 12px;
  padding: 10px 18px;
  border-top: 1px solid $gray-100;
  font-size: 14px;
  align-items: center;

  .item-name {
    font-weight: 600;
    color: $gray-900;
  }

  .item-value {
    font-weight: 500;
    color: $gray-700;
  }

  .item-change {
    font-size: 13px;
    color: $gray-500;
  }
}

.tag-abnormal { color: #cf1322; font-weight: 600; }
.tag-recovered { color: #389e0d; font-weight: 600; }
.tag-changed { color: #d48806; font-weight: 600; }
.tag-new { color: #096dd9; font-weight: 600; }
.tag-removed { color: #8c8c8c; }

@media screen and (max-width: 1024px) {
  .diff-summary {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .compare-head {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .compare-meta h2 {
    font-size: 16px;
  }

  .compare-actions {
    width: 100%;
  }

  .diff-summary {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .diff-card {
    padding: 12px;
    .count { font-size: 22px; }
  }

  .info-table td,
  .info-table th {
    padding: 8px 10px;
    font-size: 13px;
  }

  .diff-row {
    grid-template-columns: 1fr 1fr;
    gap: 4px;
    padding: 8px 14px;
    font-size: 13px;

    .item-value:last-of-type {
      display: none;
    }
  }

  .module-header {
    padding: 10px 14px;
  }

  .module-name {
    font-size: 14px;
    word-break: break-word;
  }

  .export-menu {
    position: fixed;
    left: 12px;
    right: 12px;
    top: auto;
    bottom: 12px;
    border-radius: 12px;
  }
}

@media screen and (max-width: 480px) {
  .diff-summary {
    grid-template-columns: 1fr 1fr;
    gap: 6px;
  }

  .diff-card {
    padding: 10px;
    .count { font-size: 18px; }
    .icon { font-size: 16px; }
  }

  .diff-row {
    padding: 7px 12px;
    font-size: 12px;
  }

  .module-header {
    padding: 8px 12px;
  }

  .module-name {
    font-size: 13px;
  }
}
</style>