<template>
  <div class="statistics-page">
    <!-- 顶部：时间筛选 -->
    <el-card class="search-card">
      <el-form :inline="true">
        <el-form-item label="统计时间">
          <el-button-group class="date-shortcuts">
            <el-button :type="activeShortcut === 7 ? 'primary' : ''" @click="setDateRange(7)">最近7天</el-button>
            <el-button :type="activeShortcut === 30 ? 'primary' : ''" @click="setDateRange(30)">最近30天</el-button>
            <el-button :type="activeShortcut === 90 ? 'primary' : ''" @click="setDateRange(90)">最近90天</el-button>
          </el-button-group>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="activeShortcut = 0"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 中部：隐患类型分布（多折线） + 隐患整改统计（分组柱状） -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header><span>隐患类型分布</span></template>
          <div ref="chartTypeRef" class="chart" v-loading="typeLoading"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header><span>隐患整改统计</span></template>
          <div ref="chartStatusRef" class="chart" v-loading="statusLoading"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部：各区域隐患统计 -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header><span>各区域隐患统计</span></template>
          <div ref="chartRegionRef" class="chart" v-loading="regionLoading"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import {
  getHazardStatisticsTypeTimeline,
  getHazardStatisticsStatusTimeline,
  getHazardStatisticsByRegion
} from '@/api/pipeNetwork/hazard'
import { getDicts } from '@/api/system/dict/data'

const chartTypeRef = ref(null)
const chartStatusRef = ref(null)
const chartRegionRef = ref(null)
const typeLoading = ref(false)
const statusLoading = ref(false)
const regionLoading = ref(false)

const hazardTypeDict = ref([])
const hazardStatusDict = ref([])
const dateRange = ref([])
const activeShortcut = ref(7)

function formatDateStr(d) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}
function daysAgo(n) {
  const e = new Date()
  const s = new Date()
  s.setDate(s.getDate() - n)
  return [formatDateStr(s), formatDateStr(e)]
}
function setDateRange(days) {
  activeShortcut.value = days
  dateRange.value = daysAgo(days)
  loadAllCharts()
}
// 默认选中最近7天
dateRange.value = daysAgo(7)

const TYPE_COLORS = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
const STATUS_BAR_COLORS = [
  ['#fac858', '#d4a017'],  // 待整改 橙
  ['#409eff', '#1a6dd4'],  // 整改中 蓝
  ['#52c41a', '#2d8c0e'],  // 已整改 绿
  ['#ee6666', '#c93737'],
  ['#73c0de', '#4a9ec9'],
  ['#9a60b4', '#7a3d9a']
]

function getDictLabel(dict, value) {
  if (!dict || !dict.length) return value
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}

function getDateParams() {
  if (dateRange.value && dateRange.value.length === 2) {
    return { startDate: dateRange.value[0], endDate: dateRange.value[1] }
  }
  return {}
}

async function loadDicts() {
  try {
    const [typeRes, statusRes] = await Promise.all([
      getDicts('hazard_type'),
      getDicts('hazard_status')
    ])
    hazardTypeDict.value = typeRes.data || []
    hazardStatusDict.value = statusRes.data || []
  } catch (e) {
    console.error('加载字典失败', e)
  }
}

// --- 图表管理 ---
let chartInstances = []
let resizeHandlers = []

function registerChart(instance) {
  chartInstances.push(instance)
  const handler = () => instance.resize()
  resizeHandlers.push(handler)
  window.addEventListener('resize', handler)
}

function disposeCharts() {
  chartInstances.forEach(c => { try { c.dispose() } catch { /* ignore */ } })
  chartInstances = []
  resizeHandlers.forEach(h => window.removeEventListener('resize', h))
  resizeHandlers = []
}

async function initTypeChart() {
  typeLoading.value = true
  try {
    await nextTick()
    const echartsModule = await import('echarts')
    const echarts = echartsModule.default || echartsModule
    const res = await getHazardStatisticsTypeTimeline(getDateParams())
    const payload = res.data || {}
    const categories = payload.categories || []
    const rawSeries = payload.series || []
    if (!chartTypeRef.value) return

    const c = echarts.init(chartTypeRef.value)
    c.setOption({
      tooltip: { trigger: 'axis' },
      legend: {
        data: rawSeries.map(s => getDictLabel(hazardTypeDict, s.name)),
        bottom: 0,
        type: 'scroll'
      },
      grid: { left: '3%', right: '6%', top: 20, bottom: 40, containLabel: true },
      xAxis: {
        type: 'category',
        data: categories,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#ccc' } },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: rawSeries.map((s, i) => ({
        type: 'line',
        name: getDictLabel(hazardTypeDict, s.name),
        data: s.data || [],
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 2 },
        itemStyle: { color: TYPE_COLORS[i % TYPE_COLORS.length] }
      }))
    })
    registerChart(c)
  } catch (e) {
    console.error('隐患类型分布图表加载失败', e)
  } finally {
    typeLoading.value = false
  }
}

async function initStatusChart() {
  statusLoading.value = true
  try {
    await nextTick()
    const echartsModule = await import('echarts')
    const echarts = echartsModule.default || echartsModule
    const res = await getHazardStatisticsStatusTimeline(getDateParams())
    const payload = res.data || {}
    const categories = payload.categories || []
    const rawSeries = payload.series || []
    if (!chartStatusRef.value) return

    const c = echarts.init(chartStatusRef.value)
    c.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: {
        data: rawSeries.map(s => getDictLabel(hazardStatusDict, s.name)),
        bottom: 0,
        type: 'scroll'
      },
      grid: { left: '3%', right: '4%', top: 20, bottom: 40, containLabel: true },
      xAxis: {
        type: 'category',
        data: categories,
        axisLine: { lineStyle: { color: '#ccc' } },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: rawSeries.map((s, i) => {
        const [c1, c2] = STATUS_BAR_COLORS[i % STATUS_BAR_COLORS.length]
        return {
          type: 'bar',
          name: getDictLabel(hazardStatusDict, s.name),
          data: s.data || [],
          barWidth: 16,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: c1 },
              { offset: 1, color: c2 }
            ]),
            borderRadius: [4, 4, 0, 0]
          }
        }
      })
    })
    registerChart(c)
  } catch (e) {
    console.error('隐患整改统计图表加载失败', e)
  } finally {
    statusLoading.value = false
  }
}

async function initRegionChart() {
  regionLoading.value = true
  try {
    await nextTick()
    const echartsModule = await import('echarts')
    const echarts = echartsModule.default || echartsModule
    const res = await getHazardStatisticsByRegion(getDateParams())
    const rawData = (res.data || []).sort((a, b) => b.value - a.value)
    if (!chartRegionRef.value) return

    const c = echarts.init(chartRegionRef.value)
    c.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: '3%', right: '4%', top: 20, bottom: 10, containLabel: true },
      xAxis: {
        type: 'category',
        data: rawData.map(d => d.name),
        axisLine: { lineStyle: { color: '#ccc' } },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: [{
        type: 'bar',
        data: rawData.map(d => ({
          value: d.value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#409eff' }, { offset: 1, color: '#a0d2ff' }
            ]),
            borderRadius: [4, 4, 0, 0]
          }
        })),
        barWidth: 32,
        label: { show: true, position: 'top', color: '#333' }
      }]
    })
    registerChart(c)
  } catch (e) {
    console.error('各区域隐患统计图表加载失败', e)
  } finally {
    regionLoading.value = false
  }
}

function loadAllCharts() {
  disposeCharts()
  initTypeChart()
  initStatusChart()
  initRegionChart()
}

function handleSearch() {
  loadAllCharts()
}

onMounted(async () => {
  await loadDicts()
  loadAllCharts()
})

onBeforeUnmount(() => {
  disposeCharts()
})
</script>

<style scoped>
.statistics-page { padding: 16px; min-height: 100%; background: #f0f2f5; }

.search-card { margin-bottom: 16px; }
.date-shortcuts { margin-right: 12px; }

.chart-row { margin-bottom: 16px; }
.chart-card { border-radius: 8px; }
.chart { width: 100%; height: 380px; }
</style>
