'use client';

import { SpatialAnalysisState, SpatialAnalysisAction, LandBlock, AnalysisResult, BatchAnalysisTask, EvaluationFactor } from './spatialAnalysisReducer';

// 空间分析服务接口
interface SpatialAnalysisService {
  analyzeBlock(block: LandBlock, factors: EvaluationFactor[], weights: any): Promise<{
    success: boolean;
    suitabilityIndex: number;
    result?: AnalysisResult;
    error?: string;
  }>;
}

// 模拟空间分析服务
class MockSpatialAnalysisService implements SpatialAnalysisService {
  async analyzeBlock(block: LandBlock, factors: EvaluationFactor[], weights: any): Promise<{
    success: boolean;
    suitabilityIndex: number;
    result?: AnalysisResult;
    error?: string;
  }> {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 1200));

    try {
      // 模拟分析失败的情况 (10% 概率)
      if (Math.random() < 0.1) {
        throw new Error('空间分析服务暂时不可用');
      }

      // 读取各项因子数据
      const factorData = await this.readFactorData(block);

      // 进行加权计算
      const suitabilityIndex = this.calculateWeightedScore(factorData, factors, weights);

      // 生成详细分析结果
      const result = this.generateAnalysisResult(block, factorData, suitabilityIndex, weights);

      return {
        success: true,
        suitabilityIndex,
        result
      };
    } catch (error) {
      return {
        success: false,
        suitabilityIndex: 0,
        error: error instanceof Error ? error.message : '分析失败'
      };
    }
  }

  private async readFactorData(block: LandBlock): Promise<any> {
    // 模拟从各种数据源读取因子数据
    await new Promise(resolve => setTimeout(resolve, 200));

    return {
      // 土壤因子数据
      soilFactors: {
        ph: block.pH || (6.0 + Math.random() * 2),
        organicMatter: block.organicMatter || (1.5 + Math.random() * 2),
        nitrogen: block.nitrogen || (60 + Math.random() * 80),
        phosphorus: block.phosphorus || (30 + Math.random() * 40),
        potassium: block.potassium || (80 + Math.random() * 80),
        soilType: block.soilType,
        texture: this.getSoilTexture(block.soilType)
      },

      // 气候因子数据 (模拟从气象API获取)
      climateFactors: {
        temperature: 15 + Math.random() * 20, // 年均温度
        rainfall: 400 + Math.random() * 800, // 年降雨量
        sunlight: 1600 + Math.random() * 800, // 年日照时数
        humidity: 50 + Math.random() * 30,
        frostFreeDays: 180 + Math.random() * 60
      },

      // 地形因子数据 (模拟从地形API获取)
      topographyFactors: {
        elevation: block.elevation || (20 + Math.random() * 100),
        slope: block.slope || (Math.random() * 10),
        aspect: Math.floor(Math.random() * 360), // 坡向
        relief: Math.random() * 50, // 地形起伏度
        drainageIndex: 0.3 + Math.random() * 0.7 // 排水指数
      },

      // 基础设施数据
      infrastructureFactors: {
        irrigationType: block.irrigation,
        irrigationScore: this.getIrrigationScore(block.irrigation),
        accessibility: 0.4 + Math.random() * 0.6, // 交通便利性
        distanceToRoad: Math.random() * 5, // 到道路距离(km)
        distanceToMarket: Math.random() * 20, // 到市场距离(km)
        powerSupply: Math.random() > 0.3, // 电力供应
        waterSupply: Math.random() > 0.2 // 水源供应
      }
    };
  }

  private getSoilTexture(soilType: string): string {
    const textureMap: { [key: string]: string } = {
      '壤土': 'loam',
      '砂壤土': 'sandy_loam',
      '黏土': 'clay',
      '砂土': 'sandy',
      '砾质土': 'gravelly'
    };
    return textureMap[soilType] || 'loam';
  }

  private getIrrigationScore(irrigationType: string): number {
    const scoreMap: { [key: string]: number } = {
      '滴灌': 0.95,
      '喷灌': 0.85,
      '漫灌': 0.70,
      '无灌溉': 0.30
    };
    return scoreMap[irrigationType] || 0.70;
  }

  private calculateWeightedScore(factorData: any, factors: EvaluationFactor[], weights: any): number {
    let totalScore = 0;
    let totalWeight = 0;

    // 土壤因子得分计算
    const soilWeight = weights.soil || 0.35;
    const soilScore = this.calculateSoilScore(factorData.soilFactors, factors);
    totalScore += soilScore * soilWeight;
    totalWeight += soilWeight;

    // 气候因子得分计算
    const climateWeight = weights.climate || 0.30;
    const climateScore = this.calculateClimateScore(factorData.climateFactors, factors);
    totalScore += climateScore * climateWeight;
    totalWeight += climateWeight;

    // 地形因子得分计算
    const topographyWeight = weights.topography || 0.20;
    const topographyScore = this.calculateTopographyScore(factorData.topographyFactors, factors);
    totalScore += topographyScore * topographyWeight;
    totalWeight += topographyWeight;

    // 基础设施因子得分计算
    const infrastructureWeight = weights.infrastructure || 0.15;
    const infrastructureScore = this.calculateInfrastructureScore(factorData.infrastructureFactors, factors);
    totalScore += infrastructureScore * infrastructureWeight;
    totalWeight += infrastructureWeight;

    return Math.round(totalWeight > 0 ? (totalScore / totalWeight) * 100 : 0);
  }

  private calculateSoilScore(soilFactors: any, factors: EvaluationFactor[]): number {
    let score = 0;
    let count = 0;

    // pH值评分
    if (soilFactors.ph >= 6.0 && soilFactors.ph <= 7.5) {
      score += 90;
    } else if (soilFactors.ph >= 5.5 && soilFactors.ph <= 8.0) {
      score += 70;
    } else {
      score += 40;
    }
    count++;

    // 有机质评分
    if (soilFactors.organicMatter >= 2.5) {
      score += 90;
    } else if (soilFactors.organicMatter >= 1.5) {
      score += 70;
    } else {
      score += 45;
    }
    count++;

    // 养分评分 (NPK)
    const npkScore = Math.min(100, (soilFactors.nitrogen + soilFactors.phosphorus + soilFactors.potassium) / 3);
    score += npkScore;
    count++;

    return count > 0 ? score / count : 50;
  }

  private calculateClimateScore(climateFactors: any, factors: EvaluationFactor[]): number {
    let score = 0;
    let count = 0;

    // 温度适宜性
    if (climateFactors.temperature >= 15 && climateFactors.temperature <= 25) {
      score += 90;
    } else if (climateFactors.temperature >= 10 && climateFactors.temperature <= 30) {
      score += 70;
    } else {
      score += 50;
    }
    count++;

    // 降雨适宜性
    if (climateFactors.rainfall >= 500 && climateFactors.rainfall <= 1000) {
      score += 90;
    } else if (climateFactors.rainfall >= 300 && climateFactors.rainfall <= 1500) {
      score += 70;
    } else {
      score += 45;
    }
    count++;

    // 日照充足性
    if (climateFactors.sunlight >= 2000) {
      score += 90;
    } else if (climateFactors.sunlight >= 1600) {
      score += 75;
    } else {
      score += 60;
    }
    count++;

    return count > 0 ? score / count : 50;
  }

  private calculateTopographyScore(topographyFactors: any, factors: EvaluationFactor[]): number {
    let score = 0;
    let count = 0;

    // 坡度评分
    if (topographyFactors.slope <= 3) {
      score += 95;
    } else if (topographyFactors.slope <= 6) {
      score += 80;
    } else if (topographyFactors.slope <= 15) {
      score += 60;
    } else {
      score += 30;
    }
    count++;

    // 海拔适宜性
    if (topographyFactors.elevation <= 100) {
      score += 90;
    } else if (topographyFactors.elevation <= 300) {
      score += 80;
    } else if (topographyFactors.elevation <= 600) {
      score += 65;
    } else {
      score += 45;
    }
    count++;

    // 排水条件
    score += topographyFactors.drainageIndex * 100;
    count++;

    return count > 0 ? score / count : 50;
  }

  private calculateInfrastructureScore(infrastructureFactors: any, factors: EvaluationFactor[]): number {
    let score = 0;
    let count = 0;

    // 灌溉条件
    score += infrastructureFactors.irrigationScore * 100;
    count++;

    // 交通便利性
    score += infrastructureFactors.accessibility * 100;
    count++;

    // 基础设施完善度
    const infrastructureScore =
      (infrastructureFactors.powerSupply ? 50 : 0) +
      (infrastructureFactors.waterSupply ? 50 : 0);
    score += infrastructureScore;
    count++;

    return count > 0 ? score / count : 50;
  }

  private generateAnalysisResult(block: LandBlock, factorData: any, suitabilityIndex: number, weights: any): AnalysisResult {
    const soilScore = this.calculateSoilScore(factorData.soilFactors, []);
    const climateScore = this.calculateClimateScore(factorData.climateFactors, []);
    const topographyScore = this.calculateTopographyScore(factorData.topographyFactors, []);
    const infrastructureScore = this.calculateInfrastructureScore(factorData.infrastructureFactors, []);

    // 生成作物推荐
    const recommendedCrops = this.generateCropRecommendations(block, factorData, suitabilityIndex);

    // 生成风险因素
    const riskFactors = this.generateRiskFactors(block, factorData, suitabilityIndex);

    // 生成改进建议
    const improvementSuggestions = this.generateImprovementSuggestions(block, factorData, soilScore, climateScore, topographyScore, infrastructureScore);

    return {
      blockId: block.id,
      blockName: block.name,
      overallScore: suitabilityIndex,
      soilScore,
      climateScore,
      topographyScore,
      infrastructureScore,
      recommendedCrops,
      riskFactors,
      improvementSuggestions,
      estimatedYield: Math.round(block.area * (suitabilityIndex / 100) * (6000 + Math.random() * 4000)),
      economicReturn: Math.round(block.area * (suitabilityIndex / 100) * (8000 + Math.random() * 6000))
    };
  }

  private generateCropRecommendations(block: LandBlock, factorData: any, suitabilityIndex: number): any[] {
    // 简化的作物推荐逻辑
    const crops = [
      { name: '小麦', suitabilityScore: Math.min(95, suitabilityIndex + Math.random() * 10 - 5) },
      { name: '玉米', suitabilityScore: Math.min(95, suitabilityIndex + Math.random() * 15 - 5) },
      { name: '水稻', suitabilityScore: factorData.climateFactors.rainfall > 800 ? Math.min(95, suitabilityIndex + Math.random() * 10) : Math.max(40, suitabilityIndex - 20) },
      { name: '大豆', suitabilityScore: Math.min(95, suitabilityIndex + Math.random() * 8 - 4) },
      { name: '棉花', suitabilityScore: Math.min(95, suitabilityIndex + Math.random() * 12 - 6) }
    ];

    return crops
      .map(crop => ({
        crop: {
          id: crop.name.toLowerCase(),
          name: crop.name,
          category: '粮食作物',
          growthCycle: 100 + Math.floor(Math.random() * 50),
          economicValue: 2000 + Math.floor(Math.random() * 6000),
          riskLevel: crop.suitabilityScore > 70 ? 'low' : crop.suitabilityScore > 50 ? 'medium' : 'high' as const
        },
        suitabilityScore: Math.round(crop.suitabilityScore),
        matchPercentage: Math.round(crop.suitabilityScore),
        advantages: crop.suitabilityScore > 70 ? ['土壤条件适宜', '气候匹配度高'] : ['需要改善条件'],
        disadvantages: crop.suitabilityScore < 60 ? ['土壤需要改良', '气候条件一般'] : [],
        managementNotes: ['注意合理施肥', '加强田间管理']
      }))
      .filter(crop => crop.suitabilityScore > 40)
      .sort((a, b) => b.suitabilityScore - a.suitabilityScore)
      .slice(0, 3);
  }

  private generateRiskFactors(block: LandBlock, factorData: any, suitabilityIndex: number): string[] {
    const risks = [];

    if (suitabilityIndex < 40) {
      risks.push('综合条件较差，种植风险较高');
    }

    if (factorData.soilFactors.ph < 6.0 || factorData.soilFactors.ph > 7.5) {
      risks.push('土壤pH值偏离理想范围');
    }

    if (factorData.soilFactors.organicMatter < 1.5) {
      risks.push('土壤有机质含量偏低');
    }

    if (factorData.topographyFactors.slope > 8) {
      risks.push('坡度较大，存在水土流失风险');
    }

    if (factorData.infrastructureFactors.irrigationScore < 0.5) {
      risks.push('灌溉条件不足，依赖自然降水');
    }

    if (factorData.climateFactors.rainfall < 400) {
      risks.push('降雨量偏少，干旱风险较高');
    }

    return risks.length > 0 ? risks : ['无明显风险因素'];
  }

  private generateImprovementSuggestions(block: LandBlock, factorData: any, soilScore: number, climateScore: number, topographyScore: number, infrastructureScore: number): string[] {
    const suggestions = [];

    if (soilScore < 70) {
      suggestions.push('增施有机肥，改善土壤结构');
    }

    if (soilScore < 60) {
      suggestions.push('进行土壤检测，针对性补充养分');
    }

    if (climateScore < 70) {
      suggestions.push('选择适应性更强的作物品种');
    }

    if (topographyScore < 70) {
      suggestions.push('修建梯田或等高线种植');
    }

    if (infrastructureScore < 70) {
      suggestions.push('完善灌溉和排水系统');
    }

    if (factorData.infrastructureFactors.accessibility < 0.6) {
      suggestions.push('改善田间道路条件');
    }

    return suggestions.length > 0 ? suggestions : ['当前条件良好，继续保持'];
  }
}

// 批量分析管理器
export class BatchAnalysisManager {
  private service: SpatialAnalysisService;
  private dispatch: React.Dispatch<SpatialAnalysisAction>;
  private isRunning: boolean = false;
  private currentTask: BatchAnalysisTask | null = null;

  constructor(dispatch: React.Dispatch<SpatialAnalysisAction>) {
    this.service = new MockSpatialAnalysisService();
    this.dispatch = dispatch;
  }

  async startBatchAnalysis(
    taskName: string,
    factors: EvaluationFactor[],
    weightConfig: any
  ): Promise<void> {
    if (this.isRunning) {
      throw new Error('已有分析任务正在运行');
    }

    // 固定分析68个地块
    const totalFields = 68;
    const blockIds = Array.from({ length: totalFields }, (_, i) => `field-${i + 1}`);

    // 创建批量分析任务
    this.dispatch({
      type: 'START_BATCH_ANALYSIS',
      payload: { name: taskName, blockIds }
    });

    this.isRunning = true;

    try {
      // 获取创建的任务
      const task = await this.waitForTaskCreation();
      if (!task) return;

      this.currentTask = task;

      // 更新任务状态为运行中
      this.dispatch({
        type: 'UPDATE_BATCH_TASK',
        payload: {
          taskId: task.id,
          updates: {
            status: 'running',
            startedAt: new Date().toLocaleString('zh-CN'),
            totalBlocks: totalFields
          }
        }
      });

      // 循环处理所有地块
      const results: AnalysisResult[] = [];
      let highSuitability = 0;
      let mediumSuitability = 0;
      let lowSuitability = 0;

      for (let i = 0; i < totalFields; i++) {
        if (!this.isRunning) break; // 检查是否被取消

        const fieldId = `field-${i + 1}`;
        const fieldName = `地块${String.fromCharCode(65 + (i % 26))}${Math.floor(i / 26) + 1}`;

        // 创建临时地块对象
        const tempBlock: LandBlock = {
          id: fieldId,
          name: fieldName,
          area: 10 + Math.random() * 20, // 随机面积10-30亩
          location: { lat: 39.9042 + (Math.random() - 0.5) * 0.1, lng: 116.4074 + (Math.random() - 0.5) * 0.1 },
          soilType: ['壤土', '砂壤土', '黏土'][Math.floor(Math.random() * 3)],
          elevation: 20 + Math.random() * 100,
          slope: Math.random() * 10,
          irrigation: ['滴灌', '喷灌', '漫灌'][Math.floor(Math.random() * 3)],
          pH: 6.0 + Math.random() * 2,
          organicMatter: 1.5 + Math.random() * 2,
          nitrogen: 60 + Math.random() * 80,
          phosphorus: 30 + Math.random() * 40,
          potassium: 80 + Math.random() * 80
        };

        // 更新当前处理的地块
        this.dispatch({
          type: 'UPDATE_BATCH_TASK',
          payload: {
            taskId: task.id,
            updates: {
              currentProcessingBlock: fieldName,
              processedBlocks: i,
              progress: Math.round((i / totalFields) * 100)
            }
          }
        });

        try {
          // 调用空间分析服务
          const analysisResult = await this.service.analyzeBlock(tempBlock, factors, weightConfig);

          if (analysisResult.success && analysisResult.result) {
            results.push(analysisResult.result);

            // 统计适宜性等级
            const score = analysisResult.suitabilityIndex;
            if (score >= 80) {
              highSuitability++;
            } else if (score >= 60) {
              mediumSuitability++;
            } else {
              lowSuitability++;
            }
          }

          // 更新任务统计
          this.dispatch({
            type: 'UPDATE_BATCH_TASK',
            payload: {
              taskId: task.id,
              updates: {
                successCount: results.length,
                failedCount: i + 1 - results.length,
                progress: Math.round(((i + 1) / totalFields) * 100)
              }
            }
          });

        } catch (error) {
          console.error(`分析地块 ${fieldName} 失败:`, error);
        }
      }

      // 完成批量分析
      this.dispatch({
        type: 'COMPLETE_BATCH_ANALYSIS',
        payload: { taskId: task.id, results }
      });

    } catch (error) {
      console.error('批量分析失败:', error);
      if (this.currentTask) {
        this.dispatch({
          type: 'UPDATE_BATCH_TASK',
          payload: {
            taskId: this.currentTask.id,
            updates: {
              status: 'failed',
              errorMessage: error instanceof Error ? error.message : '未知错误'
            }
          }
        });
      }
    } finally {
      this.isRunning = false;
      this.currentTask = null;
    }
  }

  pauseAnalysis(): void {
    if (this.currentTask) {
      this.dispatch({
        type: 'PAUSE_BATCH_ANALYSIS',
        payload: { taskId: this.currentTask.id }
      });
    }
    this.isRunning = false;
  }

  resumeAnalysis(): void {
    if (this.currentTask) {
      this.dispatch({
        type: 'RESUME_BATCH_ANALYSIS',
        payload: { taskId: this.currentTask.id }
      });
      this.isRunning = true;
    }
  }

  cancelAnalysis(): void {
    if (this.currentTask) {
      this.dispatch({
        type: 'CANCEL_BATCH_ANALYSIS',
        payload: { taskId: this.currentTask.id }
      });
    }
    this.isRunning = false;
    this.currentTask = null;
  }

  private async waitForTaskCreation(): Promise<BatchAnalysisTask | null> {
    // 等待任务创建完成 - 直接返回一个虚拟任务
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          id: Date.now().toString(),
          name: '批量分析任务',
          status: 'running',
          createdAt: new Date().toLocaleString('zh-CN'),
          totalBlocks: 68,
          processedBlocks: 0,
          successCount: 0,
          failedCount: 0,
          selectedBlockIds: [],
          weightConfig: {},
          factorIds: [],
          progress: 0
        });
      }, 100);
    });
  }
}

export default BatchAnalysisManager;