// composables/useWeatherStats.ts
import { computed, type Ref } from "vue";
import { RAIN_LEVELS, rainLevelLabel } from "./useWeatherConstants";

// ---------- 类型 ----------

export interface WeatherDataRow {
  year: number;
  rainfall: number | null;
  tmax: number | null;
  tavg: number | null;
  tmin: number | null;
  windSpeed: number | null;
  windDirection: number | null;
  humidity?: number;
  pressure?: number;
  // 运行时标记
  _matched?: boolean;
  _isMaxRain?: boolean;
  _isMaxTmax?: boolean;
  _isMinTmin?: boolean;
  _rainLevel?: string;
}

export interface WeatherStats {
  avgTmax: string;
  avgTmaxYear: number | string;
  avgTmin: string;
  avgTminYear: number | string;
  avgRain: string;
  maxRain: number | string;
  maxRainYear: number | string;
  rainyCount: number;
  rainyPct: string;
  maxTmax: number | string;
  maxTmaxYear: number | string;
  minTmin: number | string;
  minTminYear: number | string;
  maxTavg?: number | string;
  maxTavgYear?: number | string;
}

export interface StatCard {
  items: StatCardItem[];
}

export interface StatCardItem {
  label: string;
  value: number | string;
  unit: string;
  color: string;
}

export interface SummaryMeta {
  stationName: string;
  fromYear: number;
  toYear: number;
  month: number;
  day: number;
  count: number;
  /** 实际数据中最早年份 */
  dataFromYear?: number;
  /** 实际数据中最晚年份 */
  dataToYear?: number;
}

// ---------- 纯函数 ----------

export function emptyStats(): WeatherStats {
  return {
    avgTmax: "-",
    avgTmaxYear: "-",
    avgTmin: "-",
    avgTminYear: "-",
    avgRain: "-",
    maxRain: "-",
    maxRainYear: "-",
    rainyCount: 0,
    rainyPct: "0",
    maxTmax: "-",
    maxTmaxYear: "-",
    minTmin: "-",
    minTminYear: "-"
  };
}

/** null-safe 数值比较：a > b，但 null 视为无数据（永不大于有效值） */
function gtNullSafe(a: number | null, b: number | null): boolean {
  if (a == null) return false;
  if (b == null) return true;
  return a > b;
}

/** null-safe 数值比较：a < b，但 null 视为无数据（永不小于有效值） */
function ltNullSafe(a: number | null, b: number | null): boolean {
  if (a == null) return false;
  if (b == null) return true;
  return a < b;
}

export function computeStats(data: WeatherDataRow[]): WeatherStats {
  if (!data.length) return emptyStats();

  const result = data.reduce(
    (acc, row) => ({
      // 只有非 null 值才计入求和
      sumTmax: row.tmax != null ? acc.sumTmax + row.tmax : acc.sumTmax,
      sumTmin: row.tmin != null ? acc.sumTmin + row.tmin : acc.sumTmin,
      sumRain: row.rainfall != null ? acc.sumRain + row.rainfall : acc.sumRain,
      // count 仍然计所有行，但用于均值的分母需改为有效值计数
      count: acc.count + 1,
      validTmaxCount: acc.validTmaxCount + (row.tmax != null ? 1 : 0),
      validTminCount: acc.validTminCount + (row.tmin != null ? 1 : 0),
      validRainCount: acc.validRainCount + (row.rainfall != null ? 1 : 0),
      rainyCount: acc.rainyCount + (row.rainfall != null && row.rainfall > 0.1 ? 1 : 0),
      maxRainRow:
        gtNullSafe(row.rainfall, acc.maxRainRow?.rainfall ?? null) ? row : acc.maxRainRow,
      maxTmaxRow:
        gtNullSafe(row.tmax, acc.maxTmaxRow?.tmax ?? null) ? row : acc.maxTmaxRow,
      minTminRow:
        ltNullSafe(row.tmin, acc.minTminRow?.tmin ?? null) ? row : acc.minTminRow,
      maxTavgRow:
        gtNullSafe(row.tavg, acc.maxTavgRow?.tavg ?? null) ? row : acc.maxTavgRow,
      maxAvgTmaxRow:
        gtNullSafe(row.tmax, acc.maxAvgTmaxRow?.tmax ?? null) ? row : acc.maxAvgTmaxRow,
      minAvgTminRow:
        ltNullSafe(row.tmin, acc.minAvgTminRow?.tmin ?? null) ? row : acc.minAvgTminRow
    }),
    {
      sumTmax: 0,
      sumTmin: 0,
      sumRain: 0,
      count: 0,
      validTmaxCount: 0,
      validTminCount: 0,
      validRainCount: 0,
      rainyCount: 0,
      maxRainRow: null as WeatherDataRow | null,
      maxTmaxRow: null as WeatherDataRow | null,
      minTminRow: null as WeatherDataRow | null,
      maxTavgRow: null as WeatherDataRow | null,
      maxAvgTmaxRow: null as WeatherDataRow | null,
      minAvgTminRow: null as WeatherDataRow | null
    }
  );

  const avg = (sum: number, validCount: number) =>
    validCount > 0 ? (sum / validCount).toFixed(1) : "-";

  return {
    avgTmax: avg(result.sumTmax, result.validTmaxCount),
    avgTmaxYear: result.maxAvgTmaxRow?.year ?? "-",
    avgTmin: avg(result.sumTmin, result.validTminCount),
    avgTminYear: result.minAvgTminRow?.year ?? "-",
    avgRain: avg(result.sumRain, result.validRainCount),
    maxRain: result.maxRainRow?.rainfall ?? "-",
    maxRainYear: result.maxRainRow?.year ?? "-",
    rainyCount: result.rainyCount,
    rainyPct: ((result.rainyCount / result.count) * 100).toFixed(0),
    maxTmax: result.maxTmaxRow?.tmax ?? "-",
    maxTmaxYear: result.maxTmaxRow?.year ?? "-",
    minTmin: result.minTminRow?.tmin ?? "-",
    minTminYear: result.minTminRow?.year ?? "-",
    maxTavg: result.maxTavgRow?.tavg ?? "-",
    maxTavgYear: result.maxTavgRow?.year ?? "-"
  };
}

/**
 * 构建统计卡片（去除了原版中与"多年平均最高/低温"重复的第4/5组）
 */
export function buildStatCards(stats: WeatherStats): StatCard[] {
  return [
    {
      items: [
        { label: "多年平均最高温", value: stats.avgTmax, unit: "℃", color: "#ef4444" },
        { label: "多年平均最低温", value: stats.avgTmin, unit: "℃", color: "#2563eb" }
      ]
    },
    {
      items: [
        { label: "历史最高温度", value: stats.maxTmax, unit: "℃", color: "#ef4444" },
        { label: "出现年份", value: stats.maxTmaxYear, unit: "年", color: "#4a4645" }
      ]
    },
    {
      items: [
        { label: "历史最低温度", value: stats.minTmin, unit: "℃", color: "#2563eb" },
        { label: "出现年份", value: stats.minTminYear, unit: "年", color: "#4a4645" }
      ]
    },
    {
      items: [
        { label: "最大单日降水", value: stats.maxRain, unit: "mm", color: "#7c3aed" },
        { label: "出现年份", value: stats.maxRainYear, unit: "年", color: "#4a4645" }
      ]
    },
    {
      items: [
        { label: "平均降水量", value: stats.avgRain, unit: "mm", color: "#0891b2" },
        { label: "降水概率", value: stats.rainyPct, unit: "%", color: "#059669" }
      ]
    }
  ];
}

export function buildSummary(stats: WeatherStats, meta: SummaryMeta): string {
  const { stationName, fromYear, toYear, month, day, count, dataFromYear, dataToYear } = meta;
  const d = String(day).padStart(2, "0");
  const dataRange = dataFromYear != null && dataToYear != null
    ? `（${dataFromYear}-${dataToYear}）`
    : "";
  return [
    `${stationName}在 ${fromYear}~${toYear} 年间，每年${month}月${d}日这一天共回溯 ${count} 条单日记录${dataRange}。`,
    `其中 ${stats.rainyCount} 年当天出现降水，历史平均单日降雨量 ${stats.avgRain}mm，`,
    `单日最大降雨 ${stats.maxRain}mm（${stats.maxRainYear}年）。`,
    `多年平均最高气温 ${stats.avgTmax}℃，多年平均最低气温 ${stats.avgTmin}℃，`,
    `历史最高气温 ${stats.maxTmax}℃（${stats.maxTmaxYear}年），历史最低气温 ${stats.minTmin}℃（${stats.minTminYear}年）。`
  ].join("");
}

// ---------- Composable ----------

export function useWeatherStats(displayRows: Ref<WeatherDataRow[]>) {
  /** 雨量等级分布（null 值不计入任何等级） */
  const rainLevelDistribution = computed(() => {
    const data = displayRows.value;
    const total = data.length;
    if (!total) return [] as { label: string; count: number; pct: string }[];

    const counts = new Array(RAIN_LEVELS.length).fill(0);
    let nullCount = 0;
    data.forEach((r) => {
      if (r.rainfall == null) {
        nullCount++;
        return;
      }
      const v = Number(r.rainfall);
      for (let i = 0; i < RAIN_LEVELS.length; i++) {
        if (v >= RAIN_LEVELS[i].min && v < RAIN_LEVELS[i].max) {
          counts[i]++;
          break;
        }
      }
    });

    const items: { label: string; count: number; pct: string }[] = RAIN_LEVELS.map((l, i) => ({
      label: l.label,
      count: counts[i],
      pct: total > 0 ? ((counts[i] / total) * 100).toFixed(1) : "0.0"
    }));

    // 如果存在 null 值，追加"无数据"条目
    if (nullCount > 0) {
      items.push({
        label: "无数据",
        count: nullCount,
        pct: ((nullCount / total) * 100).toFixed(1)
      });
    }

    return items;
  });

  return { rainLevelDistribution };
}
