<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :inline="true" label-width="60px">
      <el-form-item label="年份">
        <el-select v-model="queryYear" placeholder="全部" clearable style="width: 120px">
          <el-option v-for="y in yearOptions" :key="y" :label="y" :value="y" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位">
        <el-select v-model="queryAddvcd" placeholder="全部" clearable style="width: 140px">
          <el-option label="太湖局" value="THJ" />
          <el-option label="江苏" value="JS" />
          <el-option label="浙江" value="ZJ" />
          <el-option label="上海" value="SH" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="loadAll">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 汇总卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header><span>水量数据统计</span></template>
          <div style="font-size: 28px; font-weight: bold; color: #409EFF; text-align: center;">
            {{ slTotal }}
          </div>
          <div style="text-align: center; color: #909399; margin-top: 6px;">条</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header><span>水质数据统计</span></template>
          <div style="font-size: 28px; font-weight: bold; color: #67C23A; text-align: center;">
            {{ szTotal }}
          </div>
          <div style="text-align: center; color: #909399; margin-top: 6px;">条</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header><span>监测站点数</span></template>
          <div style="font-size: 28px; font-weight: bold; color: #E6A23C; text-align: center;">
            {{ stationTotal }}
          </div>
          <div style="text-align: center; color: #909399; margin-top: 6px;">个</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 按单位统计表 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <template #header><span>按单位数据统计</span></template>
      <el-table :data="countData" border stripe style="width: 100%">
        <el-table-column label="年份" prop="year" width="100" align="center" />
        <el-table-column label="数据类型" prop="ty" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.ty === 'SL' ? 'primary' : 'success'" size="small">
              {{ scope.row.ty === 'SL' ? '水量' : '水质' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传单位" prop="addvcd" width="120" align="center" />
        <el-table-column label="数据条数" prop="count" width="120" align="right" />
      </el-table>
    </el-card>

    <!-- 趋势图 -->
    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>数据量趋势</span>
          <div>
            <el-date-picker v-model="trendRange" style="width: 260px" value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="loadTrend" />
          </div>
        </div>
      </template>
      <div ref="chartRef" style="height: 360px;"></div>
    </el-card>
  </div>
</template>

<script setup name="YjjtStatistics">
import { selectCount, selectYearCount, sum } from "@/api/yjjt/statistics";
import * as echarts from 'echarts';

const chartRef = ref(null);
let chartInstance = null;

const queryYear = ref(new Date().getFullYear().toString());
const queryAddvcd = ref(undefined);

const slTotal = ref(0);
const szTotal = ref(0);
const stationTotal = ref(0);
const countData = ref([]);
const trendRange = ref([]);

// 生成近10年选项
const currentYear = new Date().getFullYear();
const yearOptions = ref([]);
for (let y = currentYear; y >= currentYear - 10; y--) {
  yearOptions.value.push(y.toString());
}

function loadAll() {
  loadCount();
  loadYearCount();
  loadTrend();
}

function loadCount() {
  const params = { year: queryYear.value, addvcd: queryAddvcd.value };
  selectCount(params).then((res) => {
    const list = res.data || [];
    countData.value = list;
    slTotal.value = list.filter(i => i.ty === 'SL').reduce((s, i) => s + (i.count || 0), 0);
    szTotal.value = list.filter(i => i.ty === 'SZ').reduce((s, i) => s + (i.count || 0), 0);
  });
}

function loadYearCount() {
  const params = { year: queryYear.value, addvcd: queryAddvcd.value };
  selectYearCount(params).then((res) => {
    const list = res.data || [];
    stationTotal.value = list.reduce((s, i) => s + (i.stcdNm || 0), 0);
  });
}

function loadTrend() {
  if (!trendRange.value || trendRange.value.length !== 2) {
    // 默认最近30天
    const end = new Date();
    const start = new Date();
    start.setDate(end.getDate() - 29);
    trendRange.value = [
      start.toISOString().slice(0, 10),
      end.toISOString().slice(0, 10)
    ];
  }
  sum({ beginDate: trendRange.value[0], endDate: trendRange.value[1] }).then((res) => {
    const list = res.data || [];
    renderChart(list);
  });
}

function renderChart(list) {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  const dates = list.map(i => i.dt);
  const slCounts = list.map(i => i.sl_count || 0);
  const szCounts = list.map(i => i.sz_count || 0);

  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['水量', '水质'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dates, axisLabel: { rotate: 45 } },
    yAxis: { type: 'value', name: '数据条数' },
    series: [
      { name: '水量', type: 'bar', data: slCounts, itemStyle: { color: '#409EFF' } },
      { name: '水质', type: 'bar', data: szCounts, itemStyle: { color: '#67C23A' } }
    ]
  });
}

// 窗口resize时自动调整图表
window.addEventListener('resize', () => {
  if (chartInstance) chartInstance.resize();
});

loadAll();
</script>
