import apiClient from './index';
import type { 
    DashboardStatsDTO, 
    AqiDistributionDTO, 
    TaskStatsDTO, 
    TrendDataPointDTO, 
    GridCoverageDTO, 
    HeatmapPointDTO, 
    PollutionStatsDTO, 
    AqiHeatmapPointDTO,
    PollutantThresholdDTO,
    Grid
} from './types';

/**
 * Fetches the main dashboard statistics.
 * @returns A promise that resolves to the dashboard stats.
 */
export const getDashboardStats = (): Promise<DashboardStatsDTO> => {
    return apiClient.get('/dashboard/stats');
};

/**
 * Fetches the AQI level distribution.
 * @returns A promise that resolves to an array of AQI distribution data.
 */
export const getAqiDistribution = (): Promise<AqiDistributionDTO[]> => {
    return apiClient.get('/dashboard/reports/aqi-distribution');
};

/**
 * Fetches the monthly trend of exceedance events.
 * @returns A promise that resolves to an array of trend data points.
 */
export const getMonthlyExceedanceTrend = (): Promise<TrendDataPointDTO[]> => {
    return apiClient.get('/dashboard/reports/monthly-exceedance-trend')
        .then(data => {
            console.log('原始趋势数据:', data);
            // 确保数据格式正确
            if (Array.isArray(data)) {
                return data.map(item => ({
                    yearMonth: item.yearMonth || '',
                    count: item.count || 0
                }));
            }
            return [];
        });
};

/**
 * Fetches the grid coverage statistics by city.
 * @returns A promise that resolves to an array of grid coverage data.
 */
export const getGridCoverageByCity = (): Promise<GridCoverageDTO[]> => {
    return apiClient.get('/dashboard/reports/grid-coverage');
};

/**
 * Fetches the heatmap data for pollution incidents.
 * @returns A promise that resolves to an array of heatmap points.
 */
export const getHeatmapData = (): Promise<HeatmapPointDTO[]> => {
    return apiClient.get('/dashboard/map/heatmap');
};

/**
 * Fetches the pollution statistics.
 * @returns A promise that resolves to an array of pollution stats.
 */
export const getPollutionStats = (): Promise<PollutionStatsDTO[]> => {
    return apiClient.get('/dashboard/reports/pollution-stats');
};

/**
 * Fetches the task completion statistics.
 * @returns A promise that resolves to the task stats.
 */
export const getTaskCompletionStats = (): Promise<TaskStatsDTO> => {
    return apiClient.get('/dashboard/reports/task-completion-stats');
};

/**
 * Fetches the AQI heatmap data.
 * @returns A promise that resolves to an array of AQI heatmap points.
 */
export const getAqiHeatmapData = (): Promise<AqiHeatmapPointDTO[]> => {
    return apiClient.get('/dashboard/map/aqi-heatmap');
};

/**
 * Fetches all pollutant thresholds.
 * @returns A promise that resolves to an array of pollutant thresholds.
 */
export const getPollutantThresholds = (): Promise<PollutantThresholdDTO[]> => {
    return apiClient.get('/dashboard/thresholds');
};

/**
 * Fetches a specific pollutant threshold.
 * @param pollutantName The name of the pollutant.
 * @returns A promise that resolves to the pollutant threshold.
 */
export const getPollutantThreshold = (pollutantName: string): Promise<PollutantThresholdDTO> => {
    return apiClient.get(`/dashboard/thresholds/${pollutantName}`);
};

/**
 * Saves a pollutant threshold.
 * @param threshold The pollutant threshold to save.
 * @returns A promise that resolves to the saved pollutant threshold.
 */
export const savePollutantThreshold = (threshold: PollutantThresholdDTO): Promise<PollutantThresholdDTO> => {
    return apiClient.post('/dashboard/thresholds', threshold);
};

/**
 * 获取每种污染物的月度趋势数据
 * @returns 每种污染物的月度趋势数据
 */
export const getPollutantMonthlyTrends = (value: string): Promise<Record<string, TrendDataPointDTO[]>> => {
    return apiClient.get('/dashboard/reports/pollutant-monthly-trends')
        .then(data => {
            console.log('原始污染物趋势数据:', data);
            // 确保数据格式正确
            if (data && typeof data === 'object') {
                const result: Record<string, TrendDataPointDTO[]> = {};
                Object.entries(data).forEach(([key, value]) => {
                    if (Array.isArray(value)) {
                        result[key] = value.map(item => ({
                            yearMonth: item.yearMonth || '',
                            count: item.count || 0
                        }));
                    }
                });
                return result;
            }
            return {};
        });
};

/**
 * Fetches all grid data from the server.
 * @returns A promise that resolves to an array of Grid objects.
 */
export const getGrids = (): Promise<Grid[]> => {
    return apiClient.get('/grids');
}; 