/**
 * 作物-环境知识库
 * 定义各种作物的最适宜生长环境参数范围
 */

export interface CropKnowledge {
  id: string;
  cropName: string;
  category: '粮食作物' | '经济作物' | '蔬菜作物' | '果树';
  description: string;
  
  // 土壤环境要求
  soilRequirements: {
    ph: {
      optimal: [number, number];      // 最佳范围
      acceptable: [number, number];    // 可接受范围
    };
    organicMatter: {
      optimal: [number, number];       // g/kg
      acceptable: [number, number];
    };
    soilDepth: {
      optimal: [number, number];       // cm
      acceptable: [number, number];
    };
    nitrogen: {
      optimal: [number, number];       // g/kg
      acceptable: [number, number];
    };
    phosphorus: {
      optimal: [number, number];       // g/kg
      acceptable: [number, number];
    };
    potassium: {
      optimal: [number, number];       // g/kg
      acceptable: [number, number];
    };
    drainage: {
      optimal: [number, number];       // 0-100分
      acceptable: [number, number];
    };
  };
  
  // 气候环境要求
  climateRequirements: {
    temperature: {
      optimal: [number, number];       // °C
      acceptable: [number, number];
    };
    rainfall: {
      optimal: [number, number];       // mm/年
      acceptable: [number, number];
    };
    sunlight: {
      optimal: [number, number];       // 小时/天
      acceptable: [number, number];
    };
  };
  
  // 预期产量（kg/亩）
  expectedYield: {
    high: [number, number];            // 高适宜性条件下
    medium: [number, number];          // 中等适宜性条件下
    low: [number, number];             // 低适宜性条件下
  };
  
  // 生长周期
  growthCycle: {
    days: number;                      // 天数
    seasons: string[];                 // 适宜季节
  };
  
  // 风险因子
  riskFactors: {
    id: string;
    name: string;
    condition: string;                 // 触发条件描述
    severity: 'high' | 'medium' | 'low';
    suggestion: string;                // 应对建议
  }[];
}

/**
 * 作物知识库数据
 */
export const cropKnowledgeBase: CropKnowledge[] = [
  {
    id: 'rice',
    cropName: '水稻',
    category: '粮食作物',
    description: '主要粮食作物，喜温暖湿润气候，需水量大',
    
    soilRequirements: {
      ph: {
        optimal: [5.5, 6.5],
        acceptable: [5.0, 7.0],
      },
      organicMatter: {
        optimal: [25, 40],
        acceptable: [20, 45],
      },
      soilDepth: {
        optimal: [40, 80],
        acceptable: [30, 100],
      },
      nitrogen: {
        optimal: [1.5, 2.5],
        acceptable: [1.0, 3.0],
      },
      phosphorus: {
        optimal: [0.8, 1.5],
        acceptable: [0.6, 2.0],
      },
      potassium: {
        optimal: [15, 25],
        acceptable: [12, 30],
      },
      drainage: {
        optimal: [40, 70],
        acceptable: [30, 80],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [20, 30],
        acceptable: [15, 35],
      },
      rainfall: {
        optimal: [1000, 1500],
        acceptable: [800, 2000],
      },
      sunlight: {
        optimal: [6, 8],
        acceptable: [5, 10],
      },
    },
    
    expectedYield: {
      high: [500, 600],
      medium: [400, 500],
      low: [300, 400],
    },
    
    growthCycle: {
      days: 120,
      seasons: ['春季', '夏季'],
    },
    
    riskFactors: [
      {
        id: 'drought',
        name: '干旱风险',
        condition: '年降雨量 < 900mm',
        severity: 'high',
        suggestion: '建议配套灌溉设施，确保水源充足',
      },
      {
        id: 'ph_low',
        name: '土壤酸化',
        condition: 'pH < 5.5',
        severity: 'medium',
        suggestion: '建议施用石灰调节土壤pH值',
      },
      {
        id: 'temperature_low',
        name: '低温冷害',
        condition: '平均温度 < 18°C',
        severity: 'high',
        suggestion: '选择耐寒品种或调整种植时间',
      },
      {
        id: 'nitrogen_low',
        name: '氮素不足',
        condition: '全氮 < 1.2 g/kg',
        severity: 'medium',
        suggestion: '增施氮肥，建议尿素或复合肥',
      },
    ],
  },
  
  {
    id: 'corn',
    cropName: '玉米',
    category: '粮食作物',
    description: '重要粮食作物，耐旱性强，适应性广',
    
    soilRequirements: {
      ph: {
        optimal: [6.0, 7.5],
        acceptable: [5.5, 8.0],
      },
      organicMatter: {
        optimal: [20, 35],
        acceptable: [15, 40],
      },
      soilDepth: {
        optimal: [60, 100],
        acceptable: [50, 120],
      },
      nitrogen: {
        optimal: [1.0, 2.0],
        acceptable: [0.8, 2.5],
      },
      phosphorus: {
        optimal: [0.6, 1.2],
        acceptable: [0.4, 1.5],
      },
      potassium: {
        optimal: [18, 28],
        acceptable: [15, 35],
      },
      drainage: {
        optimal: [70, 90],
        acceptable: [60, 95],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [22, 30],
        acceptable: [18, 35],
      },
      rainfall: {
        optimal: [600, 1000],
        acceptable: [500, 1200],
      },
      sunlight: {
        optimal: [7, 10],
        acceptable: [6, 12],
      },
    },
    
    expectedYield: {
      high: [550, 700],
      medium: [450, 550],
      low: [350, 450],
    },
    
    growthCycle: {
      days: 110,
      seasons: ['春季', '夏季'],
    },
    
    riskFactors: [
      {
        id: 'waterlogging',
        name: '涝害风险',
        condition: '排水性 < 60分',
        severity: 'high',
        suggestion: '改善排水系统，开挖排水沟',
      },
      {
        id: 'ph_high',
        name: '土壤碱化',
        condition: 'pH > 7.8',
        severity: 'medium',
        suggestion: '施用酸性肥料或硫磺调节pH',
      },
      {
        id: 'potassium_low',
        name: '钾素缺乏',
        condition: '全钾 < 16 g/kg',
        severity: 'medium',
        suggestion: '增施钾肥，建议氯化钾或硫酸钾',
      },
      {
        id: 'high_temp',
        name: '高温胁迫',
        condition: '平均温度 > 32°C',
        severity: 'medium',
        suggestion: '适当遮阴，增加灌溉频次',
      },
    ],
  },
  
  {
    id: 'wheat',
    cropName: '小麦',
    category: '粮食作物',
    description: '主要粮食作物，喜冷凉气候，耐寒性强',
    
    soilRequirements: {
      ph: {
        optimal: [6.5, 7.5],
        acceptable: [6.0, 8.0],
      },
      organicMatter: {
        optimal: [18, 30],
        acceptable: [15, 35],
      },
      soilDepth: {
        optimal: [50, 90],
        acceptable: [40, 100],
      },
      nitrogen: {
        optimal: [1.2, 2.2],
        acceptable: [0.9, 2.5],
      },
      phosphorus: {
        optimal: [0.7, 1.3],
        acceptable: [0.5, 1.8],
      },
      potassium: {
        optimal: [16, 24],
        acceptable: [14, 28],
      },
      drainage: {
        optimal: [75, 90],
        acceptable: [65, 95],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [12, 20],
        acceptable: [5, 25],
      },
      rainfall: {
        optimal: [450, 750],
        acceptable: [350, 900],
      },
      sunlight: {
        optimal: [6, 8],
        acceptable: [5, 9],
      },
    },
    
    expectedYield: {
      high: [450, 550],
      medium: [350, 450],
      low: [250, 350],
    },
    
    growthCycle: {
      days: 210,
      seasons: ['秋季', '冬季', '春季'],
    },
    
    riskFactors: [
      {
        id: 'spring_cold',
        name: '倒春寒',
        condition: '春季平均温度 < 8°C',
        severity: 'high',
        suggestion: '选择抗寒品种，适当延迟播种',
      },
      {
        id: 'drought_spring',
        name: '春季干旱',
        condition: '春季降雨 < 100mm',
        severity: 'medium',
        suggestion: '及时灌溉，保持土壤湿润',
      },
      {
        id: 'organic_low',
        name: '有机质偏低',
        condition: '有机质 < 16 g/kg',
        severity: 'medium',
        suggestion: '增施有机肥，改良土壤结构',
      },
      {
        id: 'phosphorus_low',
        name: '磷素不足',
        condition: '全磷 < 0.6 g/kg',
        severity: 'low',
        suggestion: '基肥增施过磷酸钙',
      },
    ],
  },
  
  {
    id: 'soybean',
    cropName: '大豆',
    category: '粮食作物',
    description: '重要油料和蛋白作物，具有固氮能力',
    
    soilRequirements: {
      ph: {
        optimal: [6.0, 7.0],
        acceptable: [5.5, 7.5],
      },
      organicMatter: {
        optimal: [22, 35],
        acceptable: [18, 40],
      },
      soilDepth: {
        optimal: [45, 80],
        acceptable: [35, 90],
      },
      nitrogen: {
        optimal: [0.8, 1.5],
        acceptable: [0.6, 2.0],
      },
      phosphorus: {
        optimal: [0.8, 1.5],
        acceptable: [0.6, 2.0],
      },
      potassium: {
        optimal: [18, 26],
        acceptable: [15, 30],
      },
      drainage: {
        optimal: [70, 85],
        acceptable: [60, 90],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [20, 28],
        acceptable: [15, 32],
      },
      rainfall: {
        optimal: [500, 900],
        acceptable: [400, 1100],
      },
      sunlight: {
        optimal: [6, 9],
        acceptable: [5, 10],
      },
    },
    
    expectedYield: {
      high: [200, 280],
      medium: [160, 200],
      low: [120, 160],
    },
    
    growthCycle: {
      days: 100,
      seasons: ['春季', '夏季'],
    },
    
    riskFactors: [
      {
        id: 'waterlogging',
        name: '涝害风险',
        condition: '排水性 < 65分',
        severity: 'high',
        suggestion: '改善排水，避免积水',
      },
      {
        id: 'drought_pod',
        name: '结荚期干旱',
        condition: '夏季降雨 < 200mm',
        severity: 'medium',
        suggestion: '结荚期及时灌溉',
      },
      {
        id: 'phosphorus_critical',
        name: '磷素关键需求',
        condition: '全磷 < 0.7 g/kg',
        severity: 'medium',
        suggestion: '大豆对磷敏感，需重点补充',
      },
    ],
  },
  
  {
    id: 'cotton',
    cropName: '棉花',
    category: '经济作物',
    description: '重要纤维作物，喜温暖干燥气候',
    
    soilRequirements: {
      ph: {
        optimal: [6.5, 8.0],
        acceptable: [6.0, 8.5],
      },
      organicMatter: {
        optimal: [18, 28],
        acceptable: [15, 32],
      },
      soilDepth: {
        optimal: [60, 100],
        acceptable: [50, 120],
      },
      nitrogen: {
        optimal: [1.0, 1.8],
        acceptable: [0.8, 2.2],
      },
      phosphorus: {
        optimal: [0.6, 1.2],
        acceptable: [0.5, 1.5],
      },
      potassium: {
        optimal: [20, 30],
        acceptable: [16, 35],
      },
      drainage: {
        optimal: [80, 95],
        acceptable: [70, 100],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [25, 32],
        acceptable: [20, 35],
      },
      rainfall: {
        optimal: [500, 800],
        acceptable: [400, 1000],
      },
      sunlight: {
        optimal: [8, 12],
        acceptable: [7, 14],
      },
    },
    
    expectedYield: {
      high: [120, 160],
      medium: [90, 120],
      low: [60, 90],
    },
    
    growthCycle: {
      days: 180,
      seasons: ['春季', '夏季', '秋季'],
    },
    
    riskFactors: [
      {
        id: 'late_rain',
        name: '后期多雨',
        condition: '秋季降雨 > 300mm',
        severity: 'high',
        suggestion: '影响棉花采摘和品质，需排水',
      },
      {
        id: 'potassium_high',
        name: '钾素需求大',
        condition: '全钾 < 18 g/kg',
        severity: 'medium',
        suggestion: '棉花需钾量大，重点补充钾肥',
      },
      {
        id: 'temperature_low',
        name: '生长期温度不足',
        condition: '平均温度 < 22°C',
        severity: 'medium',
        suggestion: '延长生育期，影响产量',
      },
    ],
  },
  
  {
    id: 'tomato',
    cropName: '番茄',
    category: '蔬菜作物',
    description: '重要蔬菜作物，喜温暖，对光照要求高',
    
    soilRequirements: {
      ph: {
        optimal: [6.0, 7.0],
        acceptable: [5.5, 7.5],
      },
      organicMatter: {
        optimal: [28, 45],
        acceptable: [22, 50],
      },
      soilDepth: {
        optimal: [40, 70],
        acceptable: [30, 80],
      },
      nitrogen: {
        optimal: [1.5, 2.5],
        acceptable: [1.2, 3.0],
      },
      phosphorus: {
        optimal: [1.0, 2.0],
        acceptable: [0.8, 2.5],
      },
      potassium: {
        optimal: [22, 32],
        acceptable: [18, 38],
      },
      drainage: {
        optimal: [75, 90],
        acceptable: [65, 95],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [20, 28],
        acceptable: [15, 32],
      },
      rainfall: {
        optimal: [400, 700],
        acceptable: [300, 900],
      },
      sunlight: {
        optimal: [8, 12],
        acceptable: [6, 14],
      },
    },
    
    expectedYield: {
      high: [4000, 6000],
      medium: [3000, 4000],
      low: [2000, 3000],
    },
    
    growthCycle: {
      days: 95,
      seasons: ['春季', '秋季'],
    },
    
    riskFactors: [
      {
        id: 'humidity_high',
        name: '高湿病害',
        condition: '排水性 < 70分',
        severity: 'high',
        suggestion: '易发生病害，加强通风排湿',
      },
      {
        id: 'nitrogen_excess',
        name: '氮肥过量',
        condition: '全氮 > 2.8 g/kg',
        severity: 'medium',
        suggestion: '控制氮肥，避免徒长',
      },
      {
        id: 'temperature_extreme',
        name: '温度不适',
        condition: '温度 < 15°C 或 > 30°C',
        severity: 'medium',
        suggestion: '影响坐果，需温室栽培',
      },
    ],
  },
  
  {
    id: 'potato',
    cropName: '马铃薯',
    category: '粮食作物',
    description: '重要粮食和蔬菜作物，喜冷凉气候',
    
    soilRequirements: {
      ph: {
        optimal: [5.0, 6.5],
        acceptable: [4.5, 7.0],
      },
      organicMatter: {
        optimal: [25, 40],
        acceptable: [20, 45],
      },
      soilDepth: {
        optimal: [50, 80],
        acceptable: [40, 90],
      },
      nitrogen: {
        optimal: [1.2, 2.0],
        acceptable: [1.0, 2.5],
      },
      phosphorus: {
        optimal: [0.8, 1.6],
        acceptable: [0.6, 2.0],
      },
      potassium: {
        optimal: [20, 30],
        acceptable: [16, 35],
      },
      drainage: {
        optimal: [80, 95],
        acceptable: [70, 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: [2500, 3500],
      medium: [1800, 2500],
      low: [1200, 1800],
    },
    
    growthCycle: {
      days: 90,
      seasons: ['春季', '秋季'],
    },
    
    riskFactors: [
      {
        id: 'waterlogging',
        name: '涝害烂薯',
        condition: '排水性 < 75分',
        severity: 'high',
        suggestion: '必须排水良好，避免积水',
      },
      {
        id: 'ph_high',
        name: 'pH偏高',
        condition: 'pH > 6.8',
        severity: 'medium',
        suggestion: '易发生疮痂病，施用硫磺调酸',
      },
      {
        id: 'temperature_high',
        name: '高温影响',
        condition: '平均温度 > 24°C',
        severity: 'medium',
        suggestion: '块茎膨大受阻，影响产量',
      },
      {
        id: 'potassium_critical',
        name: '钾素关键',
        condition: '全钾 < 18 g/kg',
        severity: 'high',
        suggestion: '马铃薯需钾量大，影响品质',
      },
    ],
  },
  
  {
    id: 'peanut',
    cropName: '花生',
    category: '经济作物',
    description: '重要油料作物，喜温暖，耐旱耐瘠',
    
    soilRequirements: {
      ph: {
        optimal: [6.0, 7.0],
        acceptable: [5.5, 7.5],
      },
      organicMatter: {
        optimal: [18, 30],
        acceptable: [15, 35],
      },
      soilDepth: {
        optimal: [50, 80],
        acceptable: [40, 90],
      },
      nitrogen: {
        optimal: [0.8, 1.5],
        acceptable: [0.6, 2.0],
      },
      phosphorus: {
        optimal: [0.7, 1.4],
        acceptable: [0.5, 1.8],
      },
      potassium: {
        optimal: [16, 24],
        acceptable: [14, 28],
      },
      drainage: {
        optimal: [80, 95],
        acceptable: [70, 100],
      },
    },
    
    climateRequirements: {
      temperature: {
        optimal: [22, 30],
        acceptable: [18, 34],
      },
      rainfall: {
        optimal: [500, 700],
        acceptable: [400, 900],
      },
      sunlight: {
        optimal: [7, 10],
        acceptable: [6, 12],
      },
    },
    
    expectedYield: {
      high: [350, 450],
      medium: [280, 350],
      low: [200, 280],
    },
    
    growthCycle: {
      days: 120,
      seasons: ['春季', '夏季'],
    },
    
    riskFactors: [
      {
        id: 'waterlogging',
        name: '涝害风险',
        condition: '排水性 < 75分',
        severity: 'high',
        suggestion: '花生最忌涝，需沙质土壤',
      },
      {
        id: 'calcium_deficiency',
        name: '钙素缺乏',
        condition: 'pH < 5.8',
        severity: 'medium',
        suggestion: '易出现空壳，施用石灰补钙',
      },
      {
        id: 'late_rain',
        name: '后期多雨',
        condition: '秋季降雨 > 250mm',
        severity: 'medium',
        suggestion: '影响收获和品质',
      },
    ],
  },
];

/**
 * 根据地块环境参数匹配推荐作物
 */
export function matchCropsForField(fieldFactors: {
  ph: number;
  organic: number;
  depth: number;
  nitrogen: number;
  phosphorus: number;
  potassium: number;
  drainage: number;
  temperature?: number;
  rainfall?: number;
}): Array<{
  crop: CropKnowledge;
  matchScore: number;
  suitabilityLevel: '高度推荐' | '推荐' | '谨慎种植' | '不推荐';
  matchDetails: {
    factor: string;
    status: 'optimal' | 'acceptable' | 'unacceptable';
    value: number;
    range: string;
  }[];
  applicableRisks: typeof cropKnowledgeBase[0]['riskFactors'];
  expectedYield: [number, number];
}> {
  return cropKnowledgeBase.map(crop => {
    const matchDetails: any[] = [];
    let optimalMatches = 0;
    let acceptableMatches = 0;
    let totalFactors = 0;
    
    // 检查土壤因子匹配度
    const soilFactors = {
      pH值: { value: fieldFactors.ph, req: crop.soilRequirements.ph },
      有机质: { value: fieldFactors.organic, req: crop.soilRequirements.organicMatter },
      土层厚度: { value: fieldFactors.depth, req: crop.soilRequirements.soilDepth },
      全氮: { value: fieldFactors.nitrogen, req: crop.soilRequirements.nitrogen },
      全磷: { value: fieldFactors.phosphorus, req: crop.soilRequirements.phosphorus },
      全钾: { value: fieldFactors.potassium, req: crop.soilRequirements.potassium },
      排水性: { value: fieldFactors.drainage, req: crop.soilRequirements.drainage },
    };
    
    Object.entries(soilFactors).forEach(([name, data]) => {
      totalFactors++;
      let status: 'optimal' | 'acceptable' | 'unacceptable';
      
      if (data.value >= data.req.optimal[0] && data.value <= data.req.optimal[1]) {
        status = 'optimal';
        optimalMatches++;
      } else if (data.value >= data.req.acceptable[0] && data.value <= data.req.acceptable[1]) {
        status = 'acceptable';
        acceptableMatches++;
      } else {
        status = 'unacceptable';
      }
      
      matchDetails.push({
        factor: name,
        status,
        value: data.value,
        range: `最佳${data.req.optimal[0]}-${data.req.optimal[1]}`,
      });
    });
    
    // 计算匹配分数 (0-100)
    const matchScore = Math.round(
      (optimalMatches * 100 + acceptableMatches * 60) / totalFactors
    );
    
    // 确定适宜性等级
    let suitabilityLevel: '高度推荐' | '推荐' | '谨慎种植' | '不推荐';
    if (matchScore >= 85) {
      suitabilityLevel = '高度推荐';
    } else if (matchScore >= 70) {
      suitabilityLevel = '推荐';
    } else if (matchScore >= 50) {
      suitabilityLevel = '谨慎种植';
    } else {
      suitabilityLevel = '不推荐';
    }
    
    // 筛选适用的风险因子
    const applicableRisks = crop.riskFactors.filter(risk => {
      // 根据实际值判断是否触发风险
      if (risk.id === 'ph_low' && fieldFactors.ph < 5.5) return true;
      if (risk.id === 'ph_high' && fieldFactors.ph > 7.8) return true;
      if (risk.id === 'nitrogen_low' && fieldFactors.nitrogen < 1.2) return true;
      if (risk.id === 'phosphorus_low' && fieldFactors.phosphorus < 0.6) return true;
      if (risk.id === 'phosphorus_critical' && fieldFactors.phosphorus < 0.7) return true;
      if (risk.id === 'potassium_low' && fieldFactors.potassium < 16) return true;
      if (risk.id === 'potassium_high' && fieldFactors.potassium < 18) return true;
      if (risk.id === 'potassium_critical' && fieldFactors.potassium < 18) return true;
      if (risk.id === 'organic_low' && fieldFactors.organic < 16) return true;
      if (risk.id === 'waterlogging' && fieldFactors.drainage < 60) return true;
      if (risk.id === 'nitrogen_excess' && fieldFactors.nitrogen > 2.8) return true;
      if (risk.id === 'calcium_deficiency' && fieldFactors.ph < 5.8) return true;
      
      // 气候相关风险（使用默认值或传入值）
      const temp = fieldFactors.temperature || 22;
      const rainfall = fieldFactors.rainfall || 800;
      
      if (risk.id === 'drought' && rainfall < 900) return true;
      if (risk.id === 'drought_spring' && rainfall < 100) return true;
      if (risk.id === 'drought_pod' && rainfall < 200) return true;
      if (risk.id === 'temperature_low' && temp < 18) return true;
      if (risk.id === 'temperature_high' && temp > 24) return true;
      if (risk.id === 'high_temp' && temp > 32) return true;
      if (risk.id === 'spring_cold' && temp < 8) return true;
      if (risk.id === 'late_rain' && rainfall > 300) return true;
      if (risk.id === 'humidity_high' && fieldFactors.drainage < 70) return true;
      if (risk.id === 'temperature_extreme' && (temp < 15 || temp > 30)) return true;
      
      return false;
    });
    
    // 根据适宜性等级确定预期产量范围
    let expectedYield: [number, number];
    if (suitabilityLevel === '高度推荐') {
      expectedYield = crop.expectedYield.high;
    } else if (suitabilityLevel === '推荐') {
      expectedYield = crop.expectedYield.medium;
    } else {
      expectedYield = crop.expectedYield.low;
    }
    
    return {
      crop,
      matchScore,
      suitabilityLevel,
      matchDetails,
      applicableRisks,
      expectedYield,
    };
  }).sort((a, b) => b.matchScore - a.matchScore); // 按匹配分数降序排列
}
