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';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Progress } from '../ui/progress';
import {
  FileText,
  Download,
  Eye,
  MapPin,
  Calendar,
  Users,
  Package,
  Droplet,
  Sprout,
  TrendingUp,
  BarChart3,
  Search,
  Filter,
  Database,
  Link2,
  GitBranch,
  Activity,
  Clock,
  Camera,
  CheckCircle2,
  AlertCircle,
  Layers,
  Archive,
  Gauge,
  Leaf,
  Target,
  Zap,
  FileBarChart,
  Image as ImageIcon,
  RefreshCw,
  Plus,
  Sparkles,
  ListTree,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  AreaChart,
  Area,
} from 'recharts';

interface OperationArchiveProps {
  activePath?: string;
}

interface ArchiveData {
  id: string;
  fieldId: string;
  fieldName: string;
  fieldArea: number;
  crop: string;
  variety: string;
  batchNo: string;
  season: string;
  year: number;
  startDate: string;
  endDate: string | null;
  status: '进行中' | '已完成' | '已归档';
  operations: OperationRecord[];
  inputs: InputRecord[];
  harvest: HarvestRecord[];
  iot: IoTRecord[];
  plans: PlanRecord[];
  tasks: TaskRecord[];
  completeness: number;
  lastUpdated: string;
  autoGenerated: boolean;
}

interface OperationRecord {
  id: string;
  date: string;
  time: string;
  type: string;
  description: string;
  executor: string;
  team: string;
  duration: number;
  location: { lat: number; lng: number; address: string };
  weather: string;
  photos: string[];
  notes: string;
  source: string; // 数据来源
}

interface InputRecord {
  id: string;
  date: string;
  category: '肥料' | '农药' | '种子' | '其他';
  name: string;
  brand: string;
  batchNo: string;
  amount: number;
  unit: string;
  source: string;
  supplier: string;
  cost: number;
  purpose: string;
}

interface HarvestRecord {
  id: string;
  date: string;
  area: number;
  yield: number;
  unitYield: number;
  quality: string;
  grade: string;
  moisture: number;
  impurity: number;
  destination: string;
  inspector: string;
}

interface IoTRecord {
  id: string;
  date: string;
  time: string;
  sensorType: string;
  temperature: number;
  humidity: number;
  soilMoisture: number;
  soilPH: number;
  light: number;
}

interface PlanRecord {
  id: string;
  name: string;
  startDate: string;
  endDate: string;
  activities: number;
  status: string;
  activityList?: PlanActivity[];
}

interface PlanActivity {
  id: string;
  name: string;
  type: string;
  period: string;
  duration: string;
  description: string;
}

interface TaskRecord {
  id: string;
  name: string;
  type: string;
  assignee: string;
  startDate: string;
  endDate: string;
  status: string;
  progress: number;
}

export function OperationArchive({ activePath }: OperationArchiveProps) {
  const [activeTab, setActiveTab] = useState('aggregation');
  const [filterField, setFilterField] = useState<string>('all');
  const [filterYear, setFilterYear] = useState<string>('2025');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterBatch, setFilterBatch] = useState<string>('all');
  const [selectedArchive, setSelectedArchive] = useState<ArchiveData | null>(null);
  const [showArchiveDialog, setShowArchiveDialog] = useState(false);
  const [showGenerateDialog, setShowGenerateDialog] = useState(false);
  const [generateFieldId, setGenerateFieldId] = useState<string>('');
  const [generating, setGenerating] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPlan, setSelectedPlan] = useState<PlanRecord | null>(null);
  const [showPlanActivitiesDialog, setShowPlanActivitiesDialog] = useState(false);

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

  // 模拟档案数据
  const [archives, setArchives] = useState<ArchiveData[]>([
    {
      id: 'archive-1',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      fieldArea: 50.5,
      crop: '小麦',
      variety: '优质冬小麦1号',
      batchNo: 'BATCH-2025-001',
      season: '秋冬季',
      year: 2025,
      startDate: '2025-10-01',
      endDate: null,
      status: '进行中',
      completeness: 72,
      lastUpdated: '2025-10-20',
      autoGenerated: true,
      plans: [
        {
          id: 'plan-1',
          name: '2025年秋冬季小麦种植计划',
          startDate: '2025-10-01',
          endDate: '2026-06-30',
          activities: 28,
          status: '执行中',
          activityList: [
            { id: 'act-1', name: '土地整备', type: '整地', period: '10月上旬', duration: '3天', description: '深耕深翻30cm，打碎土块，整平地面' },
            { id: 'act-2', name: '基肥施用', type: '施肥', period: '10月上旬', duration: '1天', description: '施用有机肥3000kg/亩，复合肥50kg/亩' },
            { id: 'act-3', name: '种子处理', type: '种子处理', period: '10月上旬', duration: '1天', description: '拌种剂拌种，预防病虫害' },
            { id: 'act-4', name: '播种作业', type: '播种', period: '10月中旬', duration: '2天', description: '精量播种，播种量15kg/亩，行距20cm' },
            { id: 'act-5', name: '播后镇压', type: '镇压', period: '10月中旬', duration: '1天', description: '播后镇压，确保种子与土壤紧密接触' },
            { id: 'act-6', name: '苗期查苗补种', type: '查苗', period: '10月下旬', duration: '1天', description: '检查出苗情况，及时补种缺苗断垄' },
            { id: 'act-7', name: '除草剂喷施', type: '除草', period: '11月上旬', duration: '1天', description: '苗后除草，防除杂草' },
            { id: 'act-8', name: '冬前追肥', type: '施肥', period: '11月中旬', duration: '1天', description: '追施尿素10kg/亩，促进分蘖' },
            { id: 'act-9', name: '冬灌作业', type: '灌溉', period: '11月下旬', duration: '2天', description: '冬灌80-100方/亩，促进根系生长' },
            { id: 'act-10', name: '越冬期管理', type: '管理', period: '12月-2月', duration: '持续', description: '监测苗情，预防冻害' },
            { id: 'act-11', name: '春季镇压', type: '镇压', period: '3月上旬', duration: '1天', description: '返青前镇压，保墒防冻' },
            { id: 'act-12', name: '春季追肥', type: '施肥', period: '3月中旬', duration: '1天', description: '追施尿素15kg/亩，促进起身拔节' },
            { id: 'act-13', name: '春季灌溉', type: '灌溉', period: '3月下旬', duration: '2天', description: '拔节水，灌溉60-80方/亩' },
            { id: 'act-14', name: '病虫害预防', type: '植保', period: '4月上旬', duration: '1天', description: '喷施杀菌剂，预防纹枯病、白粉病' },
            { id: 'act-15', name: '拔节期追肥', type: '施肥', period: '4月中旬', duration: '1天', description: '追施尿素10kg/亩' },
            { id: 'act-16', name: '孕穗期灌溉', type: '灌溉', period: '4月下旬', duration: '2天', description: '孕穗水，灌溉50-60方/亩' },
            { id: 'act-17', name: '一喷三防', type: '植保', period: '5月上旬', duration: '1天', description: '喷施杀虫剂、杀菌剂、叶面肥混合液' },
            { id: 'act-18', name: '扬花期管理', type: '管理', period: '5月中旬', duration: '持续', description: '监测天气，防止倒伏和病害' },
            { id: 'act-19', name: '灌浆期灌溉', type: '灌溉', period: '5月下旬', duration: '2天', description: '灌浆水，灌溉40-50方/亩' },
            { id: 'act-20', name: '后期病虫防治', type: '植保', period: '6月上旬', duration: '1天', description: '防治蚜虫、赤霉病等' },
            { id: 'act-21', name: '成熟期监测', type: '监测', period: '6月中旬', duration: '持续', description: '监测籽粒成熟度，确定收获时间' },
            { id: 'act-22', name: '收获前准备', type: '准备', period: '6月中旬', duration: '2天', description: '检修机械，准备收获' },
            { id: 'act-23', name: '联合收割', type: '收获', period: '6月下旬', duration: '3天', description: '联合收割机收获，控制损失率' },
            { id: 'act-24', name: '秸秆处理', type: '清理', period: '6月下旬', duration: '2天', description: '秸秆粉碎还田或打捆离田' },
            { id: 'act-25', name: '晾晒入库', type: '仓储', period: '6月下旬', duration: '3天', description: '籽粒晾晒至安全水分，入库储存' },
            { id: 'act-26', name: '产量统计', type: '统计', period: '6月下旬', duration: '1天', description: '称重统计产量，计算单产' },
            { id: 'act-27', name: '质量检测', type: '检测', period: '6月下旬', duration: '1天', description: '检测水分、杂质、容重等指标' },
            { id: 'act-28', name: '效益分析', type: '分析', period: '6月下旬', duration: '1天', description: '核算成本和收益，总结经验' },
          ]
        }
      ],
      tasks: [
        {
          id: 'task-1',
          name: '小麦播种任务',
          type: '播种',
          assignee: '张三',
          startDate: '2025-10-01',
          endDate: '2025-10-03',
          status: '已完成',
          progress: 100,
        },
        {
          id: 'task-2',
          name: '小麦除草任务',
          type: '除草',
          assignee: '张三',
          startDate: '2025-10-17',
          endDate: '2025-10-19',
          status: '进行中',
          progress: 65,
        },
      ],
      operations: [
        {
          id: 'op-1',
          date: '2025-10-01',
          time: '08:00',
          type: '深翻',
          description: '使用旋耕机进行土地深翻作业',
          executor: '张三',
          team: '第一作业组',
          duration: 4,
          location: { lat: 30.25, lng: 120.15, address: '浙江省杭州市余杭区东区1号地' },
          weather: '晴天',
          photos: ['photo1.jpg', 'photo2.jpg'],
          notes: '土壤墒情良好，深度25cm',
          source: '操作录入模块',
        },
        {
          id: 'op-2',
          date: '2025-10-02',
          time: '09:00',
          type: '施底肥',
          description: '施用复合肥作为底肥',
          executor: '张三',
          team: '第一作业组',
          duration: 3,
          location: { lat: 30.25, lng: 120.15, address: '浙江省杭州市余杭区东区1号地' },
          weather: '晴天',
          photos: ['photo3.jpg'],
          notes: '复合肥用量101kg，均匀撒施',
          source: '操作录入模块',
        },
        {
          id: 'op-3',
          date: '2025-10-03',
          time: '07:30',
          type: '播种',
          description: '优质冬小麦播种',
          executor: '张三',
          team: '第一作业组',
          duration: 5,
          location: { lat: 30.25, lng: 120.15, address: '浙江省杭州市余杭区东区1号地' },
          weather: '晴天',
          photos: ['photo4.jpg', 'photo5.jpg'],
          notes: '播种深度3-4cm，行距20cm',
          source: '操作录入模块',
        },
        {
          id: 'op-4',
          date: '2025-10-08',
          time: '09:00',
          type: '灌溉',
          description: '播后第一次灌溉',
          executor: '张三',
          team: '第一作业组',
          duration: 2,
          location: { lat: 30.25, lng: 120.15, address: '浙江省杭州市余杭区东区1号地' },
          weather: '晴天',
          photos: [],
          notes: '滴灌系统，水量25mm',
          source: '操作录入模块',
        },
        {
          id: 'op-5',
          date: '2025-10-18',
          time: '08:30',
          type: '除草',
          description: '人工除草',
          executor: '张三',
          team: '第一作业组',
          duration: 6,
          location: { lat: 30.25, lng: 120.15, address: '浙江省杭州市余杭区东区1号地' },
          weather: '多云',
          photos: ['photo6.jpg'],
          notes: '主要清除阔叶杂草',
          source: '操作录入模块',
        },
      ],
      inputs: [
        {
          id: 'input-1',
          date: '2025-10-01',
          category: '种子',
          name: '优质冬小麦1号',
          brand: '隆平高科',
          batchNo: 'LP20250901',
          amount: 177,
          unit: 'kg',
          source: '采购',
          supplier: '杭州种业公司',
          cost: 3540,
          purpose: '秋季播种',
        },
        {
          id: 'input-2',
          date: '2025-10-02',
          category: '肥料',
          name: '复合肥（NPK 15-15-15）',
          brand: '金正大',
          batchNo: 'JZD20250925',
          amount: 2020,
          unit: 'kg',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 10100,
          purpose: '底肥施用',
        },
        {
          id: 'input-3',
          date: '2025-10-16',
          category: '农药',
          name: '除草剂',
          brand: '先正达',
          batchNo: 'XZD20251010',
          amount: 3.5,
          unit: 'L',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 700,
          purpose: '杂草防治',
        },
      ],
      harvest: [],
      iot: [
        {
          id: 'iot-1',
          date: '2025-10-05',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 18.5,
          humidity: 62,
          soilMoisture: 72,
          soilPH: 6.8,
          light: 48000,
        },
        {
          id: 'iot-2',
          date: '2025-10-10',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 16.2,
          humidity: 68,
          soilMoisture: 68,
          soilPH: 6.7,
          light: 42000,
        },
        {
          id: 'iot-3',
          date: '2025-10-15',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 19.8,
          humidity: 58,
          soilMoisture: 75,
          soilPH: 6.8,
          light: 51000,
        },
        {
          id: 'iot-4',
          date: '2025-10-20',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 17.3,
          humidity: 65,
          soilMoisture: 70,
          soilPH: 6.7,
          light: 45000,
        },
      ],
    },
    {
      id: 'archive-2',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      fieldArea: 45.2,
      crop: '油菜',
      variety: '优质油菜2号',
      batchNo: 'BATCH-2025-002',
      season: '秋冬季',
      year: 2025,
      startDate: '2025-10-02',
      endDate: null,
      status: '进行中',
      completeness: 68,
      lastUpdated: '2025-10-20',
      autoGenerated: true,
      plans: [
        {
          id: 'plan-2',
          name: '2025年油菜种植计划',
          startDate: '2025-10-02',
          endDate: '2026-05-31',
          activities: 24,
          status: '执行中',
        }
      ],
      tasks: [
        {
          id: 'task-3',
          name: '油菜播种任务',
          type: '播种',
          assignee: '李四',
          startDate: '2025-10-07',
          endDate: '2025-10-09',
          status: '已完成',
          progress: 100,
        },
        {
          id: 'task-4',
          name: '油菜灌溉任务',
          type: '灌溉',
          assignee: '李四',
          startDate: '2025-10-18',
          endDate: '2025-10-18',
          status: '进行中',
          progress: 80,
        },
      ],
      operations: [
        {
          id: 'op-6',
          date: '2025-10-02',
          time: '08:00',
          type: '整地',
          description: '土地平整和耕作',
          executor: '李四',
          team: '第二作业组',
          duration: 4,
          location: { lat: 30.28, lng: 120.12, address: '浙江省杭州市余杭区西区2号地' },
          weather: '晴天',
          photos: [],
          notes: '整地质量良好',
          source: '操作录入模块',
        },
        {
          id: 'op-7',
          date: '2025-10-03',
          time: '09:00',
          type: '施底肥',
          description: '施用有机肥和复合肥',
          executor: '李四',
          team: '第二作业组',
          duration: 3,
          location: { lat: 30.28, lng: 120.12, address: '浙江省杭州市余杭区西区2号地' },
          weather: '晴天',
          photos: ['photo7.jpg'],
          notes: '有机肥2000kg + 复合肥800kg',
          source: '操作录入模块',
        },
        {
          id: 'op-8',
          date: '2025-10-08',
          time: '07:30',
          type: '播种',
          description: '油菜直播',
          executor: '李四',
          team: '第二作业组',
          duration: 4,
          location: { lat: 30.28, lng: 120.12, address: '浙江省杭州市余杭区西区2号地' },
          weather: '晴天',
          photos: ['photo8.jpg', 'photo9.jpg'],
          notes: '行距30cm，播量0.3kg/亩',
          source: '操作录入模块',
        },
        {
          id: 'op-9',
          date: '2025-10-18',
          time: '10:00',
          type: '灌溉',
          description: '苗期灌溉',
          executor: '李四',
          team: '第二作业组',
          duration: 2,
          location: { lat: 30.28, lng: 120.12, address: '浙江省杭州市余杭区西区2号地' },
          weather: '晴天',
          photos: [],
          notes: '喷灌系统，水量20mm',
          source: '操作录入模块',
        },
      ],
      inputs: [
        {
          id: 'input-4',
          date: '2025-10-02',
          category: '种子',
          name: '优质油菜2号',
          brand: '中油杂',
          batchNo: 'ZYZ20250901',
          amount: 13.56,
          unit: 'kg',
          source: '采购',
          supplier: '杭州种业公司',
          cost: 2712,
          purpose: '秋季播种',
        },
        {
          id: 'input-5',
          date: '2025-10-03',
          category: '肥料',
          name: '有机肥',
          brand: '绿丰',
          batchNo: 'LF20250920',
          amount: 2000,
          unit: 'kg',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 6000,
          purpose: '底肥施用',
        },
        {
          id: 'input-6',
          date: '2025-10-03',
          category: '肥料',
          name: '复合肥',
          brand: '金正大',
          batchNo: 'JZD20250925',
          amount: 800,
          unit: 'kg',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 4000,
          purpose: '底肥施用',
        },
      ],
      harvest: [],
      iot: [
        {
          id: 'iot-5',
          date: '2025-10-10',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 17.8,
          humidity: 65,
          soilMoisture: 70,
          soilPH: 7.0,
          light: 46000,
        },
        {
          id: 'iot-6',
          date: '2025-10-15',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 18.5,
          humidity: 60,
          soilMoisture: 68,
          soilPH: 6.9,
          light: 49000,
        },
        {
          id: 'iot-7',
          date: '2025-10-20',
          time: '12:00',
          sensorType: '环境监测站',
          temperature: 16.9,
          humidity: 67,
          soilMoisture: 72,
          soilPH: 7.0,
          light: 44000,
        },
      ],
    },
    {
      id: 'archive-3',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      fieldArea: 60.3,
      crop: '水稻',
      variety: '优质水稻1号',
      batchNo: 'BATCH-2025-003',
      season: '夏秋季',
      year: 2025,
      startDate: '2025-06-01',
      endDate: '2025-10-15',
      status: '已完成',
      completeness: 100,
      lastUpdated: '2025-10-15',
      autoGenerated: true,
      plans: [
        {
          id: 'plan-3',
          name: '2025年夏季水稻种植计划',
          startDate: '2025-06-01',
          endDate: '2025-10-15',
          activities: 32,
          status: '已完成',
        }
      ],
      tasks: [
        {
          id: 'task-5',
          name: '水稻播种',
          type: '播种',
          assignee: '陈七',
          startDate: '2025-06-01',
          endDate: '2025-06-05',
          status: '已完成',
          progress: 100,
        },
        {
          id: 'task-6',
          name: '水稻采收',
          type: '采收',
          assignee: '陈七',
          startDate: '2025-10-10',
          endDate: '2025-10-15',
          status: '已完成',
          progress: 100,
        },
      ],
      operations: [
        {
          id: 'op-10',
          date: '2025-06-01',
          time: '08:00',
          type: '深翻',
          description: '水田深翻作业',
          executor: '陈七',
          team: '第三作业组',
          duration: 5,
          location: { lat: 30.22, lng: 120.18, address: '浙江省杭州市余杭区南区3号地' },
          weather: '晴天',
          photos: ['photo10.jpg'],
          notes: '水田深度20cm',
          source: '操作录入模块',
        },
        {
          id: 'op-11',
          date: '2025-06-05',
          time: '07:00',
          type: '插秧',
          description: '机械化插秧',
          executor: '陈七',
          team: '第三作业组',
          duration: 6,
          location: { lat: 30.22, lng: 120.18, address: '浙江省杭州市余杭区南区3号地' },
          weather: '晴天',
          photos: ['photo11.jpg', 'photo12.jpg'],
          notes: '株距20cm×30cm',
          source: '操作录入模块',
        },
        {
          id: 'op-12',
          date: '2025-10-12',
          time: '08:00',
          type: '采收',
          description: '机械化收割',
          executor: '陈七',
          team: '第三作业组',
          duration: 8,
          location: { lat: 30.22, lng: 120.18, address: '浙江省杭州市余杭区南区3号地' },
          weather: '晴天',
          photos: ['photo13.jpg', 'photo14.jpg', 'photo15.jpg'],
          notes: '收割机作业，含水率14.2%',
          source: '操作录入模块',
        },
      ],
      inputs: [
        {
          id: 'input-7',
          date: '2025-06-01',
          category: '种子',
          name: '优质水稻1号',
          brand: '隆平高科',
          batchNo: 'LP20250501',
          amount: 211,
          unit: 'kg',
          source: '采购',
          supplier: '杭州种业公司',
          cost: 4220,
          purpose: '夏季插秧',
        },
        {
          id: 'input-8',
          date: '2025-06-02',
          category: '肥料',
          name: '水稻专用肥',
          brand: '金正大',
          batchNo: 'JZD20250520',
          amount: 2410,
          unit: 'kg',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 12050,
          purpose: '基肥和追肥',
        },
        {
          id: 'input-9',
          date: '2025-07-15',
          category: '农药',
          name: '稻瘟灵',
          brand: '先正达',
          batchNo: 'XZD20250710',
          amount: 4.2,
          unit: 'L',
          source: '采购',
          supplier: '杭州农资公司',
          cost: 840,
          purpose: '病虫害防治',
        },
      ],
      harvest: [
        {
          id: 'harvest-1',
          date: '2025-10-15',
          area: 60.3,
          yield: 30150,
          unitYield: 500,
          quality: '优质',
          grade: '一等',
          moisture: 14.2,
          impurity: 1.1,
          destination: '粮食收储中心',
          inspector: '王五',
        },
      ],
      iot: [
        {
          id: 'iot-8',
          date: '2025-06-15',
          time: '12:00',
          sensorType: '水田监测站',
          temperature: 28.5,
          humidity: 78,
          soilMoisture: 95,
          soilPH: 6.5,
          light: 58000,
        },
        {
          id: 'iot-9',
          date: '2025-08-15',
          time: '12:00',
          sensorType: '水田监测站',
          temperature: 32.8,
          humidity: 82,
          soilMoisture: 92,
          soilPH: 6.4,
          light: 62000,
        },
      ],
    },
  ]);

  const mockFields = [
    { id: 'field-1', name: '东区1号地', area: 50.5, crop: '小麦' },
    { id: 'field-2', name: '西区2号地', area: 45.2, crop: '油菜' },
    { id: 'field-3', name: '南区3号地', area: 60.3, crop: '水稻' },
    { id: 'field-4', name: '北区4号地', area: 44.0, crop: '小麦' },
  ];

  // 生成档案
  const handleGenerateArchive = () => {
    if (!generateFieldId) {
      toast.error('请选择地块');
      return;
    }

    setGenerating(true);
    const field = mockFields.find(f => f.id === generateFieldId);
    
    toast.loading('正在自动归集数据...', { id: 'generating' });
    
    setTimeout(() => {
      toast.loading('正在关联农事计划...', { id: 'generating' });
    }, 500);

    setTimeout(() => {
      toast.loading('正在关联任务记录...', { id: 'generating' });
    }, 1000);

    setTimeout(() => {
      toast.loading('正在关联操作记录...', { id: 'generating' });
    }, 1500);

    setTimeout(() => {
      toast.loading('正在关联投入品数据...', { id: 'generating' });
    }, 2000);

    setTimeout(() => {
      toast.loading('正在关联物联网监测数据...', { id: 'generating' });
    }, 2500);

    setTimeout(() => {
      toast.loading('正在按时序排列整理...', { id: 'generating' });
    }, 3000);

    setTimeout(() => {
      const newArchive: ArchiveData = {
        id: `archive-${Date.now()}`,
        fieldId: generateFieldId,
        fieldName: field?.name || '',
        fieldArea: field?.area || 0,
        crop: field?.crop || '',
        variety: `优质${field?.crop}1号`,
        batchNo: `BATCH-${new Date().getFullYear()}-${String(archives.length + 1).padStart(3, '0')}`,
        season: '秋冬季',
        year: 2025,
        startDate: new Date().toISOString().split('T')[0],
        endDate: null,
        status: '进行中',
        completeness: 0,
        lastUpdated: new Date().toISOString().split('T')[0],
        autoGenerated: true,
        plans: [],
        tasks: [],
        operations: [],
        inputs: [],
        harvest: [],
        iot: [],
      };

      setArchives(prev => [newArchive, ...prev]);
      setGenerating(false);
      setShowGenerateDialog(false);
      setGenerateFieldId('');
      toast.success('档案生成成功！已自动归集所有相关数据', { id: 'generating' });
    }, 3500);
  };

  const handleViewArchive = (archive: ArchiveData) => {
    setSelectedArchive(archive);
    setShowArchiveDialog(true);
  };

  const handleExportArchive = (archive: ArchiveData) => {
    toast.loading('正在导出档案...', { id: 'export' });
    setTimeout(() => {
      toast.success(`档案 ${archive.batchNo} 导出成功`, { id: 'export' });
    }, 1500);
  };

  const handleBatchExport = () => {
    toast.loading('正在批量导出档案...', { id: 'batch-export' });
    setTimeout(() => {
      toast.success(`成功导出 ${filteredArchives.length} 个档案`, { id: 'batch-export' });
    }, 2000);
  };

  // 获取所有批次号
  const allBatches = Array.from(new Set(archives.map(a => a.batchNo)));

  // 筛选逻辑
  const filteredArchives = archives.filter(a => {
    if (filterField !== 'all' && a.fieldId !== filterField) return false;
    if (filterYear !== 'all' && a.year.toString() !== filterYear) return false;
    if (filterStatus !== 'all' && a.status !== filterStatus) return false;
    if (filterBatch !== 'all' && a.batchNo !== filterBatch) return false;
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      return (
        a.batchNo.toLowerCase().includes(term) ||
        a.crop.toLowerCase().includes(term) ||
        a.variety.toLowerCase().includes(term) ||
        a.fieldName.toLowerCase().includes(term)
      );
    }
    return true;
  });

  // 统计数据
  const totalArchives = filteredArchives.length;
  const totalOperations = filteredArchives.reduce((sum, a) => sum + a.operations.length, 0);
  const totalInputs = filteredArchives.reduce((sum, a) => sum + a.inputs.length, 0);
  const totalHarvest = filteredArchives.reduce((sum, a) => sum + a.harvest.length, 0);
  const totalPlans = filteredArchives.reduce((sum, a) => sum + a.plans.length, 0);
  const totalTasks = filteredArchives.reduce((sum, a) => sum + a.tasks.length, 0);
  const totalIoT = filteredArchives.reduce((sum, a) => sum + a.iot.length, 0);

  // 投入品统计
  const inputStats = filteredArchives.flatMap(a => a.inputs).reduce((acc, input) => {
    const category = input.category;
    if (!acc[category]) {
      acc[category] = { count: 0, cost: 0 };
    }
    acc[category].count++;
    acc[category].cost += input.cost;
    return acc;
  }, {} as Record<string, { count: number; cost: number }>);

  const inputChartData = Object.entries(inputStats).map(([category, data]) => ({
    name: category,
    数量: data.count,
    成本: data.cost,
  }));

  // 操作类型统计
  const operationTypeStats = filteredArchives
    .flatMap(a => a.operations)
    .reduce((acc, op) => {
      acc[op.type] = (acc[op.type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

  const operationChartData = Object.entries(operationTypeStats).map(([type, count]) => ({
    name: type,
    次数: count,
  }));

  // 时间线数据（用于追踪溯源）
  const getTimelineData = (archive: ArchiveData) => {
    const events: Array<{
      date: string;
      time: string;
      type: string;
      icon: any;
      color: string;
      title: string;
      description: string;
      details?: any;
    }> = [];

    // 添加计划
    archive.plans.forEach(plan => {
      events.push({
        date: plan.startDate,
        time: '00:00',
        type: '计划',
        icon: Calendar,
        color: 'blue',
        title: plan.name,
        description: `包含 ${plan.activities} 项农事活动`,
        details: plan,
      });
    });

    // 添加任务
    archive.tasks.forEach(task => {
      events.push({
        date: task.startDate,
        time: '00:00',
        type: '任务',
        icon: ListTree,
        color: 'purple',
        title: task.name,
        description: `负责人: ${task.assignee}`,
        details: task,
      });
    });

    // 添加操作
    archive.operations.forEach(op => {
      events.push({
        date: op.date,
        time: op.time,
        type: '操作',
        icon: Activity,
        color: 'green',
        title: `${op.type} - ${op.description}`,
        description: `执行人: ${op.executor}`,
        details: op,
      });
    });

    // 添加投入品
    archive.inputs.forEach(input => {
      events.push({
        date: input.date,
        time: '00:00',
        type: '投入',
        icon: Package,
        color: 'orange',
        title: `使用${input.category}: ${input.name}`,
        description: `用量: ${input.amount}${input.unit}`,
        details: input,
      });
    });

    // 添加IoT数据
    archive.iot.forEach(iot => {
      events.push({
        date: iot.date,
        time: iot.time,
        type: 'IoT',
        icon: Gauge,
        color: 'red',
        title: `${iot.sensorType}监测`,
        description: `温度: ${iot.temperature}°C, 湿度: ${iot.humidity}%`,
        details: iot,
      });
    });

    // 添加采收
    archive.harvest.forEach(harvest => {
      events.push({
        date: harvest.date,
        time: '00:00',
        type: '采收',
        icon: Sprout,
        color: 'yellow',
        title: `采收 ${harvest.yield}kg`,
        description: `单产: ${harvest.unitYield}kg/亩, 品质: ${harvest.quality}`,
        details: harvest,
      });
    });

    // 按时间排序
    events.sort((a, b) => {
      const dateA = new Date(`${a.date} ${a.time}`);
      const dateB = new Date(`${b.date} ${b.time}`);
      return dateA.getTime() - dateB.getTime();
    });

    return events;
  };

  const COLORS = ['#22c55e', '#eab308', '#3b82f6', '#a855f7', '#ef4444', '#f97316'];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">农事档案归集与生成</h2>
          <p className="text-muted-foreground">
            自动关联多模块数据，动态汇聚生成完整时序档案
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleBatchExport}>
            <Download className="w-4 h-4 mr-2" />
            批量导出
          </Button>
          <Button 
            className="bg-success hover:bg-success/90"
            onClick={() => setShowGenerateDialog(true)}
          >
            <Sparkles className="w-4 h-4 mr-2" />
            智能生成档案
          </Button>
        </div>
      </div>

      {/* 统计概览 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">档案总数</p>
              <p className="mt-2 text-3xl text-success">{totalArchives}</p>
              <p className="mt-1 text-xs text-muted-foreground">
                进行中 {archives.filter(a => a.status === '进行中').length} 个
              </p>
            </div>
            <Archive className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">关联数据源</p>
              <p className="mt-2 text-3xl text-info">6</p>
              <p className="mt-1 text-xs text-muted-foreground">
                计划·任务·操作·投入·IoT·采收
              </p>
            </div>
            <Link2 className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">总记录数</p>
              <p className="mt-2 text-3xl text-foreground">
                {totalOperations + totalInputs + totalIoT + totalHarvest}
              </p>
              <p className="mt-1 text-xs text-muted-foreground">
                自动归集整理
              </p>
            </div>
            <Database className="w-12 h-12 text-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均完整度</p>
              <p className="mt-2 text-3xl text-warning">
                {Math.round(filteredArchives.reduce((sum, a) => sum + a.completeness, 0) / (filteredArchives.length || 1))}%
              </p>
              <p className="mt-1 text-xs text-muted-foreground">
                实时更新
              </p>
            </div>
            <TrendingUp className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      {/* 筛选器 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <Filter className="w-4 h-4 text-muted-foreground" />
          <Select value={filterField} onValueChange={setFilterField}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="选择地块" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部地块</SelectItem>
              {mockFields.map(field => (
                <SelectItem key={field.id} value={field.id}>
                  {field.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={filterYear} onValueChange={setFilterYear}>
            <SelectTrigger className="w-36">
              <SelectValue placeholder="选择年份" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部年份</SelectItem>
              <SelectItem value="2025">2025年</SelectItem>
              <SelectItem value="2024">2024年</SelectItem>
              <SelectItem value="2023">2023年</SelectItem>
            </SelectContent>
          </Select>

          <Select value={filterBatch} onValueChange={setFilterBatch}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="选择批次" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部批次</SelectItem>
              {allBatches.map(batch => (
                <SelectItem key={batch} value={batch}>
                  {batch}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={filterStatus} onValueChange={setFilterStatus}>
            <SelectTrigger className="w-36">
              <SelectValue placeholder="档案状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="进行中">进行中</SelectItem>
              <SelectItem value="已完成">已完成</SelectItem>
              <SelectItem value="已归档">已归档</SelectItem>
            </SelectContent>
          </Select>

          <div className="flex-1" />
          <div className="flex items-center gap-2">
            <Search className="w-4 h-4 text-muted-foreground" />
            <Input 
              placeholder="搜索批次号、作物、品种..." 
              className="w-64"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="aggregation">
            <Database className="w-4 h-4 mr-2" />
            档案归集与生成
          </TabsTrigger>
          <TabsTrigger value="view">
            <Layers className="w-4 h-4 mr-2" />
            全维度数据视图
          </TabsTrigger>
          <TabsTrigger value="trace">
            <GitBranch className="w-4 h-4 mr-2" />
            追踪与溯源
          </TabsTrigger>
        </TabsList>

        {/* 档案归集与生成 */}
        <TabsContent value="aggregation" className="space-y-4">
          {/* 归集说明 */}
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <Sparkles className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-gray-800">
                <p className="mb-2 font-medium">智能档案归集系统：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动关联</strong>: 系统自动关联农事计划、任务、操作记录、物联网监测、农资使用、采收数据等6大模块数据</li>
                  <li>• <strong>多维度汇聚</strong>: 支持按地块、批次、季节、年份等维度动态汇聚数据，灵活组织档案</li>
                  <li>• <strong>时序排列</strong>: 所有操作按时间顺序自动排列，形成完整时间线，清晰展现农事全过程</li>
                  <li>• <strong>无需人工</strong>: 全程自动化处理，无需手动整理，确保数据完整性和准确性，节省80%以上人力</li>
                  <li>• <strong>实时更新</strong>: 新增操作自动纳入档案，保持档案最新状态，完整度实时计算</li>
                  <li>• <strong>智能导出</strong>: 一键导出完整档案，支持PDF、Excel等多种格式，满足不同场景需求</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 档案列表 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Archive className="w-5 h-5 text-accent" />
                已生成档案列表
                <Badge variant="outline">{filteredArchives.length} 个</Badge>
              </h3>
              {filteredArchives.length > 0 && (
                <div className="text-sm text-muted-foreground">
                  平均完整度: {Math.round(filteredArchives.reduce((sum, a) => sum + a.completeness, 0) / filteredArchives.length)}%
                </div>
              )}
            </div>
            <div className="space-y-4">
              {filteredArchives.length === 0 ? (
                <div className="text-center py-12">
                  <Archive className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <p className="text-gray-500 mb-4">暂无档案数据</p>
                  <Button 
                    onClick={() => setShowGenerateDialog(true)}
                    className="bg-success hover:bg-success/90"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    生成第一个档案
                  </Button>
                </div>
              ) : (
                filteredArchives.map(archive => (
                  <Card key={archive.id} className="p-4 border-l-4 border-l-green-500 hover:shadow-lg transition-shadow">
                    <div className="flex items-start justify-between mb-4">
                      <div className="flex items-start gap-3">
                        <div className="p-3 bg-success-muted rounded-lg">
                          <FileText className="w-6 h-6 text-success" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{archive.fieldName} - {archive.crop} ({archive.variety})</h4>
                            <Badge className={
                              archive.status === '进行中' ? 'bg-success-muted text-success' :
                              archive.status === '已完成' ? 'bg-info-muted text-info' :
                              'bg-muted text-muted-foreground'
                            }>
                              {archive.status}
                            </Badge>
                            <Badge variant="outline">{archive.season} {archive.year}</Badge>
                            {archive.autoGenerated && (
                              <Badge variant="outline" className="bg-accent-muted text-accent">
                                <Sparkles className="w-3 h-3 mr-1" />
                                智能生成
                              </Badge>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">
                            批次号: {archive.batchNo} | 面积: {archive.fieldArea} 亩 | 
                            {archive.startDate} ~ {archive.endDate || '进行中'}
                          </p>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => handleViewArchive(archive)}>
                          <Eye className="w-4 h-4 mr-2" />
                          查看
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleExportArchive(archive)}>
                          <Download className="w-4 h-4 mr-2" />
                          导出
                        </Button>
                      </div>
                    </div>

                    <div className="grid grid-cols-7 gap-3 mb-4">
                      <div className="p-3 bg-info-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">计划</p>
                        <p className="mt-1 text-lg font-medium text-info">{archive.plans.length}</p>
                      </div>
                      <div className="p-3 bg-accent-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">任务</p>
                        <p className="mt-1 text-lg font-medium text-accent">{archive.tasks.length}</p>
                      </div>
                      <div className="p-3 bg-success-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">操作</p>
                        <p className="mt-1 text-lg font-medium text-success">{archive.operations.length}</p>
                      </div>
                      <div className="p-3 bg-warning-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">投入</p>
                        <p className="mt-1 text-lg font-medium text-warning">{archive.inputs.length}</p>
                      </div>
                      <div className="p-3 bg-error-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">IoT</p>
                        <p className="mt-1 text-lg font-medium text-error">{archive.iot.length}</p>
                      </div>
                      <div className="p-3 bg-warning-muted rounded-lg">
                        <p className="text-xs text-muted-foreground">采收</p>
                        <p className="mt-1 text-lg font-medium text-warning">{archive.harvest.length}</p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">完整度</p>
                        <p className="mt-1 text-lg font-medium text-gray-800">{archive.completeness}%</p>
                      </div>
                    </div>

                    <div className="mb-3">
                      <div className="flex items-center justify-between text-sm mb-2">
                        <span className="text-muted-foreground">档案完整度</span>
                        <span className="font-medium">{archive.completeness}%</span>
                      </div>
                      <Progress value={archive.completeness} className="h-2" />
                    </div>

                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>最后更新: {archive.lastUpdated}</span>
                      <span>
                        总记录: {
                          archive.plans.length + 
                          archive.tasks.length + 
                          archive.operations.length + 
                          archive.inputs.length + 
                          archive.iot.length + 
                          archive.harvest.length
                        } 条
                      </span>
                    </div>
                  </Card>
                ))
              )}
            </div>
          </Card>
        </TabsContent>

        {/* 全维度数据视图 */}
        <TabsContent value="view" className="space-y-4">
          {/* 数据统计图表 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-info" />
                操作类型分布
              </h3>
              <div className="h-80">
                {operationChartData.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={operationChartData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis />
                      <RechartsTooltip />
                      <Bar dataKey="次数" fill="#3b82f6" />
                    </BarChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-full flex items-center justify-center text-gray-400">
                    暂无数据
                  </div>
                )}
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-success" />
                投入品成本分析
              </h3>
              <div className="h-80">
                {inputChartData.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={inputChartData}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                        outerRadius={100}
                        fill="#8884d8"
                        dataKey="成本"
                      >
                        {inputChartData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <RechartsTooltip />
                    </PieChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-full flex items-center justify-center text-gray-400">
                    暂无数据
                  </div>
                )}
              </div>
            </Card>
          </div>

          {/* 详细数据表格 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Layers className="w-5 h-5 text-accent" />
              全维度数据详情
            </h3>
            
            {filteredArchives.length === 0 ? (
              <div className="text-center py-12 text-gray-400">
                暂无档案数据
              </div>
            ) : (
              filteredArchives.map(archive => (
                <Card key={archive.id} className="p-6 mb-4">
                  <div className="flex items-center justify-between mb-6">
                    <div>
                      <h4>{archive.fieldName} - {archive.crop}</h4>
                      <p className="text-sm text-muted-foreground">批次: {archive.batchNo}</p>
                    </div>
                    <Badge className={
                      archive.status === '进行中' ? 'bg-success-muted text-success' :
                      archive.status === '已完成' ? 'bg-info-muted text-info' :
                      'bg-muted text-muted-foreground'
                    }>
                      {archive.status}
                    </Badge>
                  </div>

                  {/* 农事操作 */}
                  {archive.operations.length > 0 && (
                    <div className="mb-6">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Activity className="w-4 h-4 text-info" />
                        农事操作记录 ({archive.operations.length} 次)
                      </h4>
                      <div className="space-y-3">
                        {archive.operations.map(op => (
                          <Card key={op.id} className="p-4 bg-info-muted">
                            <div className="flex items-start justify-between mb-2">
                              <div>
                                <div className="flex items-center gap-2 mb-1">
                                  <Badge variant="outline">{op.type}</Badge>
                                  <span className="text-sm font-medium">{op.description}</span>
                                </div>
                                <p className="text-xs text-muted-foreground">
                                  📅 {op.date} {op.time} | 👤 {op.executor} ({op.team}) | 
                                  ⏱️ {op.duration}小时 | 🌤️ {op.weather}
                                </p>
                              </div>
                              {op.photos.length > 0 && (
                                <Badge variant="outline">
                                  <Camera className="w-3 h-3 mr-1" />
                                  {op.photos.length} 张照片
                                </Badge>
                              )}
                            </div>
                            <div className="flex items-start gap-2 text-xs">
                              <MapPin className="w-3 h-3 mt-0.5 text-muted-foreground" />
                              <span className="text-muted-foreground">{op.location.address}</span>
                            </div>
                            {op.notes && (
                              <div className="mt-2 p-2 bg-white rounded text-xs">
                                📝 {op.notes}
                              </div>
                            )}
                            <div className="mt-2 text-xs text-muted-foreground">
                              数据来源: {op.source}
                            </div>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 投入品记录 */}
                  {archive.inputs.length > 0 && (
                    <div className="mb-6">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Package className="w-4 h-4 text-accent" />
                        投入品记录 ({archive.inputs.length} 项)
                      </h4>
                      <div className="grid grid-cols-2 gap-3">
                        {archive.inputs.map(input => (
                          <Card key={input.id} className="p-4 bg-accent-muted">
                            <div className="flex items-start justify-between mb-2">
                              <div>
                                <div className="flex items-center gap-2 mb-1">
                                  <Badge className="bg-accent-muted text-accent">{input.category}</Badge>
                                  <span className="text-sm font-medium">{input.name}</span>
                                </div>
                                <p className="text-xs text-muted-foreground">
                                  品牌: {input.brand} | 批号: {input.batchNo}
                                </p>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-2 text-xs mt-2">
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">用量</span>
                                <p className="font-medium">{input.amount} {input.unit}</p>
                              </div>
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">成本</span>
                                <p className="font-medium">¥{input.cost}</p>
                              </div>
                            </div>
                            <div className="mt-2 text-xs">
                              <span className="text-muted-foreground">
                                📅 {input.date} | 🏪 {input.supplier} | 用途: {input.purpose}
                              </span>
                            </div>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* IoT数据 */}
                  {archive.iot.length > 0 && (
                    <div className="mb-6">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Gauge className="w-4 h-4 text-error" />
                        物联网监测数据 ({archive.iot.length} 条)
                      </h4>
                      <div className="grid grid-cols-2 gap-3">
                        {archive.iot.map(iot => (
                          <Card key={iot.id} className="p-4 bg-error-muted">
                            <div className="flex items-center justify-between mb-3">
                              <div>
                                <Badge className="bg-error-muted text-error">{iot.sensorType}</Badge>
                                <p className="text-xs text-muted-foreground mt-1">
                                  {iot.date} {iot.time}
                                </p>
                              </div>
                            </div>
                            <div className="grid grid-cols-3 gap-2 text-xs">
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">温度</span>
                                <p className="font-medium">{iot.temperature}°C</p>
                              </div>
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">湿度</span>
                                <p className="font-medium">{iot.humidity}%</p>
                              </div>
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">土壤湿度</span>
                                <p className="font-medium">{iot.soilMoisture}%</p>
                              </div>
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">土壤pH</span>
                                <p className="font-medium">{iot.soilPH}</p>
                              </div>
                              <div className="p-2 bg-white rounded">
                                <span className="text-muted-foreground">光照</span>
                                <p className="font-medium">{iot.light} lux</p>
                              </div>
                            </div>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 采收数据 */}
                  {archive.harvest.length > 0 && (
                    <div>
                      <h4 className="mb-3 flex items-center gap-2">
                        <Sprout className="w-4 h-4 text-success" />
                        采收数据
                      </h4>
                      {archive.harvest.map(harvest => (
                        <Card key={harvest.id} className="p-4 bg-success-muted">
                          <div className="grid grid-cols-4 gap-4">
                            <div className="p-3 bg-white rounded">
                              <p className="text-xs text-muted-foreground">总产量</p>
                              <p className="mt-1 text-lg font-medium text-success">
                                {harvest.yield} kg
                              </p>
                            </div>
                            <div className="p-3 bg-white rounded">
                              <p className="text-xs text-muted-foreground">单产</p>
                              <p className="mt-1 text-lg font-medium text-success">
                                {harvest.unitYield} kg/亩
                              </p>
                            </div>
                            <div className="p-3 bg-white rounded">
                              <p className="text-xs text-muted-foreground">品质等级</p>
                              <p className="mt-1 text-lg font-medium text-success">
                                {harvest.quality} - {harvest.grade}
                              </p>
                            </div>
                            <div className="p-3 bg-white rounded">
                              <p className="text-xs text-muted-foreground">含水率</p>
                              <p className="mt-1 text-lg font-medium text-success">
                                {harvest.moisture}%
                              </p>
                            </div>
                          </div>
                          <div className="mt-3 text-xs text-muted-foreground">
                            📅 {harvest.date} | 👤 验收人: {harvest.inspector} | 
                            🏢 去向: {harvest.destination}
                          </div>
                        </Card>
                      ))}
                    </div>
                  )}
                </Card>
              ))
            )}
          </Card>
        </TabsContent>

        {/* 追踪与溯源 */}
        <TabsContent value="trace" className="space-y-4">
          {/* 溯源说明 */}
          <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <GitBranch className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
              <div className="text-sm text-gray-800">
                <p className="mb-2 font-medium">全流程追踪溯源：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>完整时间线</strong>: 展示从计划→任务→操作→投入→监测→采收的全链路时间线</li>
                  <li>• <strong>正向追踪</strong>: 选择任意地块或批次，查看其完整的农事历史和生长过程</li>
                  <li>• <strong>反向溯源</strong>: 从产品出发，追溯种植过程、投入品使用、生长环境数据</li>
                  <li>• <strong>质量保障</strong>: 所有操作可追溯，投入品可查证，保障农产品质量安全</li>
                  <li>• <strong>二维码生成</strong>: 为每批产品生成溯源二维码，消费者扫码可查看完整种植档案</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 时间线展示 */}
          {filteredArchives.length === 0 ? (
            <Card className="p-12 text-center">
              <GitBranch className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500">暂无可追溯的档案数据</p>
            </Card>
          ) : (
            filteredArchives.map(archive => {
              const timeline = getTimelineData(archive);
              return (
                <Card key={archive.id} className="p-6">
                  <div className="mb-6">
                    <h3>{archive.fieldName} - {archive.crop} ({archive.variety})</h3>
                    <p className="text-sm text-muted-foreground">
                      批次: {archive.batchNo} | {archive.startDate} ~ {archive.endDate || '进行中'}
                    </p>
                  </div>

                  {/* 时间线 */}
                  <div className="relative">
                    <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-gray-200" />
                    <div className="space-y-6">
                      {timeline.map((event, index) => {
                        const Icon = event.icon;
                        return (
                          <div key={index} className="relative pl-20">
                            <div className={`absolute left-0 w-16 h-16 rounded-full bg-${event.color}-100 flex items-center justify-center border-4 border-white shadow-md`}>
                              <Icon className={`w-8 h-8 text-${event.color}-600`} />
                            </div>
                            <Card className="p-4">
                              <div className="flex items-start justify-between mb-2">
                                <div className="flex-1">
                                  <div className="flex items-center gap-2 mb-1">
                                    <Badge className={`bg-${event.color}-100 text-${event.color}-800`}>
                                      {event.type}
                                    </Badge>
                                    <span className="text-sm font-medium">{event.title}</span>
                                  </div>
                                  {event.type === '计划' && event.details?.activityList ? (
                                    <button
                                      onClick={() => {
                                        setSelectedPlan(event.details);
                                        setShowPlanActivitiesDialog(true);
                                      }}
                                      className="text-xs text-info hover:text-info/80 hover:underline cursor-pointer"
                                    >
                                      {event.description} →
                                    </button>
                                  ) : (
                                    <p className="text-xs text-muted-foreground">
                                      {event.description}
                                    </p>
                                  )}
                                </div>
                                <div className="text-xs text-muted-foreground text-right">
                                  <div>{event.date}</div>
                                  <div>{event.time}</div>
                                </div>
                              </div>
                              {event.details && event.type === '操作' && (
                                <div className="mt-3 p-3 bg-muted rounded text-xs">
                                  <div className="grid grid-cols-3 gap-2">
                                    <div>
                                      <span className="text-muted-foreground">地点: </span>
                                      <span>{event.details.location.address}</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">时长: </span>
                                      <span>{event.details.duration}小时</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">天气: </span>
                                      <span>{event.details.weather}</span>
                                    </div>
                                  </div>
                                  {event.details.notes && (
                                    <div className="mt-2">
                                      <span className="text-muted-foreground">备注: </span>
                                      <span>{event.details.notes}</span>
                                    </div>
                                  )}
                                </div>
                              )}
                              {event.details && event.type === '投入' && (
                                <div className="mt-3 p-3 bg-muted rounded text-xs">
                                  <div className="grid grid-cols-4 gap-2">
                                    <div>
                                      <span className="text-muted-foreground">品牌: </span>
                                      <span>{event.details.brand}</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">批号: </span>
                                      <span>{event.details.batchNo}</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">供应商: </span>
                                      <span>{event.details.supplier}</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">成本: </span>
                                      <span>¥{event.details.cost}</span>
                                    </div>
                                  </div>
                                </div>
                              )}
                              {event.details && event.type === 'IoT' && (
                                <div className="mt-3 p-3 bg-muted rounded text-xs">
                                  <div className="grid grid-cols-5 gap-2">
                                    <div>
                                      <span className="text-muted-foreground">温度: </span>
                                      <span>{event.details.temperature}°C</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">湿度: </span>
                                      <span>{event.details.humidity}%</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">土壤湿度: </span>
                                      <span>{event.details.soilMoisture}%</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">pH: </span>
                                      <span>{event.details.soilPH}</span>
                                    </div>
                                    <div>
                                      <span className="text-muted-foreground">光照: </span>
                                      <span>{event.details.light} lux</span>
                                    </div>
                                  </div>
                                </div>
                              )}
                            </Card>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </Card>
              );
            })
          )}
        </TabsContent>
      </Tabs>

      {/* 生成档案对话框 */}
      <Dialog open={showGenerateDialog} onOpenChange={setShowGenerateDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>智能生成档案</DialogTitle>
            <DialogDescription>
              系统将自动关联所有相关数据，生成完整的农事活动档案
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-2 block">选择地块</label>
              <Select value={generateFieldId} onValueChange={setGenerateFieldId}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择地块" />
                </SelectTrigger>
                <SelectContent>
                  {mockFields.map(field => (
                    <SelectItem key={field.id} value={field.id}>
                      {field.name} ({field.crop} - {field.area}亩)
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Card className="p-4 bg-info-muted border-info">
              <div className="text-sm text-muted-foreground">
                <p className="font-medium mb-2">将自动归集以下数据：</p>
                <ul className="text-xs space-y-1">
                  <li>✓ 农事计划和活动安排</li>
                  <li>✓ 任务分配和执行记录</li>
                  <li>✓ 农事操作详细记录</li>
                  <li>✓ 农资投入品使用记录</li>
                  <li>✓ 物联网传感器监测数据</li>
                  <li>✓ 采收和产量质量数据</li>
                </ul>
              </div>
            </Card>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowGenerateDialog(false)} disabled={generating}>
              取消
            </Button>
            <Button 
              onClick={handleGenerateArchive}
              className="bg-success hover:bg-success/90"
              disabled={generating}
            >
              {generating ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  生成中...
                </>
              ) : (
                <>
                  <Sparkles className="w-4 h-4 mr-2" />
                  开始生成
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 计划活动详情对话框 */}
      <Dialog open={showPlanActivitiesDialog} onOpenChange={setShowPlanActivitiesDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Calendar className="w-5 h-5 text-info" />
              {selectedPlan?.name}
            </DialogTitle>
            <DialogDescription>
              计划时间: {selectedPlan?.startDate} ~ {selectedPlan?.endDate} | 
              共 {selectedPlan?.activities} 项农事活动 | 
              状态: {selectedPlan?.status}
            </DialogDescription>
          </DialogHeader>
          {selectedPlan?.activityList && (
            <div className="space-y-4">
              {/* 统计概览 */}
              <div className="grid grid-cols-4 gap-4">
                <Card className="p-4 bg-info-muted">
                  <p className="text-xs text-muted-foreground">总活动数</p>
                  <p className="mt-1 text-2xl text-info">{selectedPlan.activityList.length}</p>
                </Card>
                <Card className="p-4 bg-success-muted">
                  <p className="text-xs text-muted-foreground">整地施肥</p>
                  <p className="mt-1 text-2xl text-success">
                    {selectedPlan.activityList.filter(a => ['整地', '施肥'].includes(a.type)).length}
                  </p>
                </Card>
                <Card className="p-4 bg-accent-muted">
                  <p className="text-xs text-muted-foreground">灌溉植保</p>
                  <p className="mt-1 text-2xl text-accent">
                    {selectedPlan.activityList.filter(a => ['灌溉', '植保', '除草'].includes(a.type)).length}
                  </p>
                </Card>
                <Card className="p-4 bg-warning-muted">
                  <p className="text-xs text-muted-foreground">收获仓储</p>
                  <p className="mt-1 text-2xl text-warning">
                    {selectedPlan.activityList.filter(a => ['收获', '仓储', '检测'].includes(a.type)).length}
                  </p>
                </Card>
              </div>

              {/* 活动列表 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <ListTree className="w-4 h-4 text-success" />
                  详细活动安排
                </h4>
                <div className="space-y-2">
                  {selectedPlan.activityList.map((activity, index) => (
                    <Card key={activity.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-start gap-4">
                        <div className="flex-shrink-0 w-12 h-12 rounded-full bg-info-muted flex items-center justify-center">
                          <span className="text-info font-medium">{index + 1}</span>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-start justify-between mb-2">
                            <div>
                              <h5 className="flex items-center gap-2">
                                {activity.name}
                                <Badge variant="outline" className="ml-2">{activity.type}</Badge>
                              </h5>
                              <p className="text-sm text-muted-foreground mt-1">
                                {activity.description}
                              </p>
                            </div>
                            <div className="text-right text-xs text-muted-foreground ml-4">
                              <div className="flex items-center gap-1 mb-1">
                                <Calendar className="w-3 h-3" />
                                {activity.period}
                              </div>
                              <div className="flex items-center gap-1">
                                <Clock className="w-3 h-3" />
                                {activity.duration}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPlanActivitiesDialog(false)}>
              关闭
            </Button>
            <Button onClick={() => {
              toast.success('计划活动列表已导出');
              setShowPlanActivitiesDialog(false);
            }}>
              <Download className="w-4 h-4 mr-2" />
              导出计划
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看档案对话框 */}
      <Dialog open={showArchiveDialog} onOpenChange={setShowArchiveDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedArchive?.fieldName} - {selectedArchive?.crop}
            </DialogTitle>
            <DialogDescription>
              批次号: {selectedArchive?.batchNo} | 
              {selectedArchive?.startDate} ~ {selectedArchive?.endDate || '进行中'}
            </DialogDescription>
          </DialogHeader>
          {selectedArchive && (
            <div className="space-y-4">
              <div className="grid grid-cols-7 gap-3">
                <div className="p-3 bg-blue-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">计划</p>
                  <p className="mt-1 text-lg font-medium text-blue-800">{selectedArchive.plans.length}</p>
                </div>
                <div className="p-3 bg-purple-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">任务</p>
                  <p className="mt-1 text-lg font-medium text-purple-800">{selectedArchive.tasks.length}</p>
                </div>
                <div className="p-3 bg-green-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">操作</p>
                  <p className="mt-1 text-lg font-medium text-green-800">{selectedArchive.operations.length}</p>
                </div>
                <div className="p-3 bg-orange-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">投入</p>
                  <p className="mt-1 text-lg font-medium text-orange-800">{selectedArchive.inputs.length}</p>
                </div>
                <div className="p-3 bg-red-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">IoT</p>
                  <p className="mt-1 text-lg font-medium text-red-800">{selectedArchive.iot.length}</p>
                </div>
                <div className="p-3 bg-yellow-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">采收</p>
                  <p className="mt-1 text-lg font-medium text-yellow-800">{selectedArchive.harvest.length}</p>
                </div>
                <div className="p-3 bg-gray-50 rounded-lg text-center">
                  <p className="text-xs text-muted-foreground">完整度</p>
                  <p className="mt-1 text-lg font-medium text-gray-800">{selectedArchive.completeness}%</p>
                </div>
              </div>

              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Clock className="w-4 h-4 text-green-600" />
                  完整时间线 ({getTimelineData(selectedArchive).length} 个事件)
                </h4>
                <div className="max-h-96 overflow-y-auto">
                  {getTimelineData(selectedArchive).map((event, index) => {
                    const Icon = event.icon;
                    return (
                      <div key={index} className="flex gap-3 mb-3">
                        <div className={`w-10 h-10 rounded-full bg-${event.color}-100 flex items-center justify-center flex-shrink-0`}>
                          <Icon className={`w-5 h-5 text-${event.color}-600`} />
                        </div>
                        <Card className="flex-1 p-3">
                          <div className="flex items-start justify-between">
                            <div>
                              <div className="flex items-center gap-2 mb-1">
                                <Badge className={`bg-${event.color}-100 text-${event.color}-800 text-xs`}>
                                  {event.type}
                                </Badge>
                                <span className="text-sm font-medium">{event.title}</span>
                              </div>
                              <p className="text-xs text-muted-foreground">{event.description}</p>
                            </div>
                            <div className="text-xs text-muted-foreground text-right">
                              <div>{event.date}</div>
                              <div>{event.time}</div>
                            </div>
                          </div>
                        </Card>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowArchiveDialog(false)}>
              关闭
            </Button>
            <Button onClick={() => selectedArchive && handleExportArchive(selectedArchive)}>
              <Download className="w-4 h-4 mr-2" />
              导出档案
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
