/**
 * 卫星影像服务类
 * 提供卫星影像数据的获取、分析和对比功能
 */

import { SatelliteImage, ImageComparisonResult, TimeSeriesAnalysis, DataSource } from './satelliteTypes';

export class SatelliteImageService {
  /**
   * 获取指定地块的卫星影像数据
   */
  static async getFieldImages(
    fieldId: string,
    startDate: string,
    endDate: string,
    source: string = 'Sentinel-2',
    maxCloudCover: number = 30
  ): Promise<SatelliteImage[]> {
    // 模拟API调用，生成测试数据
    const mockImages: SatelliteImage[] = [];
    const start = new Date(startDate);
    const end = new Date(endDate);

    // 生成6个月的影像数据，每15天一张
    const intervalDays = 15;
    const totalImages = Math.floor((end.getTime() - start.getTime()) / (intervalDays * 24 * 60 * 60 * 1000));

    for (let i = 0; i < totalImages; i++) {
      const date = new Date(start);
      date.setDate(date.getDate() + i * intervalDays);

      // 模拟NDVI变化趋势（作物生长周期）
      const dayOfYear = Math.floor((date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / (24 * 60 * 60 * 1000));
      const ndviBase = 0.3 + 0.4 * Math.sin((dayOfYear - 90) * Math.PI / 180);
      const ndvi = Math.max(0.1, Math.min(0.9, ndviBase + (Math.random() - 0.5) * 0.2));

      // 相关植被指数计算
      const evi = ndvi * (0.9 + Math.random() * 0.2);
      const lai = ndvi * 6 + Math.random() * 2;

      // 随机云量
      const cloudCover = Math.random() * 50;

      // 只包含云量符合要求的影像
      if (cloudCover <= maxCloudCover) {
        mockImages.push({
          id: `${fieldId}-${source}-${date.toISOString().split('T')[0]}`,
          date: date.toISOString().split('T')[0],
          source,
          resolution: parseInt(DATA_SOURCES[source]?.resolution || '10'),
          cloudCover,
          ndvi,
          evi,
          lai,
          season: SatelliteImageService.getSeason(date),
          thumbnail: SatelliteImageService.generateThumbnailUrl(date, source),
          url: SatelliteImageService.generateImageUrl(date, source)
        });
      }
    }

    return mockImages.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }

  /**
   * 对比两张影像
   */
  static compareImages(image1: SatelliteImage, image2: SatelliteImage): ImageComparisonResult {
    const ndviChange = image2.ndvi - image1.ndvi;
    const eviChange = image2.evi - image1.evi;

    let changeType: 'improvement' | 'decline' | 'stable';
    let changeDescription: string;

    const threshold = 0.05; // NDVI变化阈值

    if (ndviChange > threshold) {
      changeType = 'improvement';
      changeDescription = '作物长势明显改善';
    } else if (ndviChange < -threshold) {
      changeType = 'decline';
      changeDescription = '作物长势出现下降';
    } else {
      changeType = 'stable';
      changeDescription = '作物长势保持稳定';
    }

    // 生成管理建议
    const recommendations = this.generateRecommendations(changeType, ndviChange, eviChange);

    return {
      image1,
      image2,
      ndviChange,
      eviChange,
      changeType,
      changeDescription,
      recommendations
    };
  }

  /**
   * 分析时序数据
   */
  static analyzeTimeSeries(images: SatelliteImage[]): TimeSeriesAnalysis {
    if (images.length === 0) {
      return {
        dates: [],
        ndviValues: [],
        trend: 'stable',
        growthStage: '无数据',
        healthScore: '--',
        alerts: []
      };
    }

    // 按日期排序
    const sortedImages = images.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

    const dates = sortedImages.map(img => img.date);
    const ndviValues = sortedImages.map(img => img.ndvi);

    // 分析趋势
    const trend = this.analyzeTrend(ndviValues);

    // 判断生长阶段
    const growthStage = this.determineGrowthStage(ndviValues);

    // 计算健康分数
    const healthScore = this.calculateHealthScore(ndviValues);

    // 生成警报
    const alerts = this.generateAlerts(ndviValues, sortedImages);

    return {
      dates,
      ndviValues,
      trend,
      growthStage,
      healthScore,
      alerts
    };
  }

  /**
   * 下载影像
   */
  static async downloadImage(image: SatelliteImage, format: 'jpg' | 'png' | 'tiff' = 'jpg'): Promise<void> {
    // 模拟下载过程
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟下载成功
        console.log(`Downloading ${image.url} as ${format}`);
        resolve();
      }, 2000);
    });
  }

  /**
   * 获取NDVI对应的颜色
   */
  static getNDVIColor(ndvi: number): string {
    if (ndvi < 0.2) return '#ef4444'; // 红色
    if (ndvi < 0.4) return '#f97316'; // 橙色
    if (ndvi < 0.6) return '#eab308'; // 黄色
    if (ndvi < 0.8) return '#84cc16'; // 浅绿色
    return '#22c55e'; // 深绿色
  }

  /**
   * 获取NDVI对应的描述
   */
  static getNDVILabel(ndvi: number): string {
    if (ndvi < 0.2) return '植被稀疏';
    if (ndvi < 0.4) return '植被较少';
    if (ndvi < 0.6) return '植被适中';
    if (ndvi < 0.8) return '植被良好';
    return '植被茂盛';
  }

  // 私有方法

  private static getSeason(date: Date): string {
    const month = date.getMonth();
    if (month >= 2 && month <= 4) return '春季';
    if (month >= 5 && month <= 7) return '夏季';
    if (month >= 8 && month <= 10) return '秋季';
    return '冬季';
  }

  private static generateThumbnailUrl(date: Date, source: string): string {
    const dateStr = date.toISOString().split('T')[0];
    return `https://picsum.photos/seed/${source}-${dateStr}/200/200.jpg`;
  }

  private static generateImageUrl(date: Date, source: string): string {
    const dateStr = date.toISOString().split('T')[0];
    return `https://picsum.photos/seed/${source}-${dateStr}/800/600.jpg`;
  }

  private static analyzeTrend(values: number[]): 'increasing' | 'decreasing' | 'stable' | 'fluctuating' {
    if (values.length < 2) return 'stable';

    let increaseCount = 0;
    let decreaseCount = 0;

    for (let i = 1; i < values.length; i++) {
      if (values[i] > values[i - 1] + 0.02) increaseCount++;
      else if (values[i] < values[i - 1] - 0.02) decreaseCount++;
    }

    const totalChanges = values.length - 1;
    const increaseRatio = increaseCount / totalChanges;
    const decreaseRatio = decreaseCount / totalChanges;

    if (increaseRatio > 0.6) return 'increasing';
    if (decreaseRatio > 0.6) return 'decreasing';
    if (increaseRatio > 0.3 && decreaseRatio > 0.3) return 'fluctuating';
    return 'stable';
  }

  private static determineGrowthStage(ndviValues: number[]): string {
    if (ndviValues.length === 0) return '未知';

    const avgNdvi = ndviValues.reduce((sum, val) => sum + val, 0) / ndviValues.length;
    const latestNdvi = ndviValues[ndviValues.length - 1];

    if (avgNdvi < 0.3) return '苗期';
    if (avgNdvi < 0.5) return '生长期';
    if (avgNdvi < 0.7) return '旺盛期';
    return '成熟期';
  }

  private static calculateHealthScore(ndviValues: number[]): string {
    if (ndviValues.length === 0) return '--';

    const avgNdvi = ndviValues.reduce((sum, val) => sum + val, 0) / ndviValues.length;
    const latestNdvi = ndviValues[ndviValues.length - 1];

    // 综合平均NDVI和最新NDVI计算健康分数
    const healthScore = Math.round((avgNdvi * 0.6 + latestNdvi * 0.4) * 100);
    return `${healthScore}/100`;
  }

  private static generateAlerts(ndviValues: number[], images: SatelliteImage[]): string[] {
    const alerts: string[] = [];

    if (ndviValues.length < 2) return alerts;

    const latestNdvi = ndviValues[ndviValues.length - 1];
    const previousNdvi = ndviValues[ndviValues.length - 2];
    const ndviChange = latestNdvi - previousNdvi;

    // NDVI下降警报
    if (ndviChange < -0.1) {
      alerts.push('NDVI显著下降，建议检查灌溉和病虫害情况');
    }

    // NDVI过低警报
    if (latestNdvi < 0.3) {
      alerts.push('植被覆盖度过低，建议加强田间管理');
    }

    // 云量过高警报
    const highCloudImages = images.filter(img => img.cloudCover > 40);
    if (highCloudImages.length > images.length * 0.5) {
      alerts.push('近期影像云量较高，可能影响分析准确性');
    }

    return alerts;
  }

  private static generateRecommendations(
    changeType: 'improvement' | 'decline' | 'stable',
    ndviChange: number,
    eviChange: number
  ): string[] {
    const recommendations: string[] = [];

    if (changeType === 'improvement') {
      recommendations.push('作物长势良好，继续保持当前管理措施');
      recommendations.push('可适当增加施肥量，维持作物生长势头');
      if (Math.abs(eviChange) > 0.05) {
        recommendations.push('EVI指数变化明显，建议监测叶面积指数变化');
      }
    } else if (changeType === 'decline') {
      recommendations.push('作物长势下降，建议立即检查灌溉情况');
      recommendations.push('加强病虫害监测，必要时采取防治措施');
      recommendations.push('考虑补充施肥，提供充足营养');
      if (ndviChange < -0.1) {
        recommendations.push('NDVI下降明显，建议进行实地勘察');
      }
    } else {
      recommendations.push('作物长势稳定，维持当前管理方案');
      recommendations.push('定期监测植被指数变化趋势');
      recommendations.push('根据生长阶段调整田间管理措施');
    }

    return recommendations;
  }
}

// 导出数据源
export const DATA_SOURCES: Record<string, DataSource> = {
  'Sentinel-2': {
    name: 'Sentinel-2',
    resolution: '10',
    description: '欧洲航天局，高分辨率多光谱成像',
    provider: 'ESA'
  },
  'Landsat-8': {
    name: 'Landsat-8',
    resolution: '30',
    description: '美国地质调查局，中分辨率多光谱成像',
    provider: 'USGS'
  },
  'MODIS': {
    name: 'MODIS',
    resolution: '250',
    description: '中分辨率成像光谱仪，每日覆盖',
    provider: 'NASA'
  },
  '高分一号': {
    name: '高分一号',
    resolution: '8',
    description: '中国高分系列，高分辨率光学卫星',
    provider: 'CNSA'
  },
  '天地图': {
    name: '天地图',
    resolution: '2',
    description: '中国国产卫星影像服务',
    provider: 'NASG'
  }
};

// 工具函数
export const formatImageDate = (dateString: string): string => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

export const getCloudCoverColorClass = (cloudCover: number): string => {
  if (cloudCover <= 10) return 'bg-green-100 text-green-800 border-green-200';
  if (cloudCover <= 30) return 'bg-yellow-100 text-yellow-800 border-yellow-200';
  if (cloudCover <= 50) return 'bg-orange-100 text-orange-800 border-orange-200';
  return 'bg-red-100 text-red-800 border-red-200';
};