import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
// DialogDescription import fix
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogTrigger } from '../ui/dialog';
import { Progress } from '../ui/progress';
import { Slider } from '../ui/slider';
import {
  Leaf,
  TrendingUp,
  Award,
  AlertTriangle,
  CheckCircle2,
  Play,
  Settings,
  Download,
  Eye,
  Calculator,
  Database,
  RefreshCw,
  Zap,
  Target,
  Droplet,
  Cloud,
  Sun,
  ThermometerSun,
  BookOpen,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { cropKnowledgeBase, matchCropsForField } from '../../lib/cropKnowledgeBase';

interface FieldSuitabilityEvaluationProps {
  activePath?: string;
}

interface EvaluationFactor {
  id: string;
  name: string;
  value: number;
  weight: number;
  unit: string;
  optimalRange: [number, number];
  score: number;
}

interface SuitabilityResult {
  fieldId: string;
  fieldName: string;
  totalScore: number;
  grade: '高度适宜' | '一般适宜' | '不适宜';
  factors: EvaluationFactor[];
  timestamp: string;
}

export function FieldSuitabilityEvaluation({ activePath }: FieldSuitabilityEvaluationProps) {
  const [selectedField, setSelectedField] = useState('field-1');
  const [showWeightConfig, setShowWeightConfig] = useState(false);
  const [showKnowledgeBase, setShowKnowledgeBase] = useState(false);
  const [batchProgress, setBatchProgress] = useState(0);
  const [isBatchRunning, setIsBatchRunning] = useState(false);
  const [activeTab, setActiveTab] = useState('comprehensive');
  const [batchResults, setBatchResults] = useState<{
    total: number;
    processed: number;
    highSuitability: number;
    mediumSuitability: number;
    lowSuitability: number;
    currentField: string;
  }>({
    total: 68,
    processed: 0,
    highSuitability: 0,
    mediumSuitability: 0,
    lowSuitability: 0,
    currentField: '',
  });
  const [batchAnalysisResults, setBatchAnalysisResults] = useState<SuitabilityResult[]>([]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/comprehensive')) {
        setActiveTab('comprehensive');
      } else if (activePath.includes('/batch')) {
        setActiveTab('batch');
      } else if (activePath.includes('/crop')) {
        setActiveTab('crop');
      }
    }
  }, [activePath]);

  // 评价因子权重配置
  const [factorWeights, setFactorWeights] = useState([
    { id: 'ph', name: 'pH值', weight: 20, unit: '' },
    { id: 'organic', name: '有机质含量', weight: 25, unit: 'g/kg' },
    { id: 'depth', name: '土层厚度', weight: 20, unit: 'cm' },
    { id: 'nitrogen', name: '全氮', weight: 10, unit: 'g/kg' },
    { id: 'phosphorus', name: '全磷', weight: 10, unit: 'g/kg' },
    { id: 'potassium', name: '全钾', weight: 10, unit: 'g/kg' },
    { id: 'drainage', name: '排水性', weight: 5, unit: '' },
  ]);

  // 模拟适宜性评价结果
  const evaluationResults: SuitabilityResult[] = [
    {
      fieldId: 'field-1',
      fieldName: '东区1号地',
      totalScore: 87,
      grade: '高度适宜',
      factors: [
        { id: 'ph', name: 'pH值', value: 6.5, weight: 20, unit: '', optimalRange: [6.0, 7.5], score: 95 },
        { id: 'organic', name: '有机质含量', value: 32, weight: 25, unit: 'g/kg', optimalRange: [25, 40], score: 90 },
        { id: 'depth', name: '土层厚度', value: 85, weight: 20, unit: 'cm', optimalRange: [60, 100], score: 88 },
        { id: 'nitrogen', name: '全氮', value: 1.8, weight: 10, unit: 'g/kg', optimalRange: [1.5, 2.5], score: 85 },
        { id: 'phosphorus', name: '全磷', value: 1.2, weight: 10, unit: 'g/kg', optimalRange: [1.0, 2.0], score: 80 },
        { id: 'potassium', name: '全钾', value: 18, weight: 10, unit: 'g/kg', optimalRange: [15, 25], score: 82 },
        { id: 'drainage', name: '排水性', value: 4, weight: 5, unit: '', optimalRange: [3, 5], score: 90 },
      ],
      timestamp: '2024-10-15 14:30',
    },
    {
      fieldId: 'field-2',
      fieldName: '西区2号地',
      totalScore: 72,
      grade: '一般适宜',
      factors: [
        { id: 'ph', name: 'pH值', value: 7.8, weight: 20, unit: '', optimalRange: [6.0, 7.5], score: 65 },
        { id: 'organic', name: '有机质含量', value: 22, weight: 25, unit: 'g/kg', optimalRange: [25, 40], score: 70 },
        { id: 'depth', name: '土层厚度', value: 55, weight: 20, unit: 'cm', optimalRange: [60, 100], score: 68 },
        { id: 'nitrogen', name: '全氮', value: 1.3, weight: 10, unit: 'g/kg', optimalRange: [1.5, 2.5], score: 72 },
        { id: 'phosphorus', name: '全磷', value: 0.9, weight: 10, unit: 'g/kg', optimalRange: [1.0, 2.0], score: 75 },
        { id: 'potassium', name: '全钾', value: 14, weight: 10, unit: 'g/kg', optimalRange: [15, 25], score: 78 },
        { id: 'drainage', name: '排水性', value: 3, weight: 5, unit: '', optimalRange: [3, 5], score: 85 },
      ],
      timestamp: '2024-10-15 14:28',
    },
    {
      fieldId: 'field-3',
      fieldName: '南区3号地',
      totalScore: 58,
      grade: '不适宜',
      factors: [
        { id: 'ph', name: 'pH值', value: 8.5, weight: 20, unit: '', optimalRange: [6.0, 7.5], score: 45 },
        { id: 'organic', name: '有机质含量', value: 15, weight: 25, unit: 'g/kg', optimalRange: [25, 40], score: 52 },
        { id: 'depth', name: '土层厚度', value: 42, weight: 20, unit: 'cm', optimalRange: [60, 100], score: 55 },
        { id: 'nitrogen', name: '全氮', value: 0.8, weight: 10, unit: 'g/kg', optimalRange: [1.5, 2.5], score: 60 },
        { id: 'phosphorus', name: '全磷', value: 0.6, weight: 10, unit: 'g/kg', optimalRange: [1.0, 2.0], score: 65 },
        { id: 'potassium', name: '全钾', value: 10, weight: 10, unit: 'g/kg', optimalRange: [15, 25], score: 58 },
        { id: 'drainage', name: '排水性', value: 2, weight: 5, unit: '', optimalRange: [3, 5], score: 70 },
      ],
      timestamp: '2024-10-15 14:25',
    },
  ];

  // 获取当前选中的地块结果（从评价结果或批量分析结果中）
  const currentResult = 
    evaluationResults.find(r => r.fieldId === selectedField) || 
    batchAnalysisResults.find(r => r.fieldId === selectedField) ||
    evaluationResults[0];

  const getGradeColor = (grade: string) => {
    switch (grade) {
      case '高度适宜': return 'bg-green-500';
      case '一般适宜': return 'bg-yellow-500';
      case '不适宜': return 'bg-red-500';
      default: return 'bg-gray-500';
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-green-600';
    if (score >= 60) return 'text-yellow-600';
    return 'text-red-600';
  };

  // 模拟从空间分析服务读取地块因子数据
  const fetchFieldFactorsFromSpatialService = (fieldId: string): EvaluationFactor[] => {
    // 模拟读取地块的土壤因子数据
    return [
      { 
        id: 'ph', 
        name: 'pH值', 
        value: 6.0 + Math.random() * 2, // 6.0-8.0
        weight: factorWeights.find(f => f.id === 'ph')?.weight || 20,
        unit: '', 
        optimalRange: [6.5, 7.5],
        score: 0 
      },
      { 
        id: 'organic', 
        name: '有机质含量', 
        value: 15 + Math.random() * 20, // 15-35 g/kg
        weight: factorWeights.find(f => f.id === 'organic')?.weight || 25,
        unit: 'g/kg', 
        optimalRange: [20, 30],
        score: 0 
      },
      { 
        id: 'depth', 
        name: '土层厚度', 
        value: 30 + Math.random() * 70, // 30-100 cm
        weight: factorWeights.find(f => f.id === 'depth')?.weight || 20,
        unit: 'cm', 
        optimalRange: [50, 80],
        score: 0 
      },
      { 
        id: 'nitrogen', 
        name: '全氮', 
        value: 0.8 + Math.random() * 1.5, // 0.8-2.3 g/kg
        weight: factorWeights.find(f => f.id === 'nitrogen')?.weight || 10,
        unit: 'g/kg', 
        optimalRange: [1.0, 2.0],
        score: 0 
      },
      { 
        id: 'phosphorus', 
        name: '全磷', 
        value: 0.4 + Math.random() * 1.2, // 0.4-1.6 g/kg
        weight: factorWeights.find(f => f.id === 'phosphorus')?.weight || 10,
        unit: 'g/kg', 
        optimalRange: [0.6, 1.2],
        score: 0 
      },
      { 
        id: 'potassium', 
        name: '全钾', 
        value: 12 + Math.random() * 13, // 12-25 g/kg
        weight: factorWeights.find(f => f.id === 'potassium')?.weight || 10,
        unit: 'g/kg', 
        optimalRange: [15, 20],
        score: 0 
      },
      { 
        id: 'drainage', 
        name: '排水性', 
        value: 60 + Math.random() * 40, // 60-100分
        weight: factorWeights.find(f => f.id === 'drainage')?.weight || 5,
        unit: '', 
        optimalRange: [70, 90],
        score: 0 
      },
    ];
  };

  // 批量分析处理函数
  const handleRunBatchAnalysis = async () => {
    if (totalWeight !== 100) {
      toast.error('权重总和必须为100%才能进行批量分析');
      return;
    }

    setIsBatchRunning(true);
    setBatchProgress(0);
    setBatchResults({
      total: 68,
      processed: 0,
      highSuitability: 0,
      mediumSuitability: 0,
      lowSuitability: 0,
      currentField: '',
    });
    setBatchAnalysisResults([]);

    toast.success('开始批量分析，正在读取地块数据...');

    // 模拟批量处理所有地块
    const totalFields = 68;
    const results: SuitabilityResult[] = [];
    
    for (let i = 0; i < totalFields; i++) {
      await new Promise(resolve => setTimeout(resolve, 100)); // 模拟处理延迟
      
      const fieldId = `field-${i + 1}`;
      const fieldName = `地块${String.fromCharCode(65 + (i % 26))}${Math.floor(i / 26) + 1}`;
      
      // 从空间分析服务读取因子数据
      const factors = fetchFieldFactorsFromSpatialService(fieldId);
      
      // 计算每个因子的得分
      const scoredFactors = factors.map(factor => ({
        ...factor,
        score: calculateFactorScore(factor.value, factor.optimalRange)
      }));
      
      // 计算综合得分（加权汇总）
      const totalScore = calculateTotalScore(scoredFactors);
      
      // 确定适宜性等级
      const grade = getGrade(totalScore);
      
      // 构建结果对象
      const result: SuitabilityResult = {
        fieldId,
        fieldName,
        totalScore,
        grade,
        factors: scoredFactors,
        timestamp: new Date().toISOString(),
      };
      
      results.push(result);
      
      // 更新统计数据
      setBatchResults(prev => ({
        ...prev,
        processed: i + 1,
        highSuitability: prev.highSuitability + (grade === '高度适宜' ? 1 : 0),
        mediumSuitability: prev.mediumSuitability + (grade === '一般适宜' ? 1 : 0),
        lowSuitability: prev.lowSuitability + (grade === '不适宜' ? 1 : 0),
        currentField: fieldName,
      }));
      
      // 更新进度
      setBatchProgress(Math.round(((i + 1) / totalFields) * 100));
    }
    
    // 保存所有结果
    setBatchAnalysisResults(results);
    setIsBatchRunning(false);
    
    toast.success(`批量分析完成！已为${totalFields}个地块生成适宜性评价结果并更新到数据库`);
  };

  const handleUpdateWeight = (id: string, newWeight: number) => {
    setFactorWeights(prev =>
      prev.map(f => f.id === id ? { ...f, weight: newWeight } : f)
    );
  };

  const handleResetWeights = () => {
    setFactorWeights([
      { id: 'ph', name: 'pH值', weight: 20, unit: '' },
      { id: 'organic', name: '有机质含量', weight: 25, unit: 'g/kg' },
      { id: 'depth', name: '土层厚度', weight: 20, unit: 'cm' },
      { id: 'nitrogen', name: '全氮', weight: 10, unit: 'g/kg' },
      { id: 'phosphorus', name: '全磷', weight: 10, unit: 'g/kg' },
      { id: 'potassium', name: '全钾', weight: 10, unit: 'g/kg' },
      { id: 'drainage', name: '排水性', weight: 5, unit: '' },
    ]);
    toast.success('权重已恢复默认值');
  };

  const totalWeight = factorWeights.reduce((sum, f) => sum + f.weight, 0);

  // 计算单个因子的得分（基于实际值与最佳范围的接近程度）
  const calculateFactorScore = (value: number, optimalRange: [number, number]): number => {
    const [min, max] = optimalRange;
    const mid = (min + max) / 2;
    const range = max - min;

    // 如果在最佳范围内，得分较高
    if (value >= min && value <= max) {
      // 越接近中值得分越高 (85-100分)
      const deviation = Math.abs(value - mid);
      const deviationRatio = deviation / (range / 2);
      return Math.max(85, 100 - deviationRatio * 15);
    }

    // 如果在范围外，根据偏离程度降低分数
    const deviation = value < min ? min - value : value - max;
    const deviationRatio = deviation / range;
    
    // 偏离越大，分数越低 (最低20分)
    return Math.max(20, 85 - deviationRatio * 65);
  };

  // 计算综合评分（层次分析法AHP加权求和）
  const calculateTotalScore = (factors: EvaluationFactor[]): number => {
    let totalScore = 0;
    for (const factor of factors) {
      totalScore += (factor.score * factor.weight) / 100;
    }
    return Math.round(totalScore);
  };

  // 根据总分确定适宜性等级
  const getGrade = (totalScore: number): '高度适宜' | '一般适宜' | '不适宜' => {
    if (totalScore >= 80) return '高度适宜';
    if (totalScore >= 60) return '一般适宜';
    return '不适宜';
  };

  // 执行地块适宜性评价
  const handleEvaluateField = () => {
    if (totalWeight !== 100) {
      toast.error('权重总和必须为100%才能进行评价');
      return;
    }

    toast.success('正在评价地块适宜性...');
    
    // 这里应该从土壤基础数据中获取实际数据
    // 目前使用模拟数据演示计算过程
    setTimeout(() => {
      toast.success('评价完成！已应用当前权重配置计算综合得分');
    }, 1000);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">地块适宜性评价</h2>
          <p className="text-muted-foreground">
            多因子综合评价、自动化空间分析与作物适配推荐
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => setShowKnowledgeBase(true)}>
            <BookOpen className="w-4 h-4 mr-2" />
            作物知识库
          </Button>
          <Button variant="outline" onClick={() => setShowWeightConfig(true)}>
            <Settings className="w-4 h-4 mr-2" />
            权重配置
          </Button>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="comprehensive">多因子综合评价</TabsTrigger>
          <TabsTrigger value="batch">自动化空间分析</TabsTrigger>
          <TabsTrigger value="crop">作物适配推荐</TabsTrigger>
        </TabsList>

        {/* 多因子综合评价 */}
        <TabsContent value="comprehensive" className="space-y-4">
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <div className="flex-1">
                <label className="text-xs text-muted-foreground mb-2 block">选择地块</label>
                <Select value={selectedField} onValueChange={setSelectedField}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {evaluationResults.map((result) => (
                      <SelectItem key={result.fieldId} value={result.fieldId}>
                        {result.fieldName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="flex gap-2 items-end">
                <Button 
                  className="bg-green-600 hover:bg-green-700"
                  onClick={handleEvaluateField}
                >
                  <Play className="w-4 h-4 mr-2" />
                  开始评价
                </Button>
              </div>
            </div>
          </Card>

          {/* 评价结果总览 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100">
              <div className="text-center">
                <Award className="w-12 h-12 text-green-600 mx-auto mb-3" />
                <p className="text-xs text-muted-foreground mb-2">综合评分</p>
                <p className="text-4xl text-green-600 mb-2">{currentResult.totalScore}</p>
                <Badge className={`${getGradeColor(currentResult.grade)} text-white`}>
                  {currentResult.grade}
                </Badge>
              </div>
            </Card>

            <Card className="p-6">
              <div className="text-center">
                <CheckCircle2 className="w-12 h-12 text-blue-600 mx-auto mb-3" />
                <p className="text-xs text-muted-foreground mb-2">优秀因子</p>
                <p className="text-4xl text-blue-600 mb-2">
                  {currentResult.factors.filter(f => f.score >= 80).length}
                </p>
                <p className="text-xs text-muted-foreground">
                  / {currentResult.factors.length} 项
                </p>
              </div>
            </Card>

            <Card className="p-6">
              <div className="text-center">
                <AlertTriangle className="w-12 h-12 text-yellow-600 mx-auto mb-3" />
                <p className="text-xs text-muted-foreground mb-2">待改善因子</p>
                <p className="text-4xl text-yellow-600 mb-2">
                  {currentResult.factors.filter(f => f.score < 70).length}
                </p>
                <p className="text-xs text-muted-foreground">需要优化</p>
              </div>
            </Card>

            <Card className="p-6">
              <div className="text-center">
                <TrendingUp className="w-12 h-12 text-purple-600 mx-auto mb-3" />
                <p className="text-xs text-muted-foreground mb-2">评价时间</p>
                <p className="text-sm text-purple-600 mb-2">{currentResult.timestamp}</p>
                <p className="text-xs text-muted-foreground">最近更新</p>
              </div>
            </Card>
          </div>

          {/* 因子��细评分 */}
          <Card className="p-6">
            <h3 className="mb-4">评价因子详细分析</h3>
            <div className="space-y-4">
              {currentResult.factors.map((factor) => (
                <div key={factor.id} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-medium">{factor.name}</span>
                      <Badge variant="outline" className="text-xs">
                        权重: {factor.weight}%
                      </Badge>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className="text-sm text-muted-foreground">
                        实际值: {factor.value}{factor.unit}
                      </span>
                      <span className="text-sm text-muted-foreground">
                        最佳范围: {factor.optimalRange[0]}-{factor.optimalRange[1]}{factor.unit}
                      </span>
                      <span className={`text-sm font-medium ${getScoreColor(factor.score)}`}>
                        {factor.score}分
                      </span>
                    </div>
                  </div>
                  <div className="relative">
                    <Progress value={factor.score} className="h-2" />
                    <div className="absolute top-0 left-0 h-2 w-full flex items-center">
                      <div
                        className="absolute h-3 w-1 bg-blue-500"
                        style={{
                          left: `${((factor.optimalRange[0] - 0) / (factor.optimalRange[1] * 1.5)) * 100}%`
                        }}
                      />
                      <div
                        className="absolute h-3 w-1 bg-blue-500"
                        style={{
                          left: `${((factor.optimalRange[1] - 0) / (factor.optimalRange[1] * 1.5)) * 100}%`
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* 加权计算说明 */}
          <Card className="p-6">
            <h3 className="mb-4">层次分析法(AHP)加权计算</h3>
            <div className="space-y-4">
              <div className="p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-blue-900 mb-2">计算公式：</p>
                <code className="text-xs text-blue-800 block mb-2">
                  总分 = Σ(因子得分 × 因子权重)
                </code>
                <p className="text-xs text-blue-800">
                  = ({currentResult.factors.map((f, i) => 
                    `${f.score} × ${f.weight}%${i < currentResult.factors.length - 1 ? ' + ' : ''}`
                  ).join('')})
                </p>
                <p className="text-xs text-blue-800 mt-2">
                  = {currentResult.totalScore}分
                </p>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div className="p-4 bg-green-50 rounded-lg">
                  <h4 className="text-green-900 mb-2">高度适宜 (&ge;80分)</h4>
                  <ul className="text-sm text-green-800 space-y-1">
                    <li>• 土壤条件优秀</li>
                    <li>• 适合多种作物</li>
                    <li>• 预期产量高</li>
                  </ul>
                </div>
                <div className="p-4 bg-yellow-50 rounded-lg">
                  <h4 className="text-yellow-900 mb-2">一般适宜 (60-79分)</h4>
                  <ul className="text-sm text-yellow-800 space-y-1">
                    <li>• 部分因子需改善</li>
                    <li>• 可种植耐性作物</li>
                    <li>• 需适当改良</li>
                  </ul>
                </div>
                <div className="p-4 bg-red-50 rounded-lg">
                  <h4 className="text-red-900 mb-2">不适宜 (&lt;60分)</h4>
                  <ul className="text-sm text-red-800 space-y-1">
                    <li>• 土壤条件较差</li>
                    <li>• 需大幅改良</li>
                    <li>• 风险较高</li>
                  </ul>
                </div>
              </div>
            </div>
          </Card>

          {/* 多因子综合评价功能说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Zap className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-800">
                <p className="mb-2">多因子综合评价功能说明：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>关键指标整合</strong>: 整合pH值、有机质含量、土层厚度、全氮、全磷、全钾、排水性等7项关键土壤指标</li>
                  <li>• <strong>层次分析法(AHP)</strong>: 采用层次分析法构建加权评分体系，公式：总分 = Σ(因子得分 × 因子权重)</li>
                  <li>• <strong>单因子评分</strong>: 根据实际值与最佳范围的接近程度计算各因子得分（0-100分），范围内得分85-100分</li>
                  <li>• <strong>自定义权重</strong>: 支持手动调整各指标权重，提供粮食作物和经济作物两种预设方案</li>
                  <li>• <strong>综合得分</strong>: 输出0-100分的适宜性评分，自动计算加权总分</li>
                  <li>• <strong>三级分级</strong>: 高度适宜（≥80分）、一般适宜（60-79分）、不适宜（&lt;60分）</li>
                  <li>• <strong>可视化展示</strong>: 提供进度条、颜色标识等多维度可视化，直观展示各因子评分与最佳范围对比</li>
                  <li>• <strong>改善建议</strong>: 自动识别待改善因子，为土壤改良提供决策依据</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 自动化空间分析 */}
        <TabsContent value="batch" className="space-y-4">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h3 className="mb-2">批量评价地块</h3>
                <p className="text-sm text-muted-foreground">
                  自动循环调用空间分析服务，读取各项因子数据，进行加权汇总计算，生成适宜性指数并更新到数据库
                </p>
              </div>
              <Button
                size="lg"
                className="bg-green-600 hover:bg-green-700"
                onClick={handleRunBatchAnalysis}
                disabled={isBatchRunning || totalWeight !== 100}
              >
                <Database className="w-5 h-5 mr-2" />
                {isBatchRunning ? '分析中...' : '开始批量分析'}
              </Button>
            </div>

            {totalWeight !== 100 && (
              <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p className="text-sm text-yellow-800">
                  ⚠️ 权重总和必须为100%才能进行批量分析（当前：{totalWeight}%）
                </p>
              </div>
            )}

            {isBatchRunning && (
              <div className="space-y-4">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">分析进度</span>
                  <span className="font-medium">{batchProgress}%</span>
                </div>
                <Progress value={batchProgress} className="h-3" />
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">��前处理</p>
                    <p className="mt-1 text-blue-900">{batchResults.currentField}</p>
                  </div>
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">处理进度</p>
                    <p className="mt-1 text-blue-900">{batchResults.processed} / {batchResults.total} 地块</p>
                  </div>
                </div>
                <div className="text-xs text-muted-foreground space-y-1">
                  <p>✓ 正在从空间分析服务读取因子数据...</p>
                  <p>✓ 正在计算各因子得分（pH、有机质、土层厚度、全氮、全磷、全钾、排水性）...</p>
                  <p>✓ 正在进行加权汇总计算...</p>
                  <p>✓ 正在生成适宜性指数并更新到数据库...</p>
                </div>
              </div>
            )}

            {!isBatchRunning && batchResults.processed > 0 && (
              <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                <p className="text-sm text-green-800">
                  ✓ 批量分析已完成！已为 {batchResults.processed} 个地块生成适宜性评价结果并更新到数据库
                </p>
              </div>
            )}
          </Card>

          {/* 批量分析结果统计 */}
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">高度适宜</p>
                  <p className="mt-2 text-3xl text-green-600">{batchResults.highSuitability}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    地块数量 ({batchResults.total > 0 ? Math.round((batchResults.highSuitability / batchResults.total) * 100) : 0}%)
                  </p>
                </div>
                <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6 bg-gradient-to-br from-yellow-50 to-yellow-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">一般适宜</p>
                  <p className="mt-2 text-3xl text-yellow-600">{batchResults.mediumSuitability}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    地块数量 ({batchResults.total > 0 ? Math.round((batchResults.mediumSuitability / batchResults.total) * 100) : 0}%)
                  </p>
                </div>
                <AlertTriangle className="w-12 h-12 text-yellow-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6 bg-gradient-to-br from-red-50 to-red-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">不适宜</p>
                  <p className="mt-2 text-3xl text-red-600">{batchResults.lowSuitability}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    地块数量 ({batchResults.total > 0 ? Math.round((batchResults.lowSuitability / batchResults.total) * 100) : 0}%)
                  </p>
                </div>
                <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 地块列表 */}
          {batchAnalysisResults.length > 0 && (
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>地块适宜性评价结果</h3>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm">
                    <Download className="w-4 h-4 mr-2" />
                    导出结果
                  </Button>
                </div>
              </div>
              <div className="overflow-x-auto max-h-[600px] overflow-y-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 sticky top-0">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs">地块名称</th>
                      <th className="px-4 py-3 text-center text-xs">综合评分</th>
                      <th className="px-4 py-3 text-center text-xs">适宜性等级</th>
                      <th className="px-4 py-3 text-center text-xs">pH值</th>
                      <th className="px-4 py-3 text-center text-xs">有机质(g/kg)</th>
                      <th className="px-4 py-3 text-center text-xs">土层厚度(cm)</th>
                      <th className="px-4 py-3 text-center text-xs">全氮(g/kg)</th>
                      <th className="px-4 py-3 text-center text-xs">更新时间</th>
                      <th className="px-4 py-3 text-center text-xs">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {batchAnalysisResults.map((result) => (
                      <tr key={result.fieldId} className="border-t hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm">{result.fieldName}</td>
                        <td className="px-4 py-3 text-center">
                          <span className={`text-sm font-medium ${getScoreColor(result.totalScore)}`}>
                            {result.totalScore}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <Badge className={`${getGradeColor(result.grade)} text-white`}>
                            {result.grade}
                          </Badge>
                        </td>
                        <td className="px-4 py-3 text-center text-sm">
                          {result.factors.find(f => f.id === 'ph')?.value.toFixed(1)}
                        </td>
                        <td className="px-4 py-3 text-center text-sm">
                          {result.factors.find(f => f.id === 'organic')?.value.toFixed(1)}
                        </td>
                        <td className="px-4 py-3 text-center text-sm">
                          {result.factors.find(f => f.id === 'depth')?.value.toFixed(0)}
                        </td>
                        <td className="px-4 py-3 text-center text-sm">
                          {result.factors.find(f => f.id === 'nitrogen')?.value.toFixed(2)}
                        </td>
                        <td className="px-4 py-3 text-center text-sm text-muted-foreground">
                          {new Date(result.timestamp).toLocaleString('zh-CN')}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={() => {
                              setSelectedField(result.fieldId);
                              setActiveTab('comprehensive');
                            }}
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                        </td>
                      </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          )}

          {/* 空间分析说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Database className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-800">
                <p className="mb-2">自动化空间分析流程说明：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>1. 数据读取</strong>: 从数据库中读取所有地块单元，获取每个地块的空间位置信息</li>
                  <li>• <strong>2. 循环调用空间分析服务</strong>: 自动遍历每个地块，调用空间分析服务读取7项因子数据（pH值、有机质含量、土层厚度、全氮、全磷、全钾、排水性）</li>
                  <li>• <strong>3. 因子评分</strong>: 根据实际值与最佳范围的接近程度，计算各因子得分（0-100分）</li>
                  <li>• <strong>4. 加权汇总计算</strong>: 使用配置的权重体系（总和=100%），计算综合得分 = Σ(因子得分 × 因子权重)</li>
                  <li>• <strong>5. 适宜性分级</strong>: 根据综合得分自动分级：高度适宜(≥80分)、一般适宜(60-79分)、不适宜(&lt;60分)</li>
                  <li>• <strong>6. 批量更新数据库</strong>: 将每个地块的适宜性指数和评价结果批量写回数据库，完成更新</li>
                  <li>• <strong>7. 结果统计与可视化</strong>: 自动生成统计报告，支持按适宜性等级分类查看和导出</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 作物适配推荐 */}
        <TabsContent value="crop" className="space-y-4">
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <div className="flex-1">
                <label className="text-xs text-muted-foreground mb-2 block">选择地块</label>
                <Select value={selectedField} onValueChange={setSelectedField}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {evaluationResults.map((result) => (
                      <SelectItem key={result.fieldId} value={result.fieldId}>
                        {result.fieldName} - {result.grade} ({result.totalScore}分)
                      </SelectItem>
                    ))}
                    {batchAnalysisResults.map((result) => (
                      <SelectItem key={result.fieldId} value={result.fieldId}>
                        {result.fieldName} - {result.grade} ({result.totalScore}分)
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </Card>

          {/* 地块环境参数概览 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Database className="w-5 h-5 text-green-600" />
              {currentResult.fieldName} - 环境参数概览
            </h3>
            <div className="grid grid-cols-4 gap-4 mb-4">
              <div className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg">
                <p className="text-xs text-blue-600 mb-1 flex items-center gap-1">
                  <ThermometerSun className="w-3 h-3" />
                  pH值
                </p>
                <p className="text-xl font-medium text-blue-900">
                  {currentResult.factors.find(f => f.id === 'ph')?.value.toFixed(1)}
                </p>
              </div>
              <div className="p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-lg">
                <p className="text-xs text-green-600 mb-1 flex items-center gap-1">
                  <Leaf className="w-3 h-3" />
                  有机质
                </p>
                <p className="text-xl font-medium text-green-900">
                  {currentResult.factors.find(f => f.id === 'organic')?.value.toFixed(1)} g/kg
                </p>
              </div>
              <div className="p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-lg">
                <p className="text-xs text-amber-600 mb-1">土层厚度</p>
                <p className="text-xl font-medium text-amber-900">
                  {currentResult.factors.find(f => f.id === 'depth')?.value.toFixed(0)} cm
                </p>
              </div>
              <div className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg">
                <p className="text-xs text-purple-600 mb-1 flex items-center gap-1">
                  <Droplet className="w-3 h-3" />
                  排水性
                </p>
                <p className="text-xl font-medium text-purple-900">
                  {currentResult.factors.find(f => f.id === 'drainage')?.value.toFixed(0)}分
                </p>
              </div>
            </div>
            
            <div className="grid grid-cols-3 gap-4">
              <div className="p-3 bg-gray-50 rounded-lg">
                <p className="text-xs text-muted-foreground mb-1">全氮</p>
                <p className="font-medium">{currentResult.factors.find(f => f.id === 'nitrogen')?.value.toFixed(2)} g/kg</p>
              </div>
              <div className="p-3 bg-gray-50 rounded-lg">
                <p className="text-xs text-muted-foreground mb-1">全磷</p>
                <p className="font-medium">{currentResult.factors.find(f => f.id === 'phosphorus')?.value.toFixed(2)} g/kg</p>
              </div>
              <div className="p-3 bg-gray-50 rounded-lg">
                <p className="text-xs text-muted-foreground mb-1">全钾</p>
                <p className="font-medium">{currentResult.factors.find(f => f.id === 'potassium')?.value.toFixed(1)} g/kg</p>
              </div>
            </div>
          </Card>

          {/* 推荐作物清单 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Leaf className="w-5 h-5 text-green-600" />
                智能作物推荐清单
              </h3>
              <Badge variant="outline" className="text-xs">
                基于{cropKnowledgeBase.length}种作物知识库匹配
              </Badge>
            </div>
            
            <div className="space-y-4">
              {(() => {
                // 获取地块因子数据
                const fieldFactors = {
                  ph: currentResult.factors.find(f => f.id === 'ph')?.value || 0,
                  organic: currentResult.factors.find(f => f.id === 'organic')?.value || 0,
                  depth: currentResult.factors.find(f => f.id === 'depth')?.value || 0,
                  nitrogen: currentResult.factors.find(f => f.id === 'nitrogen')?.value || 0,
                  phosphorus: currentResult.factors.find(f => f.id === 'phosphorus')?.value || 0,
                  potassium: currentResult.factors.find(f => f.id === 'potassium')?.value || 0,
                  drainage: currentResult.factors.find(f => f.id === 'drainage')?.value || 0,
                  temperature: 22, // 模拟年均温度
                  rainfall: 800,   // 模拟年均降雨量
                };
                
                // 匹配推荐作物
                const recommendations = matchCropsForField(fieldFactors);
                
                return recommendations.map((recommendation, index) => {
                  const { crop, matchScore, suitabilityLevel, matchDetails, applicableRisks, expectedYield } = recommendation;
                  
                  // 根据适宜性等级设置颜色
                  const levelColor = 
                    suitabilityLevel === '高度推荐' ? { bg: 'bg-green-500', border: '#22c55e', text: 'text-green-600' } :
                    suitabilityLevel === '推荐' ? { bg: 'bg-blue-500', border: '#3b82f6', text: 'text-blue-600' } :
                    suitabilityLevel === '谨慎种植' ? { bg: 'bg-yellow-500', border: '#eab308', text: 'text-yellow-600' } :
                    { bg: 'bg-gray-500', border: '#6b7280', text: 'text-gray-600' };
                  
                  // 只显示高度推荐和推荐的作物
                  if (suitabilityLevel === '不推荐') return null;
                  
                  return (
                    <Card key={index} className="p-5 border-l-4 hover:shadow-lg transition-shadow" style={{ borderLeftColor: levelColor.border }}>
                      {/* 标题栏 */}
                      <div className="flex items-start justify-between mb-4">
                        <div className="flex items-center gap-3">
                          <div className={`p-2 rounded-lg bg-gradient-to-br from-green-50 to-green-100`}>
                            <Leaf className="w-6 h-6 text-green-600" />
                          </div>
                          <div>
                            <div className="flex items-center gap-2">
                              <h4 className="mb-1">{crop.cropName}</h4>
                              <Badge variant="outline" className="text-xs">{crop.category}</Badge>
                            </div>
                            <div className="flex items-center gap-2">
                              <Badge className={`${levelColor.bg} text-white`}>
                                {suitabilityLevel}
                              </Badge>
                              <span className="text-xs text-muted-foreground">匹配度: {matchScore}分</span>
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-xs text-muted-foreground mb-1">预期产量区间</p>
                          <p className={`text-lg font-medium ${levelColor.text}`}>
                            {expectedYield[0]}-{expectedYield[1]} kg/亩
                          </p>
                          <p className="text-xs text-muted-foreground mt-1">生长周期: {crop.growthCycle.days}天</p>
                        </div>
                      </div>
                      
                      {/* 作物描述 */}
                      <p className="text-sm text-muted-foreground mb-3 p-2 bg-gray-50 rounded">
                        {crop.description}
                      </p>
                      
                      {/* 土壤因子匹配详情 */}
                      <div className="mb-3">
                        <p className="text-xs text-muted-foreground mb-2">土壤因子匹配情况：</p>
                        <div className="grid grid-cols-7 gap-2">
                          {matchDetails.map((detail, i) => (
                            <div key={i} className="p-2 bg-gray-50 rounded text-center">
                              <p className="text-xs text-muted-foreground mb-1">{detail.factor}</p>
                              <p className="text-xs font-medium mb-1">{detail.value.toFixed(1)}</p>
                              {detail.status === 'optimal' ? (
                                <Badge className="bg-green-500 text-white" style={{ fontSize: '9px', padding: '1px 4px' }}>
                                  最佳
                                </Badge>
                              ) : detail.status === 'acceptable' ? (
                                <Badge className="bg-blue-500 text-white" style={{ fontSize: '9px', padding: '1px 4px' }}>
                                  可接受
                                </Badge>
                              ) : (
                                <Badge variant="outline" className="text-red-500" style={{ fontSize: '9px', padding: '1px 4px' }}>
                                  偏离
                                </Badge>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                      
                      {/* 气候要求 */}
                      <div className="grid grid-cols-3 gap-3 mb-3">
                        <div className="p-2 bg-blue-50 rounded-lg">
                          <p className="text-xs text-blue-600 mb-1 flex items-center gap-1">
                            <ThermometerSun className="w-3 h-3" />
                            温度要求
                          </p>
                          <p className="text-sm text-blue-900">
                            {crop.climateRequirements.temperature.optimal[0]}-{crop.climateRequirements.temperature.optimal[1]}°C
                          </p>
                        </div>
                        <div className="p-2 bg-cyan-50 rounded-lg">
                          <p className="text-xs text-cyan-600 mb-1 flex items-center gap-1">
                            <Cloud className="w-3 h-3" />
                            降雨要求
                          </p>
                          <p className="text-sm text-cyan-900">
                            {crop.climateRequirements.rainfall.optimal[0]}-{crop.climateRequirements.rainfall.optimal[1]}mm/年
                          </p>
                        </div>
                        <div className="p-2 bg-amber-50 rounded-lg">
                          <p className="text-xs text-amber-600 mb-1 flex items-center gap-1">
                            <Sun className="w-3 h-3" />
                            光照要求
                          </p>
                          <p className="text-sm text-amber-900">
                            {crop.climateRequirements.sunlight.optimal[0]}-{crop.climateRequirements.sunlight.optimal[1]}小时/天
                          </p>
                        </div>
                      </div>
                      
                      {/* 风险提示 */}
                      {applicableRisks.length > 0 && (
                        <div className={`p-3 rounded-lg border ${
                          applicableRisks.some(r => r.severity === 'high') 
                            ? 'bg-red-50 border-red-200' 
                            : 'bg-orange-50 border-orange-200'
                        }`}>
                          <p className="text-xs font-medium mb-2 flex items-center gap-1">
                            <AlertTriangle className={`w-4 h-4 ${
                              applicableRisks.some(r => r.severity === 'high') 
                                ? 'text-red-600' 
                                : 'text-orange-600'
                            }`} />
                            <span className={applicableRisks.some(r => r.severity === 'high') ? 'text-red-900' : 'text-orange-900'}>
                              风险提示与应对建议
                            </span>
                          </p>
                          <div className="space-y-2">
                            {applicableRisks.map((risk, i) => (
                              <div key={i} className="text-xs">
                                <div className="flex items-start gap-2">
                                  <Badge 
                                    className={
                                      risk.severity === 'high' ? 'bg-red-500 text-white' :
                                      risk.severity === 'medium' ? 'bg-orange-500 text-white' :
                                      'bg-yellow-500 text-white'
                                    }
                                    style={{ fontSize: '9px', padding: '2px 6px', marginTop: '2px' }}
                                  >
                                    {risk.severity === 'high' ? '高风险' : risk.severity === 'medium' ? '中风险' : '低风险'}
                                  </Badge>
                                  <div className="flex-1">
                                    <p className={`font-medium mb-0.5 ${
                                      applicableRisks.some(r => r.severity === 'high') 
                                        ? 'text-red-800' 
                                        : 'text-orange-800'
                                    }`}>
                                      {risk.name}
                                    </p>
                                    <p className="text-muted-foreground mb-1">触发条件: {risk.condition}</p>
                                    <p className={applicableRisks.some(r => r.severity === 'high') ? 'text-red-700' : 'text-orange-700'}>
                                      💡 {risk.suggestion}
                                    </p>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      {/* 适宜季节 */}
                      <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
                        <span>适宜种植季节:</span>
                        {crop.growthCycle.seasons.map((season, i) => (
                          <Badge key={i} variant="outline" className="text-xs">
                            {season}
                          </Badge>
                        ))}
                      </div>
                    </Card>
                  );
                });
              })()}
            </div>
          </Card>

          {/* 作物知识库说明 */}
          <Card className="p-5 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
            <div className="flex items-start gap-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <Target className="w-6 h-6 text-green-700 flex-shrink-0" />
              </div>
              <div className="flex-1">
                <h4 className="text-green-900 mb-3">作物-环境知识库匹配系统</h4>
                <div className="grid grid-cols-2 gap-4 text-sm text-green-800">
                  <div>
                    <p className="font-medium mb-2">🌾 知识库构成</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>作物种类</strong>: {cropKnowledgeBase.length}种主要农作物（粮食、经济、蔬菜、果树）</li>
                      <li>• <strong>土壤参数</strong>: pH、有机质、土层厚度、氮磷钾、排水性共7项指标</li>
                      <li>• <strong>气候参数</strong>: 温度、降雨量、光照时长等环境因子</li>
                      <li>• <strong>最佳范围</strong>: 每个因子包含最佳范围和可接受范围</li>
                    </ul>
                  </div>
                  <div>
                    <p className="font-medium mb-2">🎯 智能匹配流程</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>参数对比</strong>: 地块实际值与作物要求范围逐一对比</li>
                      <li>• <strong>评分计算</strong>: 最佳范围100分，可接受范围60分，偏离0分</li>
                      <li>• <strong>综合匹配度</strong>: 加权平均所有因子得分（0-100分）</li>
                      <li>• <strong>分级推荐</strong>: ≥85分高度推荐，70-84推荐，50-69谨慎种植</li>
                    </ul>
                  </div>
                  <div>
                    <p className="font-medium mb-2">📊 产量预测机制</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>三级产量区间</strong>: 高/中/低适宜性对应不同产量预期</li>
                      <li>• <strong>历史数据支撑</strong>: 基于大量实测数据建立的产量模型</li>
                      <li>• <strong>动态调整</strong>: 根据匹配度智能选择产量区间</li>
                      <li>• <strong>品种差异</strong>: 考虑不同作物的产量特性</li>
                    </ul>
                  </div>
                  <div>
                    <p className="font-medium mb-2">⚠️ 风险识别系统</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>多维度监测</strong>: 土壤、气候、营养等多方面风险识别</li>
                      <li>• <strong>条件触发</strong>: 根据实际值自动判断风险是否存在</li>
                      <li>• <strong>严重度分级</strong>: 高/中/低三级风险等级标注</li>
                      <li>• <strong>应对建议</strong>: 每个风险配套具体的应对措施</li>
                    </ul>
                  </div>
                </div>
                
                <div className="mt-4 p-3 bg-white/60 rounded-lg border border-green-200">
                  <p className="text-xs text-green-900">
                    <strong>💡 系统优势：</strong>
                    本系统整合了土壤科学、作物学、气象学等多学科知识，建立了完整的作物-环境适配知识库。
                    通过科学的评分体系和智能匹配算法，为农业生产决策提供可靠的数据支持，帮助优化作物布局，
                    提高土地利用率和经济效益，同时有效规避种植风险。
                  </p>
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

      </Tabs>

      {/* 权重配置对话框 */}
      <Dialog open={showWeightConfig} onOpenChange={setShowWeightConfig}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>评价因子权重配置</DialogTitle>
            <DialogDescription>
              调整各因子权重以适应不同作物类型的评价需求，权重总和必须为100%
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6">
            {/* 快速方案选择 */}
            <div>
              <h4 className="mb-3">快速方案</h4>
              <div className="grid grid-cols-2 gap-3">
                <Button
                  variant="outline"
                  className="h-20 flex flex-col items-center justify-center"
                  onClick={() => {
                    setFactorWeights([
                      { id: 'ph', name: 'pH值', weight: 20, unit: '' },
                      { id: 'organic', name: '有机质含量', weight: 30, unit: 'g/kg' },
                      { id: 'depth', name: '土层厚度', weight: 25, unit: 'cm' },
                      { id: 'nitrogen', name: '全氮', weight: 8, unit: 'g/kg' },
                      { id: 'phosphorus', name: '全磷', weight: 8, unit: 'g/kg' },
                      { id: 'potassium', name: '全钾', weight: 8, unit: 'g/kg' },
                      { id: 'drainage', name: '排水性', weight: 1, unit: '' },
                    ]);
                    toast.success('已应用粮食作物权重方案');
                  }}
                >
                  <Leaf className="w-6 h-6 text-green-600 mb-2" />
                  <span className="font-medium">粮食作物方案</span>
                  <span className="text-xs text-muted-foreground mt-1">
                    侧重有机质和土层厚度
                  </span>
                </Button>

                <Button
                  variant="outline"
                  className="h-20 flex flex-col items-center justify-center"
                  onClick={() => {
                    setFactorWeights([
                      { id: 'ph', name: 'pH值', weight: 25, unit: '' },
                      { id: 'organic', name: '有机质含量', weight: 35, unit: 'g/kg' },
                      { id: 'depth', name: '土层厚度', weight: 15, unit: 'cm' },
                      { id: 'nitrogen', name: '全氮', weight: 7, unit: 'g/kg' },
                      { id: 'phosphorus', name: '全磷', weight: 7, unit: 'g/kg' },
                      { id: 'potassium', name: '全钾', weight: 7, unit: 'g/kg' },
                      { id: 'drainage', name: '排水性', weight: 4, unit: '' },
                    ]);
                    toast.success('已应用经济作物权重方案');
                  }}
                >
                  <TrendingUp className="w-6 h-6 text-blue-600 mb-2" />
                  <span className="font-medium">经济作物方案</span>
                  <span className="text-xs text-muted-foreground mt-1">
                    侧重有机质和pH值
                  </span>
                </Button>
              </div>
            </div>

            {/* 手动调整权重 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h4>自定义权重</h4>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">
                    当前总和：
                  </span>
                  <Badge 
                    className={
                      totalWeight === 100 
                        ? 'bg-green-500 text-white' 
                        : 'bg-red-500 text-white'
                    }
                  >
                    {totalWeight}%
                  </Badge>
                </div>
              </div>

              <div className="space-y-4">
                {factorWeights.map((factor) => (
                  <div key={factor.id} className="space-y-2">
                    <div className="flex items-center justify-between">
                      <label className="text-sm font-medium">
                        {factor.name}
                      </label>
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          min="0"
                          max="100"
                          value={factor.weight}
                          onChange={(e) => {
                            const newWeight = Math.max(0, Math.min(100, parseInt(e.target.value) || 0));
                            handleUpdateWeight(factor.id, newWeight);
                          }}
                          className="w-20 text-right"
                        />
                        <span className="text-sm text-muted-foreground w-8">%</span>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Slider
                        value={[factor.weight]}
                        onValueChange={(value) => handleUpdateWeight(factor.id, value[0])}
                        max={100}
                        step={1}
                        className="flex-1"
                      />
                    </div>
                  </div>
                ))}
              </div>

              {totalWeight !== 100 && (
                <div className="p-3 bg-orange-50 border border-orange-200 rounded-lg mt-4">
                  <p className="text-sm text-orange-900 flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4" />
                    权重总和必须等于100%才能应用配置
                  </p>
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="flex items-center justify-between pt-4 border-t">
              <Button
                variant="outline"
                onClick={handleResetWeights}
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                恢复默认
              </Button>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={() => setShowWeightConfig(false)}
                >
                  取消
                </Button>
                <Button
                  className="bg-green-600 hover:bg-green-700"
                  onClick={() => {
                    if (totalWeight !== 100) {
                      toast.error('权重总和必须为100%');
                      return;
                    }
                    setShowWeightConfig(false);
                    toast.success('权重配置已保存');
                  }}
                  disabled={totalWeight !== 100}
                >
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  应用配置
                </Button>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 作物知识库对话框 */}
      <Dialog open={showKnowledgeBase} onOpenChange={setShowKnowledgeBase}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-green-600" />
              作物-环境知识库
            </DialogTitle>
            <DialogDescription>
              查看各种作物的土壤环境要求、气候要求、预期产量及风险因子
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 知识库统计 */}
            <div className="grid grid-cols-4 gap-4">
              <Card className="p-4 bg-green-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-green-700 mb-1">作物总数</p>
                    <p className="text-2xl font-semibold text-green-900">{cropKnowledgeBase.length}</p>
                  </div>
                  <Database className="w-8 h-8 text-green-600 opacity-50" />
                </div>
              </Card>
              <Card className="p-4 bg-blue-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-blue-700 mb-1">粮食作物</p>
                    <p className="text-2xl font-semibold text-blue-900">
                      {cropKnowledgeBase.filter(c => c.category === '粮食作物').length}
                    </p>
                  </div>
                  <Leaf className="w-8 h-8 text-blue-600 opacity-50" />
                </div>
              </Card>
              <Card className="p-4 bg-amber-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-amber-700 mb-1">经济作物</p>
                    <p className="text-2xl font-semibold text-amber-900">
                      {cropKnowledgeBase.filter(c => c.category === '经济作物').length}
                    </p>
                  </div>
                  <Target className="w-8 h-8 text-amber-600 opacity-50" />
                </div>
              </Card>
              <Card className="p-4 bg-purple-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-purple-700 mb-1">蔬菜作物</p>
                    <p className="text-2xl font-semibold text-purple-900">
                      {cropKnowledgeBase.filter(c => c.category === '蔬菜作物').length}
                    </p>
                  </div>
                  <Droplet className="w-8 h-8 text-purple-600 opacity-50" />
                </div>
              </Card>
            </div>

            {/* 作物列表 */}
            <div className="space-y-4">
              {cropKnowledgeBase.map((crop) => (
                <Card key={crop.id} className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-green-800">{crop.cropName}</h3>
                        <Badge variant={
                          crop.category === '粮食作物' ? 'default' :
                          crop.category === '经济作物' ? 'secondary' :
                          'outline'
                        }>
                          {crop.category}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">{crop.description}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-muted-foreground mb-1">生长周期</p>
                      <p className="text-lg font-semibold text-green-700">{crop.growthCycle.days}天</p>
                      <p className="text-xs text-muted-foreground mt-1">
                        {crop.growthCycle.seasons.join('、')}
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    {/* 土壤环境要求 */}
                    <div>
                      <h4 className="mb-3 flex items-center gap-2">
                        <Database className="w-4 h-4 text-green-600" />
                        土壤环境要求
                      </h4>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">pH值:</span>
                          <span className="font-medium">
                            最佳 {crop.soilRequirements.ph.optimal[0]}-{crop.soilRequirements.ph.optimal[1]} 
                            <span className="text-muted-foreground text-xs ml-2">
                              (可接受 {crop.soilRequirements.ph.acceptable[0]}-{crop.soilRequirements.ph.acceptable[1]})
                            </span>
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">有机质:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.organicMatter.optimal[0]}-{crop.soilRequirements.organicMatter.optimal[1]} g/kg
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">土层厚度:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.soilDepth.optimal[0]}-{crop.soilRequirements.soilDepth.optimal[1]} cm
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">全氮:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.nitrogen.optimal[0]}-{crop.soilRequirements.nitrogen.optimal[1]} g/kg
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">全磷:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.phosphorus.optimal[0]}-{crop.soilRequirements.phosphorus.optimal[1]} g/kg
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground">全钾:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.potassium.optimal[0]}-{crop.soilRequirements.potassium.optimal[1]} g/kg
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5">
                          <span className="text-muted-foreground">排水性评分:</span>
                          <span className="font-medium">
                            {crop.soilRequirements.drainage.optimal[0]}-{crop.soilRequirements.drainage.optimal[1]} 分
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* 气候要求与产量 */}
                    <div>
                      <h4 className="mb-3 flex items-center gap-2">
                        <Cloud className="w-4 h-4 text-blue-600" />
                        气候要求
                      </h4>
                      <div className="space-y-2 text-sm mb-4">
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground flex items-center gap-1">
                            <ThermometerSun className="w-3 h-3" />
                            温度:
                          </span>
                          <span className="font-medium">
                            {crop.climateRequirements.temperature.optimal[0]}-{crop.climateRequirements.temperature.optimal[1]} °C
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b">
                          <span className="text-muted-foreground flex items-center gap-1">
                            <Droplet className="w-3 h-3" />
                            降雨量:
                          </span>
                          <span className="font-medium">
                            {crop.climateRequirements.rainfall.optimal[0]}-{crop.climateRequirements.rainfall.optimal[1]} mm/年
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5">
                          <span className="text-muted-foreground flex items-center gap-1">
                            <Sun className="w-3 h-3" />
                            光照:
                          </span>
                          <span className="font-medium">
                            {crop.climateRequirements.sunlight.optimal[0]}-{crop.climateRequirements.sunlight.optimal[1]} 小时/天
                          </span>
                        </div>
                      </div>

                      <h4 className="mb-3 flex items-center gap-2 mt-4">
                        <TrendingUp className="w-4 h-4 text-amber-600" />
                        预期产量 (kg/亩)
                      </h4>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between py-1.5 border-b bg-green-50 px-2 rounded">
                          <span className="text-green-700">高适宜性:</span>
                          <span className="font-semibold text-green-800">
                            {crop.expectedYield.high[0]}-{crop.expectedYield.high[1]}
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b bg-blue-50 px-2 rounded">
                          <span className="text-blue-700">中等适宜性:</span>
                          <span className="font-semibold text-blue-800">
                            {crop.expectedYield.medium[0]}-{crop.expectedYield.medium[1]}
                          </span>
                        </div>
                        <div className="flex justify-between py-1.5 bg-gray-50 px-2 rounded">
                          <span className="text-gray-700">低适宜性:</span>
                          <span className="font-semibold text-gray-800">
                            {crop.expectedYield.low[0]}-{crop.expectedYield.low[1]}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* 风险因子 */}
                  {crop.riskFactors.length > 0 && (
                    <div className="mt-4 pt-4 border-t">
                      <h4 className="mb-3 flex items-center gap-2">
                        <AlertTriangle className="w-4 h-4 text-amber-600" />
                        主要风险因子
                      </h4>
                      <div className="grid grid-cols-2 gap-3">
                        {crop.riskFactors.map((risk) => (
                          <div 
                            key={risk.id}
                            className={`p-3 rounded-lg border ${
                              risk.severity === 'high' ? 'bg-red-50 border-red-200' :
                              risk.severity === 'medium' ? 'bg-amber-50 border-amber-200' :
                              'bg-blue-50 border-blue-200'
                            }`}
                          >
                            <div className="flex items-start justify-between mb-2">
                              <p className={`text-sm font-medium ${
                                risk.severity === 'high' ? 'text-red-900' :
                                risk.severity === 'medium' ? 'text-amber-900' :
                                'text-blue-900'
                              }`}>
                                {risk.name}
                              </p>
                              <Badge 
                                variant={risk.severity === 'high' ? 'destructive' : 'outline'}
                                className="text-xs"
                              >
                                {risk.severity === 'high' ? '高风险' : risk.severity === 'medium' ? '中风险' : '低风险'}
                              </Badge>
                            </div>
                            <p className="text-xs text-muted-foreground mb-2">
                              触发条件: {risk.condition}
                            </p>
                            <p className="text-xs text-foreground">
                              应对建议: {risk.suggestion}
                            </p>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </Card>
              ))}
            </div>
          </div>

          <div className="flex justify-end pt-4 border-t mt-4">
            <Button onClick={() => setShowKnowledgeBase(false)}>
              关闭
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
