<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header><div class="card-header"><span>WCO 水控工程管理</span></div></template>
      <el-row :gutter="16">
        <el-col :xs="24" :sm="6">
          <el-card shadow="never" class="nav-card" @click="$router.push('/slgc/wco/dike')">
            <div class="nav-item"><el-icon :size="36" color="#409EFF"><TrendCharts /></el-icon><div class="nav-label">堤防</div><div class="nav-count">{{ counts.dike }}条</div></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-card shadow="never" class="nav-card" @click="$router.push('/slgc/wco/pust')">
            <div class="nav-item"><el-icon :size="36" color="#67C23A"><Switch /></el-icon><div class="nav-label">水闸</div><div class="nav-count">{{ counts.pust }}座</div></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-card shadow="never" class="nav-card" @click="$router.push('/slgc/wco/reservoir')">
            <div class="nav-item"><el-icon :size="36" color="#E6A23C"><DataAnalysis /></el-icon><div class="nav-label">水库</div><div class="nav-count">{{ counts.reservoir }}座</div></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-card shadow="never" class="nav-card" @click="$router.push('/slgc/wco/waga')">
            <div class="nav-item"><el-icon :size="36" color="#F56C6C"><Setting /></el-icon><div class="nav-label">泵站</div><div class="nav-count">{{ counts.waga }}座</div></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="mt-16">
        <el-col :span="12">
          <el-card shadow="never">
            <template #header><div class="card-header"><span>工程类型分布</span></div></template>
            <div ref="pieChartRef" style="height:260px;width:100%"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <template #header><div class="card-header"><span>运行状态统计</span></div></template>
            <div ref="barChartRef" style="height:260px;width:100%"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup name="WcoIndex">
import { TrendCharts, Switch, DataAnalysis, Setting } from '@element-plus/icons-vue'
import { getWcoDikeList, getWcoPustList, getWcoReservoirList, getWcoWagaList } from '@/api/slgc/wco/index'
import * as echarts from 'echarts'

const pieChartRef = ref(null)
const barChartRef = ref(null)
const counts = reactive({ dike: 0, pust: 0, reservoir: 0, waga: 0 })

let pieChart = null
let barChart = null

function initCharts() {
  pieChart = echarts.init(pieChartRef.value)
  pieChart.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    series: [{
      type: 'pie', radius: ['40%', '70%'],
      itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
      label: { show: true, formatter: '{b}\n{d}%' },
      data: [
        { value: counts.dike, name: '堤防', itemStyle: { color: '#409EFF' } },
        { value: counts.pust, name: '水闸', itemStyle: { color: '#67C23A' } },
        { value: counts.reservoir, name: '水库', itemStyle: { color: '#E6A23C' } },
        { value: counts.waga, name: '泵站', itemStyle: { color: '#F56C6C' } }
      ]
    }]
  })

  barChart = echarts.init(barChartRef.value)
  barChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: ['正常运行', '维修', '停用'] },
    yAxis: { type: 'value' },
    series: [{
      type: 'bar', barWidth: '40%',
      data: [
        { value: counts.normal, itemStyle: { color: '#67C23A' } },
        { value: counts.repair, itemStyle: { color: '#E6A23C' } },
        { value: counts.stopped, itemStyle: { color: '#F56C6C' } }
      ],
      label: { show: true, position: 'top' }
    }]
  })

  window.addEventListener('resize', handleResize)
}

function handleResize() {
  pieChart?.resize()
  barChart?.resize()
}

function loadCounts() {
  const allItems = []
  Promise.all([
    getWcoDikeList({ pageSize: 9999, pageNum: 1 }),
    getWcoPustList({ pageSize: 9999, pageNum: 1 }),
    getWcoReservoirList({ pageSize: 9999, pageNum: 1 }),
    getWcoWagaList({ pageSize: 9999, pageNum: 1 })
  ]).then(([dikeRes, pustRes, reservoirRes, wagaRes]) => {
    counts.dike = dikeRes.total || (dikeRes.rows?.length ?? 0)
    counts.pust = pustRes.total || (pustRes.rows?.length ?? 0)
    counts.reservoir = reservoirRes.total || (reservoirRes.rows?.length ?? 0)
    counts.waga = wagaRes.total || (wagaRes.rows?.length ?? 0)

    const dikeList = dikeRes.rows || []
    const pustList = pustRes.rows || []
    const reservoirList = reservoirRes.rows || []
    const wagaList = wagaRes.rows || []
    allItems.push(...dikeList, ...pustList, ...reservoirList, ...wagaList)

    let normal = 0, repair = 0, stopped = 0
    allItems.forEach(item => {
      const s = item.runStatus || item.status || ''
      if (s === '正常运行' || s === '正常') normal++
      else if (s === '维修' || s === '检修') repair++
      else if (s === '停用' || s === '报废') stopped++
    })
    counts.normal = normal
    counts.repair = repair
    counts.stopped = stopped

    updateCharts()
  }).catch(() => {})
}

function updateCharts() {
  pieChart?.setOption({
    series: [{
      data: [
        { value: counts.dike, name: '堤防', itemStyle: { color: '#409EFF' } },
        { value: counts.pust, name: '水闸', itemStyle: { color: '#67C23A' } },
        { value: counts.reservoir, name: '水库', itemStyle: { color: '#E6A23C' } },
        { value: counts.waga, name: '泵站', itemStyle: { color: '#F56C6C' } }
      ]
    }]
  })
  barChart?.setOption({
    series: [{
      data: [
        { value: counts.normal, itemStyle: { color: '#67C23A' } },
        { value: counts.repair, itemStyle: { color: '#E6A23C' } },
        { value: counts.stopped, itemStyle: { color: '#F56C6C' } }
      ]
    }]
  })
}

onMounted(() => {
  initCharts()
  loadCounts()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  pieChart?.dispose()
  barChart?.dispose()
})
</script>

<style scoped>
.card-header { font-weight: 600; font-size: 16px; }
.nav-card { margin-bottom: 16px; cursor: pointer; }
.nav-card:hover { transform: translateY(-2px); transition: all 0.3s; }
.nav-item { text-align: center; padding: 16px; }
.nav-label { margin-top: 8px; font-size: 16px; font-weight: 500; color: #333; }
.nav-count { font-size: 13px; color: #999; margin-top: 4px; }
.mt-16 { margin-top: 16px; }
</style>
