import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface DauTrendItem {
  date: string;
  dau: number;
}

export interface RevenueTrendItem {
  date: string;
  revenue: number;
}

export interface KpiData {
  dau: {
    today: number;
    trend: DauTrendItem[];
  };
}

export interface ArtworkStat {
  resId: string;
  name: string;
  coverImage: string | null;
  clickCount: number;
  clickRate: number;
  completionCount: number;
  completionRate: number;
}

export interface ArtworkStatsResponse {
  dau_today: number;
  artworks: ArtworkStat[];
}

export interface NewArtworkTabItem {
  resId: string;
  name: string;
  thumbnail: string;
  areaCount: number;
  areaCountFloor: number;
  clickCount: number;
  completionCount: number;
  tipCount: number;
  clickRate: number;
  completionRate: number;
}

export interface NewArtworkTab {
  label: string;
  date: string;
  dau: number;
  artworks: NewArtworkTabItem[];
}

export interface NewArtworkTabsResponse {
  tabs: NewArtworkTab[];
}

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: string;
}

@Injectable({
  providedIn: 'root',
})
export class DashboardService {
  constructor(private http: HttpClient) {}

  /**
   * 获取 KPI 数据（日活用户、日活曲线、广告收益、收益曲线）
   * @param dateRange 显示过去 N 天的数据，默认 7 天
   * @returns KPI 数据
   */
  getKpi(dateRange: number = 7): Observable<ApiResponse<KpiData>> {
    let params = new HttpParams();
    if (dateRange) {
      params = params.set('dateRange', dateRange.toString());
    }
    return this.http.get<ApiResponse<KpiData>>('/api/dashboard/kpi', {
      params,
    });
  }

  /**
   * 获取作品统计数据（点击率、完成率排行）
   * @param top 返回 Top N 作品数量，默认 10
   * @param sortBy 排序字段，默认 clickCount
   * @returns 作品统计数据
   */
  getArtworkStats(
    top: number = 10,
    sortBy:
      | 'clickRate'
      | 'completionRate'
      | 'clickCount'
      | 'completionCount' = 'clickCount',
  ): Observable<ApiResponse<ArtworkStatsResponse>> {
    let params = new HttpParams()
      .set('top', top.toString())
      .set('sortBy', sortBy);
    return this.http.get<ApiResponse<ArtworkStatsResponse>>(
      '/api/dashboard/artwork-stats',
      { params },
    );
  }

  /**
   * 获取最近 N 天上新作品分日 tab 数据
   */
  getNewArtworkTabs(
    days: number = 7,
    topPerDay: number = 20,
  ): Observable<ApiResponse<NewArtworkTabsResponse>> {
    const params = new HttpParams()
      .set('days', days.toString())
      .set('topPerDay', topPerDay.toString());
    return this.http.get<ApiResponse<NewArtworkTabsResponse>>(
      '/api/dashboard/new-artwork-tabs',
      { params },
    );
  }
}
