import { Component, Input, OnChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import type { ForecastPoint, WeatherPoint } from './api.service';

import { FormsModule } from '@angular/forms';

@Component({
  selector: 'table-panel',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './table-panel.component.html'
})
export class TablePanelComponent implements OnChanges {
  @Input() history: WeatherPoint[] = [];
  @Input() forecast: ForecastPoint[] = [];
  @Input() showPastForecast = false;
  @Input() endDate: string = '';

  headers: string[] = ['时间','温度 (°C)','湿度 (%)','气压 (hPa)','风速 (m/s)','风向 (°)','雨量 (mm)'];
  rows: any[] = [];
  hasForecast = false;

  ngOnChanges(): void { this.build(); }

  build() {
    const endTs = this.endDate ? new Date(this.endDate).getTime() : Date.now();
    const future3h = endTs + 3*60*60*1000;
    const filteredFcst = (Array.isArray(this.forecast)?this.forecast:[]).filter(it => {
      const t = new Date(it.date_time.replace(' ', 'T')).getTime();
      const isFuture3h = t > endTs && t <= future3h;
      const isPast = t <= endTs;
      return isFuture3h || (this.showPastForecast && isPast);
    }).map(it => ({...it, __source: '预报'}));

    const hist = (Array.isArray(this.history)?this.history:[]).map(it => ({...it, __source: '实测'}));
    const all: any[] = [...hist as any[], ...filteredFcst as any[]];
    this.hasForecast = filteredFcst.length > 0;
    this.headers = ['时间','温度 (°C)','湿度 (%)','气压 (hPa)','风速 (m/s)','风向 (°)','雨量 (mm)'];
    if (this.hasForecast) this.headers = [...this.headers, '降水概率 (%)'];
    this.headers = [...this.headers, '光照 (lux)','紫外线'];

    const fmt = (v: any, d: number) => (v===null || v===undefined || v==='' || isNaN(Number(v))) ? '' : Number(v).toFixed(d);
    this.rows = all.sort((a,b)=> new Date(b.date_time).getTime() - new Date(a.date_time).getTime()).map(row => ({
      date_time: row.date_time,
      isForecast: row.__source==='预报',
      issued_at: (row as any).issued_at,
      issued_hhmm: (()=>{
        const ia = (row as any).issued_at as string | undefined;
        if (!ia) return null;
        // expected format: YYYY-MM-DD HH:MM:SS
        const t = ia.includes(' ') ? ia.split(' ')[1] : ia;
        return t ? t.substring(0,5) : null;
      })(),
      lead_hours: (row as any).lead_hours,
      temperature: fmt(row.temperature,1),
      humidity: fmt(row.humidity,1),
      pressure: fmt(row.pressure,1),
      wind_speed: fmt(row.wind_speed,1),
      wind_direction: fmt(row.wind_direction,0),
      rainfall: fmt(row.rainfall,2),
      precip_prob: (row.__source==='预报' && (row as any).precip_prob!=null) ? (row as any).precip_prob : null,
      light: fmt(row.light,0),
      uv: fmt(row.uv,1)
    }));
  }
}
