/**
 * 遥感影像服务
 * 集成天地图、Sentinel、Landsat等数据源
 */

// ===== 类型定义 =====

export interface SatelliteImage {
  id: string;
  date: string;
  source: 'Sentinel-2' | 'Landsat-8' | 'Landsat-9' | '天地图' | 'GF-1' | 'GF-2';
  cloudCover: number; // 云量百分比
  resolution: number; // 分辨率（米）
  ndvi: number; // 归一化植被指数
  evi: number; // 增强型植被指数
  savi: number; // 土壤调节植被指数
  lai: number; // 叶面积指数
  thumbnail: string; // 缩略图URL
  fullImageUrl: string; // 完整影像URL
  season: string;
  quality: 'excellent' | 'good' | 'fair' | 'poor';
  bands: {
    red?: string;
    green?: string;
    blue?: string;
    nir?: string;
    swir?: string;
  };
}

export interface FieldBoundary {
  id: string;
  name: string;
  coordinates: [number, number][];
  area: number; // 亩
}

export interface ImageComparisonResult {
  image1: SatelliteImage;
  image2: SatelliteImage;
  ndviChange: number;
  eviChange: number;
  changeType: 'improvement' | 'decline' | 'stable';
  changeDescription: string;
  recommendations: string[];
}

export interface TimeSeriesAnalysis {
  dates: string[];
  ndviValues: number[];
  eviValues: number[];
  trend: 'increasing' | 'decreasing' | 'fluctuating' | 'stable';
  growthStage: string;
  healthScore: number;
  alerts: string[];
}

// ===== 常量定义 =====

// 数据源配置
export const DATA_SOURCES = {
  'Sentinel-2': {
    name: 'Sentinel-2 (哨兵2号)',
    resolution: 10, // 米
    revisitTime: 5, // 重访周期（天）
    bands: ['B2-Blue', 'B3-Green', 'B4-Red', 'B8-NIR'],
    apiEndpoint: 'https://sentinelsat.esa.int/api',
    description: 'ESA哨兵2号卫星，10米分辨率，5天重访'
  },
  'Landsat-8': {
    name: 'Landsat-8',
    resolution: 30,
    revisitTime: 16,
    bands: ['B2-Blue', 'B3-Green', 'B4-Red', 'B5-NIR'],
    apiEndpoint: 'https://earthexplorer.usgs.gov/api',
    description: 'NASA陆地卫星8号，30米分辨率，16天重访'
  },
  '天地图': {
    name: '天地图',
    resolution: 2,
    revisitTime: 1,
    bands: ['RGB'],
    apiEndpoint: 'https://t0.tianditu.gov.cn/img_w/wmts',
    description: '国家地理信息公共服务平台，高分辨率影像'
  },
  'GF-1': {
    name: '高分一号',
    resolution: 2,
    revisitTime: 4,
    bands: ['B1-Blue', 'B2-Green', 'B3-Red', 'B4-NIR'],
    apiEndpoint: 'https://data.cresda.cn/api',
    description: '中国高分辨率对地观测卫星，2米分辨率'
  }
};

// NDVI评价标准
export const NDVI_THRESHOLDS = {
  excellent: 0.8, // 优秀
  good: 0.6, // 良好
  fair: 0.4, // 一般
  poor: 0.2 // 较差
};

// ===== 遥感影像服务类 =====

export class SatelliteImageService {
  
  /**
   * 获取地块的历史影像列表
   */
  static async getFieldImages(
    fieldId: string,
    startDate: string,
    endDate: string,
    source?: string,
    maxCloudCover: number = 30
  ): Promise<SatelliteImage[]> {
    // 模拟API调用
    // 实际应用中这里调用真实的遥感数据API
    
    const images = this._generateMockImages(startDate, endDate);
    
    // 过滤条件
    let filtered = images;
    
    if (source) {
      filtered = filtered.filter(img => img.source === source);
    }
    
    if (maxCloudCover < 100) {
      filtered = filtered.filter(img => img.cloudCover <= maxCloudCover);
    }
    
    // 按日期排序
    filtered.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    
    return filtered;
  }

  /**
   * 获取天地图影像
   */
  static async getTianDiTuImage(
    lon: number,
    lat: number,
    zoom: number = 15
  ): Promise<string> {
    // 天地图API密钥（需要申请）
    const tk = 'YOUR_TIANDITU_API_KEY';
    
    // 构建天地图影像URL
    const url = `https://t${Math.floor(Math.random() * 8)}.tianditu.gov.cn/img_w/wmts?` +
      `SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&` +
      `TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX=${zoom}&TILEROW=${lat}&TILECOL=${lon}&tk=${tk}`;
    
    return url;
  }

  /**
   * 计算NDVI（归一化植被指数）
   */
  static calculateNDVI(nir: number, red: number): number {
    // NDVI = (NIR - Red) / (NIR + Red)
    if (nir + red === 0) return 0;
    return (nir - red) / (nir + red);
  }

  /**
   * 计算EVI（增强型植被指数）
   */
  static calculateEVI(nir: number, red: number, blue: number): number {
    // EVI = 2.5 * (NIR - Red) / (NIR + 6 * Red - 7.5 * Blue + 1)
    const denominator = nir + 6 * red - 7.5 * blue + 1;
    if (denominator === 0) return 0;
    return 2.5 * (nir - red) / denominator;
  }

  /**
   * 计算SAVI（土壤调节植被指数）
   */
  static calculateSAVI(nir: number, red: number, L: number = 0.5): number {
    // SAVI = ((NIR - Red) / (NIR + Red + L)) * (1 + L)
    const denominator = nir + red + L;
    if (denominator === 0) return 0;
    return ((nir - red) / denominator) * (1 + L);
  }

  /**
   * 对比两个时期的影像
   */
  static compareImages(
    image1: SatelliteImage,
    image2: SatelliteImage
  ): ImageComparisonResult {
    const ndviChange = image2.ndvi - image1.ndvi;
    const eviChange = image2.evi - image1.evi;
    
    // 确定变化类型
    let changeType: 'improvement' | 'decline' | 'stable';
    if (ndviChange > 0.1) {
      changeType = 'improvement';
    } else if (ndviChange < -0.1) {
      changeType = 'decline';
    } else {
      changeType = 'stable';
    }
    
    // 生成变化描述
    const changeDescription = this._generateChangeDescription(ndviChange, eviChange);
    
    // 生成建议
    const recommendations = this._generateRecommendations(changeType, image2);
    
    return {
      image1,
      image2,
      ndviChange,
      eviChange,
      changeType,
      changeDescription,
      recommendations
    };
  }

  /**
   * 时序分析
   */
  static analyzeTimeSeries(images: SatelliteImage[]): TimeSeriesAnalysis {
    if (images.length === 0) {
      throw new Error('No images provided for analysis');
    }

    // 按日期排序
    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 eviValues = sortedImages.map(img => img.evi);

    // 计算趋势
    const trend = this._calculateTrend(ndviValues);
    
    // 判断生长阶段
    const growthStage = this._determineGrowthStage(ndviValues);
    
    // 计算健康分数（0-100）
    const avgNDVI = ndviValues.reduce((a, b) => a + b, 0) / ndviValues.length;
    const healthScore = Math.round(avgNDVI * 100);
    
    // 生成警报
    const alerts = this._generateAlerts(sortedImages);

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

  /**
   * 获取影像质量评价
   */
  static assessImageQuality(image: SatelliteImage): string {
    if (image.cloudCover < 10 && image.ndvi > 0) {
      return 'excellent';
    } else if (image.cloudCover < 20) {
      return 'good';
    } else if (image.cloudCover < 30) {
      return 'fair';
    } else {
      return 'poor';
    }
  }

  /**
   * 获取NDVI等级描述
   */
  static getNDVILabel(ndvi: number): string {
    if (ndvi > NDVI_THRESHOLDS.excellent) return '长势旺盛';
    if (ndvi > NDVI_THRESHOLDS.good) return '长势良好';
    if (ndvi > NDVI_THRESHOLDS.fair) return '长势一般';
    if (ndvi > NDVI_THRESHOLDS.poor) return '长势较弱';
    return '无植被';
  }

  /**
   * 获取NDVI颜色
   */
  static getNDVIColor(ndvi: number): string {
    if (ndvi > NDVI_THRESHOLDS.excellent) return '#22c55e'; // green-500
    if (ndvi > NDVI_THRESHOLDS.good) return '#84cc16'; // lime-500
    if (ndvi > NDVI_THRESHOLDS.fair) return '#eab308'; // yellow-500
    if (ndvi > NDVI_THRESHOLDS.poor) return '#f97316'; // orange-500
    return '#ef4444'; // red-500
  }

  /**
   * 下载影像
   */
  static async downloadImage(
    image: SatelliteImage,
    format: 'tif' | 'jpg' | 'png' = 'jpg'
  ): Promise<void> {
    // 模拟下载
    const filename = `${image.source}_${image.date}.${format}`;
    console.log(`Downloading ${filename}...`);
    
    // 实际应用中这里应该调用真实的下载API
    // 创建下载链接
    const link = document.createElement('a');
    link.href = image.fullImageUrl;
    link.download = filename;
    link.click();
  }

  // ===== 私有辅助方法 =====

  /**
   * 生成模拟影像数据（用于演示）
   */
  private static _generateMockImages(startDate: string, endDate: string): SatelliteImage[] {
    const images: SatelliteImage[] = [];
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    // 生成每个月的影像
    let current = new Date(start);
    let id = 1;
    
    while (current <= end) {
      // Sentinel-2 影像（5天一次）
      if (id % 3 === 0) {
        const ndvi = 0.6 + Math.random() * 0.3;
        images.push({
          id: `sentinel-${id}`,
          date: current.toISOString().split('T')[0],
          source: 'Sentinel-2',
          cloudCover: Math.random() * 40,
          resolution: 10,
          ndvi: ndvi,
          evi: ndvi * 0.85,
          savi: ndvi * 0.75,
          lai: ndvi * 5,
          thumbnail: `https://placeholder.com/sentinel-${id}`,
          fullImageUrl: `https://api.sentinel.com/image/${id}`,
          season: this._getSeason(current),
          quality: 'good',
          bands: {
            red: 'B4',
            green: 'B3',
            blue: 'B2',
            nir: 'B8'
          }
        });
      }
      
      // Landsat-8 影像（16天一次）
      if (id % 5 === 0) {
        const ndvi = 0.55 + Math.random() * 0.35;
        images.push({
          id: `landsat-${id}`,
          date: current.toISOString().split('T')[0],
          source: 'Landsat-8',
          cloudCover: Math.random() * 35,
          resolution: 30,
          ndvi: ndvi,
          evi: ndvi * 0.88,
          savi: ndvi * 0.78,
          lai: ndvi * 4.8,
          thumbnail: `https://placeholder.com/landsat-${id}`,
          fullImageUrl: `https://api.landsat.com/image/${id}`,
          season: this._getSeason(current),
          quality: 'good',
          bands: {
            red: 'B4',
            green: 'B3',
            blue: 'B2',
            nir: 'B5'
          }
        });
      }
      
      current.setDate(current.getDate() + 5);
      id++;
    }
    
    return images;
  }

  /**
   * 获取季节
   */
  private static _getSeason(date: Date): string {
    const month = date.getMonth() + 1;
    if (month >= 3 && month <= 5) return '春季';
    if (month >= 6 && month <= 8) return '夏季';
    if (month >= 9 && month <= 11) return '秋季';
    return '冬季';
  }

  /**
   * 生成变化描述
   */
  private static _generateChangeDescription(ndviChange: number, eviChange: number): string {
    if (ndviChange > 0.2) {
      return '植被覆盖度显著增加，作物长势明显改善';
    } else if (ndviChange > 0.1) {
      return '植被覆盖度有所增加，作物长势良好';
    } else if (ndviChange < -0.2) {
      return '植被覆盖度显著下降，需要关注作物健康状况';
    } else if (ndviChange < -0.1) {
      return '植被覆盖度有所下降，建议加强管理';
    } else {
      return '植被覆盖度基本稳定，作物生长正常';
    }
  }

  /**
   * 生成建议
   */
  private static _generateRecommendations(
    changeType: 'improvement' | 'decline' | 'stable',
    currentImage: SatelliteImage
  ): string[] {
    const recommendations: string[] = [];
    
    if (changeType === 'decline') {
      recommendations.push('建议增加灌溉频次，确保水分供应');
      recommendations.push('检查是否存在病虫害，及时防治');
      recommendations.push('适当追施氮肥，促进作物生长');
    } else if (changeType === 'improvement') {
      recommendations.push('继续保持当前管理措施');
      recommendations.push('适时进行田间观察，记录生长情况');
      recommendations.push('注意防范极端天气影响');
    } else {
      recommendations.push('维持现有灌溉和施肥计划');
      recommendations.push('定期监测作物生长状态');
    }
    
    // 根据NDVI值添加额外建议
    if (currentImage.ndvi < 0.4) {
      recommendations.push('⚠️ NDVI值偏低，建议进行土壤检测');
    }
    
    // 根据云量添加建议
    if (currentImage.cloudCover > 30) {
      recommendations.push('当前云量较高，建议选择晴天影像进行分析');
    }
    
    return recommendations;
  }

  /**
   * 计算趋势
   */
  private static _calculateTrend(values: number[]): 'increasing' | 'decreasing' | 'fluctuating' | 'stable' {
    if (values.length < 2) return 'stable';
    
    // 简单线性回归
    const n = values.length;
    const sumX = (n * (n - 1)) / 2;
    const sumY = values.reduce((a, b) => a + b, 0);
    const sumXY = values.reduce((sum, y, x) => sum + x * y, 0);
    const sumX2 = (n * (n - 1) * (2 * n - 1)) / 6;
    
    const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
    
    // 计算波动性
    const mean = sumY / n;
    const variance = values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / n;
    const stdDev = Math.sqrt(variance);
    
    if (Math.abs(slope) < 0.01 && stdDev < 0.05) {
      return 'stable';
    } else if (stdDev > 0.15) {
      return 'fluctuating';
    } else if (slope > 0.01) {
      return 'increasing';
    } else if (slope < -0.01) {
      return 'decreasing';
    }
    
    return 'stable';
  }

  /**
   * 判断生长阶段
   */
  private static _determineGrowthStage(ndviValues: number[]): string {
    if (ndviValues.length === 0) return '未知';
    
    const latestNDVI = ndviValues[ndviValues.length - 1];
    const avgNDVI = ndviValues.reduce((a, b) => a + b, 0) / ndviValues.length;
    
    if (latestNDVI < 0.3) {
      return '苗期';
    } else if (latestNDVI < 0.5) {
      return '生长期';
    } else if (latestNDVI < 0.7) {
      return '旺长期';
    } else if (latestNDVI >= 0.7 && latestNDVI < 0.85) {
      return '成熟前期';
    } else {
      return '成熟期';
    }
  }

  /**
   * 生成警报
   */
  private static _generateAlerts(images: SatelliteImage[]): string[] {
    const alerts: string[] = [];
    
    if (images.length < 2) return alerts;
    
    // 检查最近的NDVI变化
    const recent = images.slice(-3);
    const ndviValues = recent.map(img => img.ndvi);
    
    // NDVI急剧下降
    if (ndviValues.length >= 2) {
      const change = ndviValues[ndviValues.length - 1] - ndviValues[0];
      if (change < -0.2) {
        alerts.push('⚠️ 警告：近期植被指数急剧下降，请检查作物健康状况');
      }
    }
    
    // 云量过高
    const highCloudImages = recent.filter(img => img.cloudCover > 40);
    if (highCloudImages.length >= 2) {
      alerts.push('☁️ 提示：近期云量较高，建议选择晴天影像进行分析');
    }
    
    // NDVI持续低迷
    const lowNDVIImages = recent.filter(img => img.ndvi < 0.4);
    if (lowNDVIImages.length >= 2) {
      alerts.push('⚠️ 注意：植被指数持续偏低，建议加强田间管理');
    }
    
    return alerts;
  }
}

// ===== 导出工具函数 =====

/**
 * 获取云量颜色类
 */
export function getCloudCoverColorClass(cloudCover: number): string {
  if (cloudCover < 10) return 'text-green-600 bg-green-100';
  if (cloudCover < 20) return 'text-yellow-600 bg-yellow-100';
  if (cloudCover < 30) return 'text-orange-600 bg-orange-100';
  return 'text-red-600 bg-red-100';
}

/**
 * 格式化日期
 */
export function formatImageDate(date: string): string {
  const d = new Date(date);
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
}

/**
 * 获取数据源图标
 */
export function getDataSourceIcon(source: string): string {
  const icons: Record<string, string> = {
    'Sentinel-2': '🛰️',
    'Landsat-8': '🛰️',
    'Landsat-9': '🛰️',
    '天地图': '🗺️',
    'GF-1': '🛰️',
    'GF-2': '🛰️'
  };
  return icons[source] || '📡';
}
