<template>
  <div class="app-container">
    <div class="top-section">
      <div class="stat-card-section">
        <div class="stat-section-title">实时上报统计</div>
        <div class="stat-cards">
          <div class="stat-card" v-for="unit in realtimeData" :key="unit.unitCode">
            <div class="stat-card-header">
              <span class="unit-name">{{ unit.unitName }}</span>
            </div>
            <div class="stat-card-body">
              <div class="stat-item">
                <span class="stat-label">今日上报</span>
                <span class="stat-value today">{{ unit.todayCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">本周上报</span>
                <span class="stat-value week">{{ unit.weekCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">本月上报</span>
                <span class="stat-value month">{{ unit.monthCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="yearly-section">
        <div class="section-header">
          <span class="section-title">年度数据统计</span>
          <div class="header-right">
            <el-select v-model="selectedDataType" class="data-type-select" @change="handleDataTypeChange">
              <el-option label="合计" value="total" />
              <el-option label="水量" value="sl" />
              <el-option label="水质" value="sz" />
            </el-select>
            <el-date-picker
              v-model="selectedYear"
              type="year"
              placeholder="选择年份"
              format="YYYY"
              value-format="YYYY"
              @change="handleYearChange"
              clearable
              class="year-picker"
            />
          </div>
        </div>
        <el-table :data="filteredYearlyData" stripe border v-loading="yearlyLoading" height="280">
          <el-table-column prop="year" label="年份" width="80" />
          <el-table-column label="无锡">
            <el-table-column prop="wxDataCount" label="数据量" width="100">
              <template #default="{ row }">
                {{ row.wxDataCount || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="wxMonitorCount" label="监测" width="100">
              <template #default="{ row }">
                {{ row.wxMonitorCount || 0 }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="江苏">
            <el-table-column prop="jsDataCount" label="数据量" width="100">
              <template #default="{ row }">
                {{ row.jsDataCount || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="jsMonitorCount" label="监测" width="100">
              <template #default="{ row }">
                {{ row.jsMonitorCount || 0 }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="上海">
            <el-table-column prop="shDataCount" label="数据量" width="100">
              <template #default="{ row }">
                {{ row.shDataCount || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="shMonitorCount" label="监测" width="100">
              <template #default="{ row }">
                {{ row.shMonitorCount || 0 }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div v-if="filteredYearlyData.length === 0 && !yearlyLoading" class="empty-text">
          暂无数据
        </div>
      </div>
    </div>

    <div class="unit-section">
      <div class="section-header">
        <span class="section-title">历年统计分析</span>
        <el-select v-model="selectedUnit" placeholder="请选择单位" class="unit-select" @change="handleUnitChange">
          <el-option label="无锡" value="WX" />
          <el-option label="江苏" value="JS" />
          <el-option label="上海" value="SH" />
        </el-select>
      </div>
      
      <div class="unit-content">
        <el-table :data="unitStatistics" stripe border v-loading="unitLoading">
          <el-table-column prop="year" label="年份" width="100" />
          <el-table-column prop="stationCount" label="测站数量" width="150">
            <template #default="{ row }">
              {{ row.stationCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="monitorCount" label="监测次数" width="150">
            <template #default="{ row }">
              {{ row.monitorCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="dataCount" label="数据量" width="150">
            <template #default="{ row }">
              {{ row.dataCount || 0 }}
            </template>
          </el-table-column>
        </el-table>
        
        <div class="chart-container">
          <div ref="chartRef" class="chart"></div>
        </div>
      </div>
      <div v-if="unitStatistics.length === 0 && !unitLoading" class="empty-text">
        暂无数据
      </div>
    </div>
  </div>
</template>

<script setup name="YjjtStatistics">
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getRealtimeStatistics, getYearlyStatistics, getYearlySlStatistics, getYearlySzStatistics, getUnitStatistics } from '@/api/yjjt/statistics'

const realtimeData = ref([])
const yearlyData = ref([])
const unitStatistics = ref([])
const selectedUnit = ref('WX')
const selectedYear = ref('')
const selectedDataType = ref('total')
const yearlyLoading = ref(false)
const unitLoading = ref(false)
const chartRef = ref(null)
let chartInstance = null

const filteredYearlyData = computed(() => {
  return yearlyData.value
})

const handleYearChange = () => {
  loadYearlyData()
}

const handleDataTypeChange = () => {
  loadYearlyData()
}

const loadRealtimeData = async () => {
  try {
    const response = await getRealtimeStatistics()
    realtimeData.value = response.data.units || []
  } catch (error) {
    console.error('加载实时统计数据失败', error)
  }
}

const loadYearlyData = async () => {
  yearlyLoading.value = true
  try {
    let response
    const year = selectedYear.value || null
    
    if (selectedDataType.value === 'sl') {
      response = await getYearlySlStatistics(year)
    } else if (selectedDataType.value === 'sz') {
      response = await getYearlySzStatistics(year)
    } else {
      response = await getYearlyStatistics(year)
    }
    
    yearlyData.value = response.data || []
  } catch (error) {
    console.error('加载年度统计数据失败', error)
    yearlyData.value = []
  } finally {
    yearlyLoading.value = false
  }
}

const loadUnitStatistics = async () => {
  unitLoading.value = true
  try {
    const response = await getUnitStatistics(selectedUnit.value)
    unitStatistics.value = response.data || []
    await nextTick()
    renderChart()
  } catch (error) {
    console.error('加载单位统计数据失败', error)
    unitStatistics.value = []
  } finally {
    unitLoading.value = false
  }
}

const handleUnitChange = () => {
  loadUnitStatistics()
}

const renderChart = () => {
  if (!chartRef.value) {
    console.warn('chartRef未找到')
    return
  }
  
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartRef.value)
  
  if (!unitStatistics.value || unitStatistics.value.length === 0) {
    chartInstance.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: {
          fontSize: 14,
          color: '#999'
        }
      }
    })
    return
  }
  
  const years = unitStatistics.value.map(item => String(item.year)).sort((a, b) => a.localeCompare(b))
  const stationCounts = years.map(year => {
    const item = unitStatistics.value.find(s => String(s.year) === year)
    return item ? item.stationCount || 0 : 0
  })
  const monitorCounts = years.map(year => {
    const item = unitStatistics.value.find(s => String(s.year) === year)
    return item ? item.monitorCount || 0 : 0
  })
  const dataCounts = years.map(year => {
    const item = unitStatistics.value.find(s => String(s.year) === year)
    return item ? item.dataCount || 0 : 0
  })
  
  const option = {
    title: {
      text: `${getUnitName(selectedUnit.value)}历年统计`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['测站数量', '监测次数', '数据量'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: years,
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '测站数量',
        type: 'bar',
        data: stationCounts,
        itemStyle: {
          color: '#1c97e7'
        }
      },
      {
        name: '监测次数',
        type: 'bar',
        data: monitorCounts,
        itemStyle: {
          color: '#79c662'
        }
      },
      {
        name: '数据量',
        type: 'bar',
        data: dataCounts,
        itemStyle: {
          color: '#ff8562'
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const handleResize = () => {
  chartInstance && chartInstance.resize()
}

const getUnitName = (code) => {
  const names = {
    'WX': '无锡',
    'JS': '江苏',
    'SH': '上海'
  }
  return names[code] || code
}

onMounted(async () => {
  await loadRealtimeData()
  await loadYearlyData()
  await loadUnitStatistics()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card-section {
  flex: 6;
}

.stat-section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.stat-cards {
  display: flex;
  flex-direction: row;
  gap: 15px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 150px;
  background: linear-gradient(135deg, #1c97e7 0%, #017DE4 100%);
  border-radius: 8px;
  padding: 15px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(28, 151, 231, 0.3);
}

.stat-card-header {
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 8px;
  margin-bottom: 10px;
}

.unit-name {
  font-size: 16px;
  font-weight: bold;
}

.stat-card-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 13px;
  opacity: 0.9;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

.stat-value.today {
  color: #ffcc4d;
}

.stat-value.week {
  color: #93d347;
}

.stat-value.month {
  color: #ffffff;
}

.yearly-section {
  flex: 4;
  min-width: 0;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.header-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.data-type-select {
  width: 100px;
}

.year-picker {
  width: 130px;
}

.unit-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.unit-select {
  width: 150px;
}

.unit-content {
  display: flex;
  flex-direction: row;
  gap: 20px;
  align-items: flex-start;
}

.chart-container {
  flex: 1;
  min-width: 0;
}

.chart {
  width: 100%;
  height: 400px;
}

.unit-content .el-table {
  width: 400px;
  flex-shrink: 0;
}

.empty-text {
  text-align: center;
  color: #999;
  padding: 20px 0;
  font-size: 14px;
}

@media (max-width: 1200px) {
  .top-section {
    flex-direction: column;
  }
  
  .stat-card-section,
  .yearly-section {
    flex: none;
  }
  
  .unit-content {
    flex-direction: column;
  }
  
  .unit-content .el-table {
    width: 100%;
  }
}
</style>
