<template>
  <div class="app-container">
    <el-row :gutter="20" class="mb8">
      <el-col :span="24">
        <el-form :model="queryParams" inline>
          <!-- 业务说明: 范围切换 — 统计数据按三种业务维度筛选: 1=直属单位(本级管辖范围)，2=下级水行政(下级水利部门)，3=流域机构(全流域汇总) -->
          <el-form-item label="查询范围" prop="dataFrom">
            <el-select v-model="queryParams.dataFrom" placeholder="查询范围" clearable style="width: 240px" @change="handleRangeChange">
              <el-option label="直属单位" value="1" />
              <el-option label="下级水行政" value="2" />
              <el-option label="流域机构" value="3" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb8">
      <el-col :span="4" v-for="card in statCards" :key="card.key">
        <el-card shadow="hover">
          <template #header><span>{{ card.label }}</span></template>
          <div class="stat-card">
            <div class="stat-value" :style="{ color: card.color }">{{ summaryData[card.key] ?? 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb8">
      <!-- 业务说明: 事故类别分布(饼图) — 按事故的业务分类维度(如工程事故、设备事故等)展示各类别占比 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header><span>事故类别分布</span></template>
          <div ref="pieChartRef" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <!-- 业务说明: 事故等级统计(柱状图) — 按一般/较大/重大/特别重大四级展示数量分布，用于快速掌握事故严重程度构成 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header><span>事故等级统计</span></template>
          <div ref="barChartRef" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 业务说明: 事故趋势(折线图) — 按月份统计事故发生数量的时间序列，用于分析事故发生的周期性规律和趋势变化 -->
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header><span>事故趋势（按月份）</span></template>
          <div ref="trendChartRef" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="AcciStat">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { getAcciSummary, getAcciByCategory, listObjAcci } from "@/api/slaj/acci"
import * as echarts from "echarts"

const queryParams = reactive({ dataFrom: undefined })

function handleRangeChange() {
  fetchSummary()
  fetchCategory()
}

// 业务说明: 统计卡片 — 按事故严重程度划分为四个等级(一般/较大/重大/特别重大)，对应不同颜色标识
const statCards = [
  { key: 'total', label: '事故总数', color: '#409eff' },
  { key: 'general', label: '一般事故', color: '#67c23a' },
  { key: 'larger', label: '较大事故', color: '#e6a23c' },
  { key: 'major', label: '重大事故', color: '#f56c6c' },
  { key: 'special', label: '特别重大事故', color: '#b22222' },
]

const summaryData = ref({})
const pieChartRef = ref(null)
const barChartRef = ref(null)
const trendChartRef = ref(null)

function fetchSummary() {
  getAcciSummary(queryParams).then(res => {
    summaryData.value = res.data ?? {}
    nextTick(() => {
      initBarChart()
      initTrendChart()
    })
  })
}

function fetchCategory() {
  getAcciByCategory(queryParams).then(res => {
    const data = res.data ?? {}
    const pieData = Object.entries(data).map(([name, value]) => ({ name, value }))
    nextTick(() => initPieChart(pieData))
  })
}

/** 业务说明: 初始化事故类别分布饼图 — 按事故业务类别(如工程、设备、管理等)统计各维度占比 */
function initPieChart(data) {
  if (!pieChartRef.value) return
  const chart = echarts.init(pieChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { orient: 'vertical', left: 'left' },
    series: [{
      name: '事故类别', type: 'pie', radius: '50%',
      data: data.length > 0 ? data : [{ name: '暂无数据', value: 1 }],
      emphasis: { itemStyle: { shadowBlur: 10 } }
    }]
  })
}

/** 业务说明: 初始化事故等级统计柱状图 — 按一般/较大/重大/特别重大四个等级维度展示数量，柱状颜色从绿到红逐级加深 */
function initBarChart() {
  if (!barChartRef.value) return
  const chart = echarts.init(barChartRef.value)
  const levels = ['一般事故', '较大事故', '重大事故', '特别重大事故']
  const keys = ['general', 'larger', 'major', 'special']
  const data = keys.map(k => summaryData.value[k] ?? 0)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: levels },
    yAxis: { type: 'value' },
    series: [{
      name: '事故数量', type: 'bar', barWidth: '50%', data,
      itemStyle: { color: (p) => ['#67c23a', '#e6a23c', '#f56c6c', '#b22222'][p.dataIndex] }
    }]
  })
}

/** 业务说明: 初始化事故趋势折线图 — 按月统计事故发生数量，前端汇总所有事故的发生时间并归月，展示各月事故数量趋势，辅助分析事故高发时段 */
function initTrendChart() {
  if (!trendChartRef.value) return
  listObjAcci({ pageNum: 1, pageSize: 1000 }).then(res => {
    const list = res.rows || []
    const monthMap = {}
    list.forEach(item => {
      if (item.occuTime) {
        const mon = item.occuTime.substring(0, 7)
        monthMap[mon] = (monthMap[mon] || 0) + 1
      }
    })
    const sorted = Object.entries(monthMap).sort(([a], [b]) => a.localeCompare(b))
    const chart = echarts.init(trendChartRef.value)
    chart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', data: sorted.map(([m]) => m), axisLabel: { rotate: 45 } },
      yAxis: { type: 'value' },
      series: [{
        name: '事故数量', type: 'line', smooth: true,
        data: sorted.map(([, v]) => v),
        areaStyle: { color: 'rgba(64,158,255,0.1)' },
        itemStyle: { color: '#409eff' }
      }]
    })
  })
}

onMounted(() => {
  fetchSummary()
  fetchCategory()
})
</script>

<style scoped>
.stat-card { text-align: center; padding: 20px 0; }
.stat-value { font-size: 32px; font-weight: bold; margin-bottom: 10px; }
</style>
