/**
 * 作物知识库服务
 * 提供作物-环境适配数据和分析功能
 */

import { Crop, CropRecommendation, FieldFactors, MatchDetail, RiskFactor } from './multiFactorTypes';

// 作物知识库数据
export const cropKnowledgeBase: Crop[] = [
  // 粮食作物
  {
    id: 'rice',
    cropName: '水稻',
    category: '粮食作物',
    description: '水稻是世界上最重要的粮食作物之一，需要充足的水分和温暖的气候条件。',
    growthCycle: {
      days: 120,
      seasons: ['春季', '夏季']
    },
    soilRequirements: {
      ph: { optimal: [5.5, 6.5], acceptable: [5.0, 7.0] },
      organicMatter: { optimal: [25, 40], acceptable: [20, 50] },
      soilDepth: { optimal: [50, 100], acceptable: [30, 120] },
      nitrogen: { optimal: [1.5, 2.5], acceptable: [1.0, 3.0] },
      phosphorus: { optimal: [1.0, 2.0], acceptable: [0.5, 2.5] },
      potassium: { optimal: [15, 25], acceptable: [10, 30] },
      drainage: { optimal: [60, 80], acceptable: [50, 90] }
    },
    climateRequirements: {
      temperature: { optimal: [25, 32], acceptable: [20, 35] },
      rainfall: { optimal: [1000, 1500], acceptable: [800, 2000] },
      sunlight: { optimal: [6, 8], acceptable: [5, 10] }
    },
    expectedYield: {
      high: [600, 800],
      medium: [400, 600],
      low: [200, 400]
    },
    riskFactors: [
      {
        id: 'rice-cold',
        name: '低温冷害',
        condition: '温度低于20°C',
        suggestion: '选择耐寒品种，采用保温育苗技术',
        severity: 'high',
        category: 'climate'
      },
      {
        id: 'rice-drought',
        name: '干旱胁迫',
        condition: '降雨量低于800mm/年',
        suggestion: '建设灌溉系统，选用耐旱品种',
        severity: 'high',
        category: 'climate'
      }
    ]
  },
  {
    id: 'wheat',
    cropName: '小麦',
    category: '粮食作物',
    description: '小麦是温带地区重要的粮食作物，适应性较强，耐寒性较好。',
    growthCycle: {
      days: 110,
      seasons: ['秋季', '春季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.5], acceptable: [5.5, 8.0] },
      organicMatter: { optimal: [20, 35], acceptable: [15, 40] },
      soilDepth: { optimal: [60, 120], acceptable: [40, 150] },
      nitrogen: { optimal: [1.2, 2.0], acceptable: [0.8, 2.5] },
      phosphorus: { optimal: [0.8, 1.5], acceptable: [0.5, 2.0] },
      potassium: { optimal: [12, 20], acceptable: [8, 25] },
      drainage: { optimal: [70, 90], acceptable: [60, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [15, 22], acceptable: [10, 25] },
      rainfall: { optimal: [400, 600], acceptable: [300, 800] },
      sunlight: { optimal: [6, 8], acceptable: [5, 10] }
    },
    expectedYield: {
      high: [500, 700],
      medium: [300, 500],
      low: [150, 300]
    },
    riskFactors: [
      {
        id: 'wheat-heat',
        name: '高温热害',
        condition: '温度超过25°C',
        suggestion: '选择耐热品种，调整播种期',
        severity: 'medium',
        category: 'climate'
      }
    ]
  },
  {
    id: 'corn',
    cropName: '玉米',
    category: '粮食作物',
    description: '玉米是重要的粮食和饲料作物，喜温喜光，需肥量大。',
    growthCycle: {
      days: 130,
      seasons: ['春季', '夏季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [25, 40], acceptable: [20, 50] },
      soilDepth: { optimal: [80, 150], acceptable: [60, 200] },
      nitrogen: { optimal: [1.8, 2.8], acceptable: [1.2, 3.5] },
      phosphorus: { optimal: [1.2, 2.2], acceptable: [0.8, 3.0] },
      potassium: { optimal: [18, 30], acceptable: [12, 40] },
      drainage: { optimal: [80, 95], acceptable: [70, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [22, 30], acceptable: [18, 32] },
      rainfall: { optimal: [500, 800], acceptable: [400, 1000] },
      sunlight: { optimal: [7, 9], acceptable: [6, 10] }
    },
    expectedYield: {
      high: [700, 900],
      medium: [450, 700],
      low: [250, 450]
    },
    riskFactors: [
      {
        id: 'corn-drought',
        name: '干旱胁迫',
        condition: '降雨量低于400mm/年',
        suggestion: '建设灌溉设施，选用耐旱品种',
        severity: 'high',
        category: 'climate'
      },
      {
        id: 'corn-pollination',
        name: '授粉不良',
        condition: '开花期温度超过35°C',
        suggestion: '调整播种期，选择耐热品种',
        severity: 'medium',
        category: 'climate'
      }
    ]
  },

  // 经济作物
  {
    id: 'cotton',
    cropName: '棉花',
    category: '经济作物',
    description: '棉花是重要的经济作物，喜温喜光，对土壤要求较高。',
    growthCycle: {
      days: 150,
      seasons: ['春季', '夏季', '秋季']
    },
    soilRequirements: {
      ph: { optimal: [6.5, 8.0], acceptable: [6.0, 8.5] },
      organicMatter: { optimal: [20, 35], acceptable: [15, 40] },
      soilDepth: { optimal: [100, 180], acceptable: [80, 200] },
      nitrogen: { optimal: [1.5, 2.5], acceptable: [1.0, 3.0] },
      phosphorus: { optimal: [1.0, 2.0], acceptable: [0.6, 2.5] },
      potassium: { optimal: [20, 35], acceptable: [15, 45] },
      drainage: { optimal: [85, 95], acceptable: [75, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [25, 32], acceptable: [20, 35] },
      rainfall: { optimal: [400, 600], acceptable: [300, 800] },
      sunlight: { optimal: [8, 10], acceptable: [7, 12] }
    },
    expectedYield: {
      high: [120, 180],
      medium: [80, 120],
      low: [40, 80]
    },
    riskFactors: [
      {
        id: 'cotton-boll',
        name: '蕾铃脱落',
        condition: '湿度过大或温差过大',
        suggestion: '合理密植，加强田间管理',
        severity: 'medium',
        category: 'climate'
      }
    ]
  },
  {
    id: 'soybean',
    cropName: '大豆',
    category: '经济作物',
    description: '大豆是重要的油料作物，固氮能力强，适应性较广。',
    growthCycle: {
      days: 100,
      seasons: ['春季', '夏季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [25, 40], acceptable: [20, 50] },
      soilDepth: { optimal: [60, 120], acceptable: [40, 150] },
      nitrogen: { optimal: [1.2, 2.0], acceptable: [0.8, 2.5] },
      phosphorus: { optimal: [1.0, 2.0], acceptable: [0.6, 2.5] },
      potassium: { optimal: [15, 25], acceptable: [10, 30] },
      drainage: { optimal: [75, 90], acceptable: [65, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [20, 28], acceptable: [15, 32] },
      rainfall: { optimal: [500, 700], acceptable: [400, 900] },
      sunlight: { optimal: [6, 8], acceptable: [5, 10] }
    },
    expectedYield: {
      high: [250, 350],
      medium: [150, 250],
      low: [80, 150]
    },
    riskFactors: [
      {
        id: 'soybean-flower',
        name: '落花落荚',
        condition: '高温干旱或连续阴雨',
        suggestion: '合理施肥，科学管水',
        severity: 'medium',
        category: 'climate'
      }
    ]
  },

  // 蔬菜作物
  {
    id: 'tomato',
    cropName: '番茄',
    category: '蔬菜作物',
    description: '番茄是重要的蔬菜作物，喜温喜光，对肥水要求较高。',
    growthCycle: {
      days: 90,
      seasons: ['春季', '夏季', '秋季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [30, 45], acceptable: [25, 50] },
      soilDepth: { optimal: [40, 80], acceptable: [30, 100] },
      nitrogen: { optimal: [2.0, 3.0], acceptable: [1.5, 3.5] },
      phosphorus: { optimal: [1.5, 2.5], acceptable: [1.0, 3.0] },
      potassium: { optimal: [25, 40], acceptable: [20, 50] },
      drainage: { optimal: [80, 95], acceptable: [70, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [22, 28], acceptable: [18, 32] },
      rainfall: { optimal: [400, 600], acceptable: [300, 800] },
      sunlight: { optimal: [7, 9], acceptable: [6, 10] }
    },
    expectedYield: {
      high: [8000, 12000],
      medium: [5000, 8000],
      low: [2000, 5000]
    },
    riskFactors: [
      {
        id: 'tomato-disease',
        name: '病害高发',
        condition: '湿度过大，通风不良',
        suggestion: '加强病虫害防治，合理密植',
        severity: 'high',
        category: 'disease'
      }
    ]
  },
  {
    id: 'cucumber',
    cropName: '黄瓜',
    category: '蔬菜作物',
    description: '黄瓜是重要的蔬菜作物，喜温喜湿，生长周期短。',
    growthCycle: {
      days: 60,
      seasons: ['春季', '夏季', '秋季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [30, 45], acceptable: [25, 50] },
      soilDepth: { optimal: [30, 60], acceptable: [20, 80] },
      nitrogen: { optimal: [2.5, 3.5], acceptable: [2.0, 4.0] },
      phosphorus: { optimal: [1.8, 2.8], acceptable: [1.2, 3.5] },
      potassium: { optimal: [30, 45], acceptable: [25, 55] },
      drainage: { optimal: [85, 95], acceptable: [75, 100] }
    },
    climateRequirements: {
      temperature: { optimal: [22, 30], acceptable: [18, 32] },
      rainfall: { optimal: [500, 700], acceptable: [400, 900] },
      sunlight: { optimal: [6, 8], acceptable: [5, 10] }
    },
    expectedYield: {
      high: [6000, 9000],
      medium: [4000, 6000],
      low: [2000, 4000]
    },
    riskFactors: [
      {
        id: 'cucumber-pest',
        name: '虫害严重',
        condition: '温度适宜，湿度大',
        suggestion: '加强虫害监测，及时防治',
        severity: 'medium',
        category: 'pest'
      }
    ]
  }
];

/**
 * 匹配作物推荐
 */
export function matchCropsForField(fieldFactors: FieldFactors): CropRecommendation[] {
  const recommendations: CropRecommendation[] = [];

  for (const crop of cropKnowledgeBase) {
    const matchDetails: MatchDetail[] = [];
    let totalScore = 0;
    let factorCount = 0;

    // 土壤pH匹配
    const phScore = calculateFactorScore(
      fieldFactors.ph,
      crop.soilRequirements.ph.optimal,
      crop.soilRequirements.ph.acceptable
    );
    matchDetails.push({
      factor: 'pH',
      value: fieldFactors.ph,
      status: getScoreStatus(phScore),
      score: phScore
    });
    totalScore += phScore;
    factorCount++;

    // 有机质匹配
    const organicScore = calculateFactorScore(
      fieldFactors.organic,
      crop.soilRequirements.organicMatter.optimal,
      crop.soilRequirements.organicMatter.acceptable
    );
    matchDetails.push({
      factor: '有机质',
      value: fieldFactors.organic,
      status: getScoreStatus(organicScore),
      score: organicScore
    });
    totalScore += organicScore;
    factorCount++;

    // 土层厚度匹配
    const depthScore = calculateFactorScore(
      fieldFactors.depth,
      crop.soilRequirements.soilDepth.optimal,
      crop.soilRequirements.soilDepth.acceptable
    );
    matchDetails.push({
      factor: '土层厚度',
      value: fieldFactors.depth,
      status: getScoreStatus(depthScore),
      score: depthScore
    });
    totalScore += depthScore;
    factorCount++;

    // 全氮匹配
    const nitrogenScore = calculateFactorScore(
      fieldFactors.nitrogen,
      crop.soilRequirements.nitrogen.optimal,
      crop.soilRequirements.nitrogen.acceptable
    );
    matchDetails.push({
      factor: '全氮',
      value: fieldFactors.nitrogen,
      status: getScoreStatus(nitrogenScore),
      score: nitrogenScore
    });
    totalScore += nitrogenScore;
    factorCount++;

    // 全磷匹配
    const phosphorusScore = calculateFactorScore(
      fieldFactors.phosphorus,
      crop.soilRequirements.phosphorus.optimal,
      crop.soilRequirements.phosphorus.acceptable
    );
    matchDetails.push({
      factor: '全磷',
      value: fieldFactors.phosphorus,
      status: getScoreStatus(phosphorusScore),
      score: phosphorusScore
    });
    totalScore += phosphorusScore;
    factorCount++;

    // 全钾匹配
    const potassiumScore = calculateFactorScore(
      fieldFactors.potassium,
      crop.soilRequirements.potassium.optimal,
      crop.soilRequirements.potassium.acceptable
    );
    matchDetails.push({
      factor: '全钾',
      value: fieldFactors.potassium,
      status: getScoreStatus(potassiumScore),
      score: potassiumScore
    });
    totalScore += potassiumScore;
    factorCount++;

    // 排水性匹配
    const drainageScore = calculateFactorScore(
      fieldFactors.drainage,
      crop.soilRequirements.drainage.optimal,
      crop.soilRequirements.drainage.acceptable
    );
    matchDetails.push({
      factor: '排水性',
      value: fieldFactors.drainage,
      status: getScoreStatus(drainageScore),
      score: drainageScore
    });
    totalScore += drainageScore;
    factorCount++;

    // 气温匹配（如果有数据）
    if (fieldFactors.temperature !== undefined) {
      const tempScore = calculateFactorScore(
        fieldFactors.temperature,
        crop.climateRequirements.temperature.optimal,
        crop.climateRequirements.temperature.acceptable
      );
      matchDetails.push({
        factor: '温度',
        value: fieldFactors.temperature,
        status: getScoreStatus(tempScore),
        score: tempScore
      });
      totalScore += tempScore;
      factorCount++;
    }

    // 降雨匹配（如果有数据）
    if (fieldFactors.rainfall !== undefined) {
      const rainScore = calculateFactorScore(
        fieldFactors.rainfall,
        crop.climateRequirements.rainfall.optimal,
        crop.climateRequirements.rainfall.acceptable
      );
      matchDetails.push({
        factor: '降雨',
        value: fieldFactors.rainfall,
        status: getScoreStatus(rainScore),
        score: rainScore
      });
      totalScore += rainScore;
      factorCount++;
    }

    // 计算综合匹配分数
    const averageScore = Math.round(totalScore / factorCount);

    // 确定适宜性等级
    let suitabilityLevel: '高度推荐' | '推荐' | '谨慎种植' | '不推荐';
    if (averageScore >= 85) {
      suitabilityLevel = '高度推荐';
    } else if (averageScore >= 70) {
      suitabilityLevel = '推荐';
    } else if (averageScore >= 50) {
      suitabilityLevel = '谨慎种植';
    } else {
      suitabilityLevel = '不推荐';
    }

    // 获取适用风险因子
    const applicableRisks = crop.riskFactors.filter(risk => {
      if (risk.category === 'climate' && fieldFactors.temperature !== undefined) {
        return checkRiskCondition(risk.condition, fieldFactors);
      }
      // 其他风险因子的判断逻辑
      return false;
    });

    // 确定预期产量
    let expectedYield: [number, number];
    if (suitabilityLevel === '高度推荐') {
      expectedYield = crop.expectedYield.high;
    } else if (suitabilityLevel === '推荐') {
      expectedYield = crop.expectedYield.medium;
    } else {
      expectedYield = crop.expectedYield.low;
    }

    recommendations.push({
      crop,
      matchScore: averageScore,
      suitabilityLevel,
      matchDetails,
      applicableRisks,
      expectedYield
    });
  }

  // 按匹配分数排序
  return recommendations.sort((a, b) => b.matchScore - a.matchScore);
}

/**
 * 计算因子得分
 */
function calculateFactorScore(
  value: number,
  optimalRange: [number, number],
  acceptableRange: [number, number]
): number {
  // 最佳范围：100分
  if (value >= optimalRange[0] && value <= optimalRange[1]) {
    return 100;
  }

  // 可接受范围：60分
  if (value >= acceptableRange[0] && value <= acceptableRange[1]) {
    return 60;
  }

  // 偏离程度计算
  const optimalMid = (optimalRange[0] + optimalRange[1]) / 2;
  const deviation = Math.abs(value - optimalMid);
  const maxDeviation = Math.max(
    Math.abs(acceptableRange[0] - optimalMid),
    Math.abs(acceptableRange[1] - optimalMid)
  );

  // 根据偏离程度计算分数（0-60分）
  const scoreRatio = Math.max(0, 1 - deviation / maxDeviation);
  return Math.round(scoreRatio * 60);
}

/**
 * 获取得分状态
 */
function getScoreStatus(score: number): 'optimal' | 'acceptable' | 'poor' {
  if (score >= 90) return 'optimal';
  if (score >= 60) return 'acceptable';
  return 'poor';
}

/**
 * 检查风险条件
 */
function checkRiskCondition(condition: string, fieldFactors: FieldFactors): boolean {
  // 简化的条件判断逻辑
  if (condition.includes('温度低于') && fieldFactors.temperature !== undefined) {
    const threshold = parseInt(condition.match(/\d+/)?.[0] || '0');
    return fieldFactors.temperature < threshold;
  }

  if (condition.includes('温度超过') && fieldFactors.temperature !== undefined) {
    const threshold = parseInt(condition.match(/\d+/)?.[0] || '0');
    return fieldFactors.temperature > threshold;
  }

  if (condition.includes('降雨量低于') && fieldFactors.rainfall !== undefined) {
    const threshold = parseInt(condition.match(/\d+/)?.[0] || '0');
    return fieldFactors.rainfall < threshold;
  }

  return false;
}