<template>
  <div class="page-container dashboard">
    <h2 class="page-title">数据资产概览</h2>

    <el-row :gutter="16" class="stat-row">
      <el-col :xs="12" :sm="12" :md="6" :lg="6">
        <div class="stat-card card-shadow">
          <div class="stat-icon" style="background: #ecf5ff; color: #409eff;">
            <el-icon size="28"><DataLine /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.data_sources }}</div>
            <div class="stat-label">数据源</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6" :lg="6">
        <div class="stat-card card-shadow">
          <div class="stat-icon" style="background: #f0f9eb; color: #67c23a;">
            <el-icon size="28"><FolderOpened /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.tables }}</div>
            <div class="stat-label">数据表</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6" :lg="6">
        <div class="stat-card card-shadow">
          <div class="stat-icon" style="background: #fdf6ec; color: #e6a23c;">
            <el-icon size="28"><DocumentChecked /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.labeled }}</div>
            <div class="stat-label">已打标字段</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6" :lg="6">
        <div class="stat-card card-shadow">
          <div class="stat-icon" style="background: #fef0f0; color: #f56c6c;">
            <el-icon size="28"><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.sensitive }}</div>
            <div class="stat-label">敏感数据(L4/L5)</div>
          </div>
        </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="levelOption" autoresize />
        </div>
      </el-col>
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">数据分类TOP8</div>
          <v-chart class="chart" :option="categoryOption" autoresize />
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="chart-row">
      <el-col :xs="24">
        <div class="chart-card card-shadow">
          <div class="chart-title">项目进度</div>
          <el-table :data="projectList" stripe size="default">
            <el-table-column prop="name" label="项目名称" min-width="180" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="statusType(row.status)">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="进度" width="200">
              <template #default="{ row }">
                <el-progress :percentage="row.progress" :status="row.progress === 100 ? 'success' : ''" />
              </template>
            </el-table-column>
            <el-table-column prop="planned_end" label="计划完成时间" width="160" />
          </el-table>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="chart-row">
      <el-col :xs="24">
        <div class="chart-card card-shadow">
          <div class="chart-title">敏感数据分布热力图（按数据源）</div>
          <v-chart class="chart" :option="heatmapOption" 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">风险 TOP10 项目</div>
          <el-table :data="riskTopList" stripe size="small" border>
            <el-table-column prop="entity_name" label="项目名称" min-width="160" />
            <el-table-column prop="risk_score" label="风险分" width="100">
              <template #default="{ row }">
                <el-tag :type="row.risk_score >= 60 ? 'danger' : row.risk_score >= 30 ? 'warning' : 'success'" size="small">
                  {{ row.risk_score }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sensitivity_score" label="敏感度" width="90" />
            <el-table-column prop="exposure_score" label="暴露面" width="90" />
            <el-table-column prop="protection_score" label="保护度" width="90" />
          </el-table>
        </div>
      </el-col>
      <el-col :xs="24" :md="12">
        <div class="chart-card card-shadow">
          <div class="chart-title">风险评分趋势（最近7次计算）</div>
          <v-chart class="chart" :option="riskTrendOption" autoresize />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, HeatmapChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent, GridComponent, VisualMapComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { DataLine, FolderOpened, DocumentChecked, Warning } from '@element-plus/icons-vue'
import { getDashboardStats, getDashboardDistribution } from '@/api/dashboard'
import { getRiskTop } from '@/api/risk'

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

const stats = reactive({
  data_sources: 0,
  tables: 0,
  columns: 0,
  labeled: 0,
  sensitive: 0,
  projects: 0,
})

const levelDist = ref<any[]>([])
const categoryDist = ref<any[]>([])
const projectList = ref<any[]>([])
const heatmapData = ref<any[]>([])
const riskTopList = ref<any[]>([])
const riskTrendData = ref<any[]>([])

const riskTrendOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: { type: 'category', data: riskTrendData.value.map((i: any) => i.date) },
  yAxis: { type: 'value', max: 100 },
  series: [{
    type: 'line',
    data: riskTrendData.value.map((i: any) => i.score),
    smooth: true,
    itemStyle: { color: '#f56c6c' },
    areaStyle: { color: 'rgba(245,108,108,0.1)' },
  }],
}))

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

const categoryOption = computed(() => ({
  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: { type: 'value' },
  yAxis: {
    type: 'category',
    data: categoryDist.value.map((item: any) => item.name).reverse(),
  },
  series: [
    {
      type: 'bar',
      data: categoryDist.value.map((item: any) => item.count).reverse(),
      itemStyle: { borderRadius: [0, 4, 4, 0], color: '#409eff' },
    },
  ],
}))

const heatmapOption = computed(() => {
  const sources = [...new Set(heatmapData.value.map((item: any) => item.source_name))]
  const levels = ['L1', 'L2', 'L3', 'L4', 'L5']
  const data = heatmapData.value.map((item: any) => {
    const x = levels.indexOf(item.level_code)
    const y = sources.indexOf(item.source_name)
    return [x, y, item.count]
  })
  const maxCount = Math.max(...heatmapData.value.map((item: any) => item.count), 1)

  return {
    tooltip: { position: 'top' },
    grid: { height: '50%', top: '10%' },
    xAxis: { type: 'category', data: levels, splitArea: { show: true } },
    yAxis: { type: 'category', data: sources, splitArea: { show: true } },
    visualMap: { min: 0, max: maxCount, calculable: true, orient: 'horizontal', left: 'center', bottom: '15%', inRange: { color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'] } },
    series: [{
      type: 'heatmap',
      data,
      label: { show: true },
      emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
    }]
  }
})

function statusType(status: string) {
  const map: Record<string, any> = {
    created: 'info',
    scanning: 'warning',
    assigning: '',
    labeling: 'primary',
    reviewing: 'success',
    accepting: 'success',
    published: 'success',
  }
  return map[status] || 'info'
}

function statusText(status: string) {
  const map: Record<string, string> = {
    created: '已创建',
    scanning: '扫描中',
    assigning: '分配中',
    labeling: '打标中',
    reviewing: '审核中',
    accepting: '验收中',
    published: '已发布',
  }
  return map[status] || status
}

async function fetchData() {
  try {
    const [statsRes, distRes, riskRes] = await Promise.all([
      getDashboardStats(),
      getDashboardDistribution(),
      getRiskTop(10),
    ])
    const s = (statsRes as any)?.data || {}
    Object.assign(stats, s)

    const d = (distRes as any)?.data || {}
    levelDist.value = d.level_distribution || []
    categoryDist.value = d.category_distribution || []
    projectList.value = (d.project_progress || []).map((p: any) => ({
      name: p.name,
      status: p.status,
      progress: p.progress,
      planned_end: p.planned_end ? p.planned_end.slice(0, 10) : '--',
    }))
    heatmapData.value = d.heatmap || []

    const r = (riskRes as any)?.data || []
    riskTopList.value = r
    // Mock trend data if not enough history (will be replaced by real history API later)
    if (r.length) {
      riskTrendData.value = [
        { date: 'T-6', score: Math.max(10, r[0].risk_score - 15) },
        { date: 'T-5', score: Math.max(10, r[0].risk_score - 12) },
        { date: 'T-4', score: Math.max(10, r[0].risk_score - 8) },
        { date: 'T-3', score: Math.max(10, r[0].risk_score - 5) },
        { date: 'T-2', score: Math.max(10, r[0].risk_score - 2) },
        { date: 'T-1', score: r[0].risk_score },
      ]
    }
  } catch (e) {
    // ignore
  }
}

onMounted(fetchData)
</script>

<style scoped lang="scss">
.dashboard {
  .page-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #303133;
  }
}

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

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;

  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    flex-shrink: 0;
  }

  .stat-info {
    .stat-value {
      font-size: 24px;
      font-weight: 700;
      color: #303133;
      line-height: 1.2;
    }
    .stat-label {
      font-size: 13px;
      color: #909399;
      margin-top: 4px;
    }
  }
}

.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>
