<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">报表统计</h2>
      <el-select v-model="selectedProject" placeholder="选择项目生成报告" clearable style="width: 260px">
        <el-option v-for="p in projects" :key="p.id" :label="p.name" :value="p.id" />
      </el-select>
      <el-button-group v-if="selectedProject">
        <el-button type="primary" @click="downloadReport('docx')">
          <el-icon><Download /></el-icon>Word
        </el-button>
        <el-button type="primary" @click="downloadReport('excel')">
          <el-icon><Download /></el-icon>Excel
        </el-button>
        <el-button type="primary" @click="openPdfPreview">
          <el-icon><Download /></el-icon>PDF预览
        </el-button>
      </el-button-group>
    </div>

    <el-row :gutter="16" class="chart-row">
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">数据分级分布</div>
          <v-chart class="chart" :option="levelOption" autoresize />
        </div>
      </el-col>
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">项目进度</div>
          <v-chart class="chart" :option="projectOption" autoresize />
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="chart-row">
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">识别来源占比</div>
          <v-chart class="chart" :option="sourceOption" autoresize />
        </div>
      </el-col>
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">分级数量统计</div>
          <v-chart class="chart" :option="levelBarOption" autoresize />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { Download } from '@element-plus/icons-vue'
import { getProjects } from '@/api/project'
import { getReportStats, downloadReport as doDownload } from '@/api/report'

use([CanvasRenderer, PieChart, BarChart, TooltipComponent, LegendComponent, GridComponent])

const selectedProject = ref<number | undefined>(undefined)
const projects = ref<any[]>([])

const reportStats = ref<any>(null)
const projectProgress = ref<any[]>([])

const levelColors = ['#67c23a', '#409eff', '#e6a23c', '#f56c6c', '#909399']

const levelOption = computed(() => {
  const dist = reportStats.value?.level_distribution || []
  return {
    tooltip: { trigger: 'item' },
    legend: { bottom: '0%', left: 'center' },
    color: levelColors,
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
        label: { show: false },
        data: dist.map((item: any) => ({
          value: item.count,
          name: `${item.code} ${item.name}`,
        })),
      },
    ],
  }
})

const projectOption = computed(() => ({
  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: { type: 'category', data: projectProgress.value.map((p: any) => p.name.slice(0, 8)) },
  yAxis: { type: 'value', max: 100 },
  series: [
    {
      type: 'bar',
      data: projectProgress.value.map((p: any) => p.progress),
      itemStyle: { borderRadius: [4, 4, 0, 0], color: '#409eff' },
      label: { show: true, position: 'top', formatter: '{c}%' },
    },
  ],
}))

const sourceOption = computed(() => {
  const total = reportStats.value?.total || 1
  const auto = reportStats.value?.auto || 0
  const manual = reportStats.value?.manual || 0
  return {
    tooltip: { trigger: 'item' },
    legend: { bottom: '0%', left: 'center' },
    color: ['#e6a23c', '#67c23a'],
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
        label: { show: false },
        data: [
          { value: auto, name: '自动识别' },
          { value: manual, name: '人工打标' },
        ],
      },
    ],
  }
})

const levelBarOption = computed(() => {
  const dist = reportStats.value?.level_distribution || []
  return {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dist.map((item: any) => `${item.code} ${item.name}`) },
    yAxis: { type: 'value' },
    series: [
      {
        type: 'bar',
        data: dist.map((item: any) => item.count),
        itemStyle: { borderRadius: [4, 4, 0, 0], color: (params: any) => levelColors[params.dataIndex] || '#409eff' },
        label: { show: true, position: 'top' },
      },
    ],
  }
})

function downloadReport(format: string) {
  if (!selectedProject.value) return
  doDownload(selectedProject.value, format)
}

function openPdfPreview() {
  if (!selectedProject.value) return
  window.open(`/report-preview.html?projectId=${selectedProject.value}`, '_blank')
}

async function fetchProjects() {
  try {
    const res: any = await getProjects({ page: 1, page_size: 100 })
    projects.value = res?.data || []
    projectProgress.value = (res?.data || []).map((p: any) => ({
      name: p.name,
      progress: p.stats?.total ? Math.round((p.stats.reviewed / p.stats.total) * 100) : 0,
    }))
  } catch (e) {
    // ignore
  }
}

async function fetchStats() {
  try {
    const res: any = await getReportStats()
    reportStats.value = res?.data || null
  } catch (e) {
    // ignore
  }
}

onMounted(() => {
  fetchProjects()
  fetchStats()
})
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .page-title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    margin-right: auto;
  }
}

.chart-row {
  margin-bottom: 16px;
}

.chart-card {
  padding: 20px;
  background: #fff;
  border-radius: 8px;

  .chart-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #303133;
  }

  .chart {
    width: 100%;
    height: 300px;
  }
}
</style>
