import { useState, useMemo } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
import { Calendar } from '../../ui/calendar';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { TrendingUp, DollarSign, Target, Clock, AlertTriangle, Lightbulb, Filter, TrendingDown, Calendar as CalendarIcon } from 'lucide-react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

// 作业数据类型
interface OperationData {
  id: string;
  machineryId: string;
  machineryName: string;
  machineryModel: string;
  driverId: string;
  driverName: string;
  fieldId: string;
  fieldName: string;
  soilType: string;
  operationType: string;
  date: string;
  area: number;
  duration: number;
  fuelConsumption: number;
  cost: number;
  quality: number;
  seedingUniformity?: number;
  depthConsistency?: number;
}

export function OperationAnalysis() {
  const [timeRange, setTimeRange] = useState('last6months');
  const [selectedField, setSelectedField] = useState('all');
  const [selectedMachinery, setSelectedMachinery] = useState('all');
  const [selectedDriver, setSelectedDriver] = useState('all');
  const [activeTab, setActiveTab] = useState('overview');
  
  // 自定义时间范围
  const [customStartDate, setCustomStartDate] = useState<Date>();
  const [customEndDate, setCustomEndDate] = useState<Date>();
  const [showCustomDateRange, setShowCustomDateRange] = useState(false);

  // 处理时间范围变化
  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value);
    if (value === 'custom') {
      setShowCustomDateRange(true);
    } else {
      setShowCustomDateRange(false);
      setCustomStartDate(undefined);
      setCustomEndDate(undefined);
    }
  };

  // 模拟作业数据
  const mockOperationData: OperationData[] = useMemo(() => [
    {
      id: 'op-1',
      machineryId: 'm1',
      machineryName: '约翰迪尔8R',
      machineryModel: 'John Deere 8R',
      driverId: 'd1',
      driverName: '张三',
      fieldId: 'f1',
      fieldName: '1号地块',
      soilType: '黏土',
      operationType: '耕地',
      date: '2024-10',
      area: 85,
      duration: 10,
      fuelConsumption: 120,
      cost: 3825,
      quality: 92,
      depthConsistency: 88,
    },
    {
      id: 'op-2',
      machineryId: 'm1',
      machineryName: '约翰迪尔8R',
      machineryModel: 'John Deere 8R',
      driverId: 'd2',
      driverName: '李四',
      fieldId: 'f2',
      fieldName: '2号地块',
      soilType: '沙土',
      operationType: '耕地',
      date: '2024-09',
      area: 78,
      duration: 9.5,
      fuelConsumption: 95,
      cost: 3510,
      quality: 95,
      depthConsistency: 92,
    },
    {
      id: 'op-3',
      machineryId: 'm2',
      machineryName: '久保田M7',
      machineryModel: 'Kubota M7',
      driverId: 'd1',
      driverName: '张三',
      fieldId: 'f3',
      fieldName: '3号地块',
      soilType: '黏土',
      operationType: '播种',
      date: '2024-10',
      area: 62,
      duration: 8.5,
      fuelConsumption: 98,
      cost: 3224,
      quality: 88,
      seedingUniformity: 85,
      depthConsistency: 90,
    },
    {
      id: 'op-4',
      machineryId: 'm2',
      machineryName: '久保田M7',
      machineryModel: 'Kubota M7',
      driverId: 'd3',
      driverName: '王五',
      fieldId: 'f1',
      fieldName: '1号地块',
      soilType: '黏土',
      operationType: '播种',
      date: '2024-08',
      area: 70,
      duration: 10,
      fuelConsumption: 115,
      cost: 3780,
      quality: 85,
      seedingUniformity: 82,
      depthConsistency: 87,
    },
    {
      id: 'op-5',
      machineryId: 'm3',
      machineryName: '雷沃欧豹',
      machineryModel: 'LOVOL M2104',
      driverId: 'd2',
      driverName: '李四',
      fieldId: 'f2',
      fieldName: '2号地块',
      soilType: '沙土',
      operationType: '收获',
      date: '2024-10',
      area: 95,
      duration: 12,
      fuelConsumption: 135,
      cost: 4275,
      quality: 90,
    },
    {
      id: 'op-6',
      machineryId: 'm3',
      machineryName: '雷沃欧豹',
      machineryModel: 'LOVOL M2104',
      driverId: 'd1',
      driverName: '张三',
      fieldId: 'f4',
      fieldName: '4号地块',
      soilType: '壤土',
      operationType: '收获',
      date: '2024-09',
      area: 88,
      duration: 11,
      fuelConsumption: 125,
      cost: 3960,
      quality: 93,
    },
    {
      id: 'op-7',
      machineryId: 'm4',
      machineryName: '东方红LX',
      machineryModel: 'Dongfanghong LX2204',
      driverId: 'd3',
      driverName: '王五',
      fieldId: 'f3',
      fieldName: '3号地块',
      soilType: '黏土',
      operationType: '耕地',
      date: '2024-07',
      area: 72,
      duration: 9.6,
      fuelConsumption: 108,
      cost: 3456,
      quality: 87,
      depthConsistency: 85,
    },
    {
      id: 'op-8',
      machineryId: 'm1',
      machineryName: '约翰迪尔8R',
      machineryModel: 'John Deere 8R',
      driverId: 'd1',
      driverName: '张三',
      fieldId: 'f5',
      fieldName: '5号地块',
      soilType: '壤土',
      operationType: '播种',
      date: '2024-06',
      area: 80,
      duration: 10.5,
      fuelConsumption: 102,
      cost: 3600,
      quality: 94,
      seedingUniformity: 91,
      depthConsistency: 93,
    },
  ], []);

  // 筛选数据
  const filteredData = useMemo(() => {
    return mockOperationData.filter(item => {
      if (selectedField !== 'all' && item.fieldId !== selectedField) return false;
      if (selectedMachinery !== 'all' && item.machineryId !== selectedMachinery) return false;
      if (selectedDriver !== 'all' && item.driverId !== selectedDriver) return false;
      return true;
    });
  }, [mockOperationData, selectedField, selectedMachinery, selectedDriver]);

  // 计算聚合指标
  const aggregatedMetrics = useMemo(() => {
    if (filteredData.length === 0) return null;

    const totalArea = filteredData.reduce((sum, item) => sum + item.area, 0);
    const totalDuration = filteredData.reduce((sum, item) => sum + item.duration, 0);
    const totalCost = filteredData.reduce((sum, item) => sum + item.cost, 0);
    const totalFuel = filteredData.reduce((sum, item) => sum + item.fuelConsumption, 0);
    
    // 面积加权平均质量（更科学的计算方式）
    const weightedQualitySum = filteredData.reduce((sum, item) => sum + (item.quality * item.area), 0);
    const avgQuality = totalArea > 0 ? weightedQualitySum / totalArea : 0;

    return {
      avgEfficiency: (totalArea / totalDuration).toFixed(2),
      avgCostPerArea: (totalCost / totalArea).toFixed(2),
      avgQuality: avgQuality.toFixed(1),
      totalHours: totalDuration.toFixed(1),
      totalArea: totalArea.toFixed(1),
      totalCost: totalCost.toFixed(0),
      avgFuelPerArea: (totalFuel / totalArea).toFixed(2),
    };
  }, [filteredData]);

  // 机型效率对比
  const machineryComparison = useMemo(() => {
    const machineryMap = new Map<string, { area: number; duration: number; cost: number; quality: number; count: number }>();

    filteredData.forEach(item => {
      if (!machineryMap.has(item.machineryName)) {
        machineryMap.set(item.machineryName, { area: 0, duration: 0, cost: 0, quality: 0, count: 0 });
      }
      const data = machineryMap.get(item.machineryName)!;
      data.area += item.area;
      data.duration += item.duration;
      data.cost += item.cost;
      data.quality += item.quality;
      data.count += 1;
    });

    return Array.from(machineryMap.entries()).map(([name, data]) => ({
      name,
      efficiency: parseFloat((data.area / data.duration).toFixed(2)),
      cost: parseFloat((data.cost / data.area).toFixed(2)),
      quality: parseFloat((data.quality / data.count).toFixed(1)),
    }));
  }, [filteredData]);

  // 时间趋势分析
  const trendData = useMemo(() => {
    const monthMap = new Map<string, { area: number; cost: number; count: number }>();

    filteredData.forEach(item => {
      if (!monthMap.has(item.date)) {
        monthMap.set(item.date, { area: 0, cost: 0, count: 0 });
      }
      const data = monthMap.get(item.date)!;
      data.area += item.area;
      data.cost += item.cost;
      data.count += 1;
    });

    return Array.from(monthMap.entries())
      .sort((a, b) => a[0].localeCompare(b[0]))
      .map(([month, data]) => ({
        month: month.replace('2024-', '') + '月',
        area: parseFloat(data.area.toFixed(1)),
        cost: parseFloat(data.cost.toFixed(0)),
        avgCost: parseFloat((data.cost / data.area).toFixed(2)),
      }));
  }, [filteredData]);

  // 作业类型分布
  const operationTypeData = useMemo(() => {
    const typeMap = new Map<string, number>();

    filteredData.forEach(item => {
      typeMap.set(item.operationType, (typeMap.get(item.operationType) || 0) + item.area);
    });

    const total = Array.from(typeMap.values()).reduce((sum, val) => sum + val, 0);

    return Array.from(typeMap.entries()).map(([name, value]) => ({
      name,
      value: parseFloat(value.toFixed(1)),
      percentage: parseFloat(((value / total) * 100).toFixed(1)),
    }));
  }, [filteredData]);

  // 关联分析：机型 vs 土壤 vs 油耗
  const correlationAnalysis = useMemo(() => {
    const correlationMap = new Map<string, { fuel: number; area: number; count: number }>();

    filteredData.forEach(item => {
      const key = `${item.machineryModel}-${item.soilType}`;
      if (!correlationMap.has(key)) {
        correlationMap.set(key, { fuel: 0, area: 0, count: 0 });
      }
      const data = correlationMap.get(key)!;
      data.fuel += item.fuelConsumption;
      data.area += item.area;
      data.count += 1;
    });

    return Array.from(correlationMap.entries()).map(([key, data]) => {
      const [machinery, soilType] = key.split('-');
      return {
        machinery,
        soilType,
        fuelPerArea: parseFloat((data.fuel / data.area).toFixed(2)),
        count: data.count,
      };
    });
  }, [filteredData]);

  // 智能洞察：异常检测
  const insights = useMemo(() => {
    const insights: { type: 'warning' | 'info' | 'success'; message: string }[] = [];

    // 检测高油耗组合
    correlationAnalysis.forEach(item => {
      if (item.fuelPerArea > 1.5 && item.count >= 2) {
        insights.push({
          type: 'warning',
          message: `${item.machinery}在${item.soilType}土壤条件下油耗偏高 (${item.fuelPerArea}L/亩)，建议优化作业参数或更换机型`,
        });
      }
    });

    // 检测高效组合
    correlationAnalysis.forEach(item => {
      if (item.fuelPerArea < 1.3 && item.count >= 2) {
        insights.push({
          type: 'success',
          message: `${item.machinery}在${item.soilType}土壤条件下表现优异 (${item.fuelPerArea}L/亩)，推荐继续使用`,
        });
      }
    });

    // 检测质量问题
    filteredData.forEach(item => {
      if (item.quality < 85) {
        insights.push({
          type: 'warning',
          message: `${item.machineryName}在${item.fieldName}的作业质量偏低 (${item.quality}分)，建议检查设备或驾驶员操作`,
        });
      }
    });

    // 检测成本异常
    if (aggregatedMetrics) {
      const avgCost = parseFloat(aggregatedMetrics.avgCostPerArea);
      filteredData.forEach(item => {
        const costPerArea = item.cost / item.area;
        if (costPerArea > avgCost * 1.2) {
          insights.push({
            type: 'info',
            message: `${item.machineryName}在${item.fieldName}的作业成本偏高 (${costPerArea.toFixed(2)}元/亩)，平均成本${avgCost.toFixed(2)}元/亩`,
          });
        }
      });
    }

    return insights.slice(0, 5); // 只显示前5条
  }, [correlationAnalysis, filteredData, aggregatedMetrics]);

  // 驾驶员效率对比
  const driverComparison = useMemo(() => {
    const driverMap = new Map<string, { area: number; duration: number; quality: number; count: number }>();

    filteredData.forEach(item => {
      if (!driverMap.has(item.driverName)) {
        driverMap.set(item.driverName, { area: 0, duration: 0, quality: 0, count: 0 });
      }
      const data = driverMap.get(item.driverName)!;
      data.area += item.area;
      data.duration += item.duration;
      data.quality += item.quality;
      data.count += 1;
    });

    return Array.from(driverMap.entries()).map(([name, data]) => ({
      name,
      efficiency: parseFloat((data.area / data.duration).toFixed(2)),
      quality: parseFloat((data.quality / data.count).toFixed(1)),
    }));
  }, [filteredData]);

  const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6', '#ec4899'];

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-primary">作业数据分析</h2>
        <p className="text-muted-foreground">多维度分析效率、成本和质量指标</p>
      </div>

      {/* 多维度筛选器 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-5 h-5 text-success" />
          <h3>数据筛选</h3>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="text-sm text-muted-foreground mb-2 block">时间范围</label>
            <Select value={timeRange} onValueChange={handleTimeRangeChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="last6months">最近6个月</SelectItem>
                <SelectItem value="last3months">最近3个月</SelectItem>
                <SelectItem value="last1month">最近1个月</SelectItem>
                <SelectItem value="custom">自定义时间</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <label className="text-sm text-muted-foreground mb-2 block">地块</label>
            <Select value={selectedField} onValueChange={setSelectedField}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部地块</SelectItem>
                <SelectItem value="f1">1号地块</SelectItem>
                <SelectItem value="f2">2号地块</SelectItem>
                <SelectItem value="f3">3号地块</SelectItem>
                <SelectItem value="f4">4号地块</SelectItem>
                <SelectItem value="f5">5号地块</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <label className="text-sm text-muted-foreground mb-2 block">农机</label>
            <Select value={selectedMachinery} onValueChange={setSelectedMachinery}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部农机</SelectItem>
                <SelectItem value="m1">约翰迪尔8R</SelectItem>
                <SelectItem value="m2">久保田M7</SelectItem>
                <SelectItem value="m3">雷沃欧豹</SelectItem>
                <SelectItem value="m4">东方红LX</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <label className="text-sm text-muted-foreground mb-2 block">驾驶员</label>
            <Select value={selectedDriver} onValueChange={setSelectedDriver}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部驾驶员</SelectItem>
                <SelectItem value="d1">张三</SelectItem>
                <SelectItem value="d2">李四</SelectItem>
                <SelectItem value="d3">王五</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        
        {/* 自定义时间范围选择器 */}
        {showCustomDateRange && (
          <div className="mt-4 p-4 bg-info-muted rounded-lg border-info">
            <div className="flex items-center gap-2 mb-3">
              <CalendarIcon className="w-5 h-5 text-info" />
              <h4 className="text-muted-foreground">自定义时间范围</h4>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 开始日期 */}
              <div>
                <label className="text-sm text-muted-foreground mb-2 block">开始日期</label>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className="w-full justify-start text-left"
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {customStartDate ? (
                        format(customStartDate, 'yyyy年MM月dd日', { locale: zhCN })
                      ) : (
                        <span className="text-muted-foreground">选择开始日期</span>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={customStartDate}
                      onSelect={setCustomStartDate}
                      initialFocus
                      locale={zhCN}
                    />
                  </PopoverContent>
                </Popover>
              </div>
              
              {/* 结束日期 */}
              <div>
                <label className="text-sm text-muted-foreground mb-2 block">结束日期</label>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className="w-full justify-start text-left"
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {customEndDate ? (
                        format(customEndDate, 'yyyy年MM月dd日', { locale: zhCN })
                      ) : (
                        <span className="text-muted-foreground">选择结束日期</span>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={customEndDate}
                      onSelect={setCustomEndDate}
                      initialFocus
                      locale={zhCN}
                      disabled={(date) => 
                        customStartDate ? date < customStartDate : false
                      }
                    />
                  </PopoverContent>
                </Popover>
              </div>
            </div>
            
            {/* 提示信息 */}
            {customStartDate && customEndDate && (
              <div className="mt-3 p-3 bg-white rounded border-info">
                <p className="text-sm text-muted-foreground">
                  已选择时间段：
                  <strong className="mx-1">
                    {format(customStartDate, 'yyyy年MM月dd日', { locale: zhCN })}
                  </strong>
                  至
                  <strong className="mx-1">
                    {format(customEndDate, 'yyyy年MM月dd日', { locale: zhCN })}
                  </strong>
                  （共 {Math.ceil((customEndDate.getTime() - customStartDate.getTime()) / (1000 * 60 * 60 * 24))} 天）
                </p>
              </div>
            )}
          </div>
        )}
      </Card>

      {/* 智能洞察 */}
      {insights.length > 0 && (
        <Card className="p-6 bg-info-muted border-info">
          <div className="flex items-center gap-2 mb-4">
            <Lightbulb className="w-5 h-5 text-info" />
            <h3 className="text-muted-foreground">智能洞察与建议</h3>
          </div>
          <div className="space-y-2">
            {insights.map((insight, index) => (
              <div
                key={index}
                className={`flex items-start gap-3 p-3 rounded-lg ${
                  insight.type === 'warning' ? 'bg-warning-muted border-warning' :
                  insight.type === 'success' ? 'bg-success-muted border-success' :
                  'bg-info-muted border-info'
                }`}
              >
                {insight.type === 'warning' && <AlertTriangle className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />}
                {insight.type === 'success' && <TrendingUp className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />}
                {insight.type === 'info' && <TrendingDown className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />}
                <p className="text-sm flex-1">{insight.message}</p>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* KPI卡片 */}
      {aggregatedMetrics && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-green-100">
                <TrendingUp className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <div className="text-sm text-muted-foreground">平均效率</div>
                <div className="mt-1">{aggregatedMetrics.avgEfficiency} 亩/小时</div>
              </div>
            </div>
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-blue-100">
                <DollarSign className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <div className="text-sm text-muted-foreground">平均成本</div>
                <div className="mt-1">{aggregatedMetrics.avgCostPerArea} 元/亩</div>
              </div>
            </div>
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-purple-100">
                <Target className="w-5 h-5 text-purple-600" />
              </div>
              <div>
                <div className="text-sm text-muted-foreground">平均质量</div>
                <div className="mt-1">{aggregatedMetrics.avgQuality} 分</div>
              </div>
            </div>
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-orange-100">
                <Clock className="w-5 h-5 text-orange-600" />
              </div>
              <div>
                <div className="text-sm text-muted-foreground">总工时</div>
                <div className="mt-1">{aggregatedMetrics.totalHours} 小时</div>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 多维度分析Tab */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">综合概览</TabsTrigger>
          <TabsTrigger value="machinery">机型分析</TabsTrigger>
          <TabsTrigger value="driver">驾驶员分析</TabsTrigger>
          <TabsTrigger value="correlation">关联分析</TabsTrigger>
        </TabsList>

        {/* 综合概览 */}
        <TabsContent value="overview" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 时间趋势 */}
            <Card className="p-6">
              <h3 className="mb-4">作业趋势分析</h3>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={trendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <Tooltip />
                  <Legend />
                  <Line yAxisId="left" type="monotone" dataKey="area" stroke="#10b981" strokeWidth={2} name="作业面积 (亩)" />
                  <Line yAxisId="right" type="monotone" dataKey="avgCost" stroke="#3b82f6" strokeWidth={2} name="平均成本 (元/亩)" />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            {/* 作业类型分布 */}
            <Card className="p-6">
              <h3 className="mb-4">作业类型分布</h3>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={operationTypeData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={(entry) => `${entry.name} ${entry.percentage}%`}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {operationTypeData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 机型分析 */}
        <TabsContent value="machinery" className="space-y-6">
          <Card className="p-6">
            <h3 className="mb-4">机型效率、成本与质量对比</h3>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={machineryComparison}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="efficiency" fill="#10b981" name="效率 (亩/小时)" />
                <Bar yAxisId="right" dataKey="cost" fill="#3b82f6" name="成本 (元/亩)" />
                <Bar yAxisId="right" dataKey="quality" fill="#f59e0b" name="质量 (分)" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>

        {/* 驾驶员分析 */}
        <TabsContent value="driver" className="space-y-6">
          <Card className="p-6">
            <h3 className="mb-4">驾驶员效率与质量对比</h3>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={driverComparison}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="efficiency" fill="#10b981" name="效率 (亩/小时)" />
                <Bar yAxisId="right" dataKey="quality" fill="#f59e0b" name="质量 (分)" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>

        {/* 关联分析 */}
        <TabsContent value="correlation" className="space-y-6">
          <Card className="p-6">
            <h3 className="mb-4">机型 × 土壤类型 × 油耗关联分析</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-3">机型</th>
                    <th className="text-left p-3">土壤类型</th>
                    <th className="text-right p-3">油耗 (L/亩)</th>
                    <th className="text-right p-3">样本数</th>
                    <th className="text-left p-3">评估</th>
                  </tr>
                </thead>
                <tbody>
                  {correlationAnalysis.map((item, index) => (
                    <tr key={index} className="border-b">
                      <td className="p-3">{item.machinery}</td>
                      <td className="p-3">{item.soilType}</td>
                      <td className="text-right p-3">{item.fuelPerArea}</td>
                      <td className="text-right p-3">{item.count}</td>
                      <td className="p-3">
                        {item.fuelPerArea > 1.5 ? (
                          <Badge variant="destructive">偏高</Badge>
                        ) : item.fuelPerArea < 1.3 ? (
                          <Badge className="bg-green-100 text-green-700">优秀</Badge>
                        ) : (
                          <Badge variant="outline">正常</Badge>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="mb-4">油耗散点图分析</h3>
            <ResponsiveContainer width="100%" height={300}>
              <ScatterChart>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="fuelPerArea" name="油耗" unit="L/亩" />
                <YAxis dataKey="count" name="样本数" />
                <Tooltip cursor={{ strokeDasharray: '3 3' }} />
                <Legend />
                <Scatter name="机型-土壤组合" data={correlationAnalysis} fill="#10b981" />
              </ScatterChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 功能说明 */}
      <Card className="p-6 bg-green-50 border-green-200">
        <h4 className="mb-3 text-green-900">分析功能说明</h4>
        <ul className="space-y-2 text-sm text-green-800">
          <li>✅ <strong>聚合计算</strong>：对历史作业数据进行多维度聚合，计算效率（亩/小时）、成本（元/亩）、质量指标</li>
          <li>✅ <strong>多维度钻取</strong>：支持按时间、地块、农机、驾驶员等维度进行数据筛选和深入分析</li>
          <li>✅ <strong>数据挖掘</strong>：通过关联分析发现机型与土壤条件的最优组合，识别异常油耗模式</li>
          <li>✅ <strong>智能洞察</strong>：自动检测异常数据并提供优化建议，如"某机型在特定土壤条件下油耗偏高"</li>
          <li>✅ <strong>质量评估</strong>：分析播种均匀度、深浅一致性等作业质量指标</li>
          <li>✅ <strong>质量计算</strong>：平均质量采用面积加权算法（Σ(质量×面积)/Σ(面积)），更准确反映整体作业水平</li>
        </ul>
      </Card>
    </div>
  );
}
