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 { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Progress } from '../ui/progress';
import { Checkbox } from '../ui/checkbox';
import { Switch } from '../ui/switch';
import { materialStorage } from '../../lib/materialStorage';
import type { Material } from '../../types/machinery';
import { operationTypesData, OperationType } from '../../lib/operationTypes';
import {
  Calendar,
  Plus,
  Edit,
  Trash2,
  FileText,
  Users,
  MapPin,
  Clock,
  CheckCircle2,
  AlertTriangle,
  PlayCircle,
  Circle,
  Send,
  Bell,
  Mail,
  MessageSquare,
  Phone,
  Filter,
  Search,
  Download,
  BarChart3,
  PieChart,
  TrendingUp,
  ClipboardCheck,
  AlertCircle,
  Package,
  Shield,
  Eye,
  User,
  List,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart as RePieChart,
  Pie,
  Cell,
  LineChart,
  Line,
} from 'recharts';

interface OperationTaskProps {
  activePath?: string;
}

type TaskType = OperationType; // 使用农事执行的农事类型
type TaskStatus = '未开始' | '进行中' | '待验收' | '已完成';
type NotificationChannel = '消息中心' | '短信' | '邮件' | 'APP推送';
type PlanStatus = '草稿' | '已发布' | '进行中' | '已完成';

// 农事计划接口
interface OperationPlan {
  id: string;
  name: string;
  crop: string;
  variety: string;
  plannedArea: number;
  startDate: string;
  endDate: string;
  status: PlanStatus;
  activities: Array<{
    id: string;
    name: string;
    type: TaskType;
    startDate: string;
    endDate: string;
    description: string;
  }>;
}

interface Task {
  id: string;
  name: string;
  type: TaskType;
  fieldId: string;
  fieldName: string;
  fieldLocation: string;
  crop: string;
  plannedStartDate: string;
  plannedEndDate: string;
  actualStartDate?: string;
  actualEndDate?: string;
  assignedTo: string;
  teamName: string;
  status: TaskStatus;
  description: string;
  requirements: string[];
  materials: { name: string; amount: number; unit: string }[]; // 计划农资
  actualMaterials?: { name: string; brand: string; amount: number; unit: string; batchNo: string }[]; // 实际使用农资
  safetyNotes: string[];
  estimatedHours: number;
  actualHours?: number;
  progress: number;
  createdBy: string;
  createdAt: string;
  source: '计划生成' | '手动创建';
  planId?: string;
  acceptanceRating?: '优秀' | '良好' | '合格' | '不合格'; // 验收评价
  submittedBy?: string; // 提交验收的人
  submittedAt?: string; // 提交验收时间
  images?: string[]; // 现场图片
}

interface Notification {
  id: string;
  taskId: string;
  taskName: string;
  type: '任务分配' | '任务变更' | '任务提醒' | '验收通知';
  recipients: string[];
  channels: NotificationChannel[];
  content: string;
  link: string;
  sentAt: string;
  status: '已发送' | '发送失败';
}

export function OperationTask({ activePath }: OperationTaskProps) {
  const [activeTab, setActiveTab] = useState('management');
  const [showTaskDialog, setShowTaskDialog] = useState(false);
  const [showNotificationDialog, setShowNotificationDialog] = useState(false);
  const [showTaskDetailDialog, setShowTaskDetailDialog] = useState(false);
  const [showSubmitDialog, setShowSubmitDialog] = useState(false); // 提交验收对话框
  const [showAcceptanceDialog, setShowAcceptanceDialog] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterType, setFilterType] = useState<string>('all');
  
  // 提交验收数据
  const [submitData, setSubmitData] = useState({
    actualMaterials: [] as { name: string; brand: string; amount: number; unit: string; batchNo: string }[],
    submitNotes: '',
    images: [] as string[], // 现场图片
  });
  
  const [acceptanceData, setAcceptanceData] = useState({
    rating: '优秀' as '优秀' | '良好' | '合格' | '不合格',
    qualityScore: 95,
    efficiencyScore: 90,
    standardScore: 92,
    comment: '',
    inspector: '',
    issues: '',
  });
  
  // 通知渠道启用状态
  const [notificationChannels, setNotificationChannels] = useState({
    messageCenter: true,
    sms: true,
    email: true,
    appPush: true,
  });
  
  // 历史与统计 - 多维度筛选状态
  const [statisticsFilters, setStatisticsFilters] = useState({
    fieldId: '',
    crop: '',
    assignedTo: '',
    startDate: '',
    endDate: '',
    taskType: '',
  });
  
  // 显示报表对话框
  const [showReportDialog, setShowReportDialog] = useState(false);
  const [reportType, setReportType] = useState<'cost' | 'performance' | 'traceability' | null>(null);
  
  // 任务表单状态
  const [taskForm, setTaskForm] = useState({
    name: '',
    type: '播种' as TaskType,
    fieldId: '',
    fieldName: '',
    assignedTo: '',
    teamName: '',
    plannedStartDate: '',
    plannedEndDate: '',
    description: '',
    requirements: '',
    safetyNotes: '',
    estimatedHours: 0,
    relatedPlanId: '', // 关联的农事计划ID（非必填）
  });
  
  // 农资列表状态
  const [materials, setMaterials] = useState<{ name: string; amount: number; unit: string; materialId?: string; currentStock?: number }[]>([]);
  
  // 农资库存数据
  const [availableMaterials, setAvailableMaterials] = useState<Material[]>([]);
  const [showMaterialSelector, setShowMaterialSelector] = useState(false);
  const [selectingMaterialIndex, setSelectingMaterialIndex] = useState<number | null>(null);
  
  // 批量任务创建相关
  const [selectedPlan, setSelectedPlan] = useState<OperationPlan | null>(null);
  const [selectedActivities, setSelectedActivities] = useState<string[]>([]);
  const [showBatchTaskCreation, setShowBatchTaskCreation] = useState(false);
  const [showEditTaskDialog, setShowEditTaskDialog] = useState(false);
  const [batchTaskSettings, setBatchTaskSettings] = useState<{
    fieldId: string;
    fieldName: string;
    assignedTo: string;
    teamName: string;
  }>({
    fieldId: '',
    fieldName: '',
    assignedTo: '',
    teamName: '',
  });

  // 农事计划数据（可关联）
  const [operationPlans] = useState<OperationPlan[]>([
    {
      id: 'plan-1',
      name: '2024年春季水稻种植计划',
      crop: '水稻',
      variety: '优质稻1号',
      plannedArea: 200,
      startDate: '2024-03-01',
      endDate: '2024-06-30',
      status: '进行中',
      activities: [
        { id: 'act-1', name: '春季播种', type: '播种', startDate: '2024-03-01', endDate: '2024-03-15', description: '进行水稻种子浸种催芽并播种' },
        { id: 'act-2', name: '基肥施用', type: '施肥', startDate: '2024-03-10', endDate: '2024-03-20', description: '施用有机肥和复合肥作为基肥' },
        { id: 'act-3', name: '灌溉管理', type: '灌溉', startDate: '2024-03-15', endDate: '2024-06-15', description: '根据生长期进行科学灌溉' },
      ],
    },
    {
      id: 'plan-7',
      name: '2024年秋季花生种植计划',
      crop: '花生',
      variety: '鲁花11号',
      plannedArea: 95,
      startDate: '2024-07-10',
      endDate: '2024-10-31',
      status: '已发布',
      activities: [
        { id: 'act-30', name: '整地施基肥', type: '施肥', startDate: '2024-07-10', endDate: '2024-07-20', description: '整地并施用有机肥和复合肥' },
        { id: 'act-31', name: '播种', type: '播种', startDate: '2024-07-25', endDate: '2024-08-05', description: '花生播种作业' },
        { id: 'act-32', name: '苗期管理', type: '灌溉', startDate: '2024-08-10', endDate: '2024-08-25', description: '苗期灌溉及田间管理' },
      ],
    },
    {
      id: 'plan-8',
      name: '2024年冬季油菜种植计划',
      crop: '油菜',
      variety: '中油杂19',
      plannedArea: 130,
      startDate: '2024-09-20',
      endDate: '2024-12-31',
      status: '已发布',
      activities: [
        { id: 'act-36', name: '整地作畦', type: '施肥', startDate: '2024-09-20', endDate: '2024-09-30', description: '整地施底肥并作畦' },
        { id: 'act-37', name: '播种', type: '播种', startDate: '2024-10-05', endDate: '2024-10-15', description: '油菜直播或移栽' },
        { id: 'act-38', name: '间苗定苗', type: '除草', startDate: '2024-10-20', endDate: '2024-10-30', description: '间苗定苗及除草' },
      ],
    },
    {
      id: 'plan-9',
      name: '2024年高粱种植计划',
      crop: '高粱',
      variety: '辽杂19号',
      plannedArea: 75,
      startDate: '2024-05-15',
      endDate: '2024-09-15',
      status: '进行中',
      activities: [
        { id: 'act-42', name: '播前整地', type: '施肥', startDate: '2024-05-15', endDate: '2024-05-25', description: '深耕整地施基肥' },
        { id: 'act-43', name: '播种', type: '播种', startDate: '2024-05-28', endDate: '2024-06-05', description: '高粱种子播种' },
        { id: 'act-44', name: '间苗定苗', type: '除草', startDate: '2024-06-10', endDate: '2024-06-20', description: '间苗定苗及除草' },
      ],
    },
  ]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/management')) {
        setActiveTab('management');
      } else if (activePath.includes('/assignment')) {
        setActiveTab('assignment');
      } else if (activePath.includes('/monitoring')) {
        setActiveTab('monitoring');
      } else if (activePath.includes('/statistics')) {
        setActiveTab('statistics');
      }
    }
  }, [activePath]);
  
  // 加载农资数据
  useEffect(() => {
    const materials = materialStorage.getAvailableMaterials();
    setAvailableMaterials(materials);
  }, []);

  // 模拟任务数据
  const [tasks, setTasks] = useState<Task[]>([
    {
      id: 'task-1',
      name: '东区1号地水稻播种',
      type: '播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      fieldLocation: '东经120.15°, 北纬30.25°',
      crop: '水稻',
      plannedStartDate: '2024-03-01',
      plannedEndDate: '2024-03-03',
      actualStartDate: '2024-03-01',
      actualEndDate: '2024-03-02',
      assignedTo: '张三',
      teamName: '第一作业组',
      status: '已完成',
      description: '进行水稻种子浸种催芽并播种',
      requirements: [
        '种子需提前浸种12-24小时',
        '播种深度控制在2-3cm',
        '行距保持30cm',
        '播种后及时覆土并轻压',
      ],
      materials: [
        { name: '水稻种子', amount: 177, unit: 'kg' },
        { name: '浸种剂', amount: 0.5, unit: 'L' },
      ],
      safetyNotes: [
        '作业时佩戴手套和口罩',
        '注意防止滑倒',
        '避免在雨天作业',
      ],
      estimatedHours: 25,
      actualHours: 22,
      progress: 100,
      createdBy: '系统',
      createdAt: '2024-02-25',
      source: '计划生成',
      planId: 'plan-1',
      acceptanceRating: '优秀', // 验收评价
      actualMaterials: [
        { name: '水稻种子', brand: '隆平高科', amount: 180, unit: 'kg', batchNo: 'LP20240225' },
        { name: '浸种剂', brand: '金正大', amount: 0.5, unit: 'L', batchNo: 'JZD20240220' },
      ],
      submittedBy: '张三',
      submittedAt: '2024-03-02 16:30',
    },
    {
      id: 'task-2',
      name: '西区2号地施基肥',
      type: '施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      fieldLocation: '东经120.12°, 北纬30.28°',
      crop: '水稻',
      plannedStartDate: '2024-03-10',
      plannedEndDate: '2024-03-12',
      actualStartDate: '2024-03-10',
      assignedTo: '李四',
      teamName: '第二作业组',
      status: '进行中',
      description: '施用有机肥和复合肥作为基肥',
      requirements: [
        '有机肥需充分腐熟',
        '均匀撒施，避免堆积',
        '施肥后及时翻耕入土',
        '注意肥料用量控制',
      ],
      materials: [
        { name: '有机肥', amount: 18080, unit: 'kg' },
        { name: '复合肥', amount: 1808, unit: 'kg' },
      ],
      safetyNotes: [
        '穿戴防护服和手套',
        '避免直接接触肥料',
        '作业后及时清洗',
      ],
      estimatedHours: 16,
      actualHours: 8,
      progress: 50,
      createdBy: '系统',
      createdAt: '2024-03-05',
      source: '计划生成',
      planId: 'plan-1',
    },
    {
      id: 'task-3',
      name: '南区3号地病虫害防治',
      type: '病虫害防治',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      fieldLocation: '东经120.18°, 北纬30.22°',
      crop: '玉米',
      plannedStartDate: '2024-03-15',
      plannedEndDate: '2024-03-16',
      assignedTo: '王五',
      teamName: '第三作业组',
      status: '待验收',
      description: '喷洒农药防治玉米常见病虫害',
      requirements: [
        '选择晴朗无风天气进行',
        '按照说明书配比农药',
        '均匀喷洒，不留死角',
        '做好喷洒记录',
      ],
      materials: [
        { name: '杀虫剂', amount: 2.4, unit: 'L' },
        { name: '杀菌剂', amount: 1.8, unit: 'L' },
      ],
      safetyNotes: [
        '必须穿戴全套防护装备',
        '顺风向喷洒，避免吸入',
        '作业后彻底清洗',
        '农药容器妥善处理',
      ],
      estimatedHours: 12,
      actualHours: 11,
      progress: 100,
      createdBy: '李四',
      createdAt: '2024-03-10',
      source: '手动创建',
      actualMaterials: [
        { name: '杀虫剂', brand: '先正达', amount: 2.5, unit: 'L', batchNo: 'XZD20240312' },
        { name: '杀菌剂', brand: '拜耳', amount: 1.8, unit: 'L', batchNo: 'BE20240310' },
      ],
      submittedBy: '王五',
      submittedAt: '2024-03-16 15:20',
    },
    {
      id: 'task-4',
      name: '北区4号地灌溉',
      type: '灌溉',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      fieldLocation: '东经120.20°, 北纬30.30°',
      crop: '蔬菜',
      plannedStartDate: '2024-03-20',
      plannedEndDate: '2024-03-20',
      assignedTo: '赵六',
      teamName: '第一作业组',
      status: '未开始',
      description: '进行滴灌系统灌溉',
      requirements: [
        '检查滴灌系统是否正常',
        '控制灌溉水量',
        '确保均匀灌溉',
        '记录灌溉时间和水量',
      ],
      materials: [],
      safetyNotes: [
        '注意用电安全',
        '避免在雷雨天作业',
      ],
      estimatedHours: 6,
      progress: 0,
      createdBy: '张三',
      createdAt: '2024-03-15',
      source: '手动创建',
    },
  ]);

  // 模拟通知记录
  const [notifications, setNotifications] = useState<Notification[]>([
    {
      id: 'notif-1',
      taskId: 'task-1',
      taskName: '东区1号地水稻播种',
      type: '任务分配',
      recipients: ['张三'],
      channels: ['消息中心', '短信', 'APP推送'],
      content: '您有新的农事任务：东区1号地水稻播种。地块位置：东经120.15°, 北纬30.25°。计划开始时间：2024-03-01。请按要求完成任务。',
      link: '/operation/task/management?id=task-1',
      sentAt: '2024-02-25 10:00',
      status: '已发送',
    },
    {
      id: 'notif-2',
      taskId: 'task-2',
      taskName: '西区2号地施基肥',
      type: '任务提醒',
      recipients: ['李四'],
      channels: ['消息中心', '短信'],
      content: '任务提醒：西区2号地施基肥将于明天开始，请提前准备好有机肥18080kg、复合肥1808kg。地块位置：东经120.12°, 北纬30.28°。',
      link: '/operation/task/management?id=task-2',
      sentAt: '2024-03-09 18:00',
      status: '已发送',
    },
    {
      id: 'notif-3',
      taskId: 'task-3',
      taskName: '南区3号地病虫害防治',
      type: '验收通知',
      recipients: ['张三', '李四'],
      channels: ['消息中心', 'APP推送'],
      content: '任务已完成，请验收：南区3号地病虫害防治。完成人：王五。完成时间：2024-03-16。',
      link: '/operation/task/monitoring?id=task-3',
      sentAt: '2024-03-16 16:30',
      status: '已发送',
    },
  ]);

  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '未开始': return 'bg-muted text-muted-foreground';
      case '进行中': return 'bg-warning text-warning-foreground';
      case '待验收': return 'bg-info text-info-foreground';
      case '已完成': return 'bg-success text-success-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusIcon = (status: TaskStatus) => {
    switch (status) {
      case '未开始': return <Circle className="w-4 h-4" />;
      case '进行中': return <PlayCircle className="w-4 h-4" />;
      case '待验收': return <ClipboardCheck className="w-4 h-4" />;
      case '已完成': return <CheckCircle2 className="w-4 h-4" />;
      default: return <Circle className="w-4 h-4" />;
    }
  };

  const getTypeColor = (type: TaskType) => {
    switch (type) {
      case '播种': return 'bg-success-muted text-success-muted-foreground';
      case '施肥': return 'bg-warning-muted text-warning-muted-foreground';
      case '灌溉': return 'bg-info-muted text-info-muted-foreground';
      case '除草': return 'bg-muted text-muted-foreground';
      case '病虫害防治': return 'bg-error-muted text-error-muted-foreground';
      case '采收': return 'bg-warning-muted text-warning-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const handleCreateTask = () => {
    setSelectedTask(null);
    setTaskForm({
      name: '',
      type: '播种',
      fieldId: '',
      fieldName: '',
      assignedTo: '',
      teamName: '',
      plannedStartDate: '',
      plannedEndDate: '',
      description: '',
      requirements: '',
      safetyNotes: '',
      estimatedHours: 8,
      relatedPlanId: '',
    });
    setMaterials([]);
    setSelectedPlan(null);
    setSelectedActivities([]);
    setShowBatchTaskCreation(false);
    setBatchTaskSettings({
      fieldId: '',
      fieldName: '',
      assignedTo: '',
      teamName: '',
    });
    setShowTaskDialog(true);
  };

  // 处理关联计划选择 - 修改为批量任务创建
  const handlePlanSelect = (planId: string) => {
    setTaskForm(prev => ({ ...prev, relatedPlanId: planId }));
    
    if (planId === 'none') {
      // 清空关联
      setSelectedPlan(null);
      setSelectedActivities([]);
      setShowBatchTaskCreation(false);
      return;
    }
    
    const plan = operationPlans.find(p => p.id === planId);
    if (!plan) return;
    
    // 设置选中的计划
    setSelectedPlan(plan);
    // 默认全选所有活动
    setSelectedActivities(plan.activities.map(a => a.id));
    // 显示批量任务创建界面
    setShowBatchTaskCreation(true);
    
    toast.success(`已选择计划：${plan.name}，包含 ${plan.activities.length} 个农事活动`);
  };
  
  // 切换活动选中状态
  const handleToggleActivity = (activityId: string) => {
    setSelectedActivities(prev => 
      prev.includes(activityId)
        ? prev.filter(id => id !== activityId)
        : [...prev, activityId]
    );
  };
  
  // 批量创建任务
  const handleBatchCreateTasks = () => {
    if (!selectedPlan) return;
    
    if (selectedActivities.length === 0) {
      toast.error('请至少选择一个农事活动');
      return;
    }
    
    if (!batchTaskSettings.fieldId || !batchTaskSettings.assignedTo) {
      toast.error('请填写执行地块和负责人');
      return;
    }
    
    // 根据选中的活动批量创建任务
    const newTasks: Task[] = selectedActivities.map(activityId => {
      const activity = selectedPlan.activities.find(a => a.id === activityId);
      if (!activity) return null;
      
      // 根据任务类型预填充农资
      let materials: { name: string; amount: number; unit: string }[] = [];
      if (activity.type === '施肥') {
        materials = [
          { name: '有机肥', amount: Math.ceil(selectedPlan.plannedArea * 100), unit: 'kg' },
          { name: '复合肥', amount: Math.ceil(selectedPlan.plannedArea * 10), unit: 'kg' },
        ];
      } else if (activity.type === '播种') {
        materials = [
          { name: `${selectedPlan.crop}种子`, amount: 0, unit: 'kg' },
        ];
      } else if (activity.type === '病虫害防治') {
        materials = [
          { name: '杀虫剂', amount: 0, unit: 'L' },
          { name: '杀菌剂', amount: 0, unit: 'L' },
        ];
      }
      
      return {
        id: `task-${Date.now()}-${activityId}`,
        name: `${selectedPlan.crop} - ${activity.name}`,
        type: activity.type,
        fieldId: batchTaskSettings.fieldId,
        fieldName: batchTaskSettings.fieldName,
        fieldLocation: '东经120.15°, 北纬30.25°',
        crop: selectedPlan.crop,
        plannedStartDate: activity.startDate,
        plannedEndDate: activity.endDate,
        assignedTo: batchTaskSettings.assignedTo,
        teamName: batchTaskSettings.teamName,
        status: '未开始' as TaskStatus,
        description: `${activity.description}\n\n${selectedPlan.crop}（${selectedPlan.variety}）种植作业，计划面积${selectedPlan.plannedArea}亩`,
        requirements: [],
        materials: materials,
        safetyNotes: [],
        estimatedHours: Math.ceil(selectedPlan.plannedArea / 10),
        progress: 0,
        createdBy: '张三',
        createdAt: new Date().toISOString().split('T')[0],
        source: '计划生成' as const,
        planId: selectedPlan.id,
      };
    }).filter((task): task is Task => task !== null);
    
    // 添加到任务列表
    setTasks([...newTasks, ...tasks]);
    
    // 关闭对话框
    setShowTaskDialog(false);
    setShowBatchTaskCreation(false);
    setSelectedPlan(null);
    setSelectedActivities([]);
    setBatchTaskSettings({
      fieldId: '',
      fieldName: '',
      assignedTo: '',
      teamName: '',
    });
    
    toast.success(`成功创建 ${newTasks.length} 个任务`);
  };

  const handleEditTask = (task: Task) => {
    setSelectedTask(task);
    setTaskForm({
      name: task.name,
      type: task.type,
      fieldId: task.fieldId,
      fieldName: task.fieldName,
      assignedTo: task.assignedTo,
      teamName: task.teamName,
      plannedStartDate: task.plannedStartDate,
      plannedEndDate: task.plannedEndDate,
      description: task.description,
      requirements: task.requirements.join('\n'),
      safetyNotes: task.safetyNotes.join('\n'),
      estimatedHours: task.estimatedHours,
      relatedPlanId: task.planId || '',
    });
    setMaterials([...task.materials]);
    setShowEditTaskDialog(true);
  };
  
  const handleUpdateTask = () => {
    if (!selectedTask) return;
    
    if (!taskForm.name || !taskForm.fieldId || !taskForm.assignedTo || !taskForm.plannedStartDate) {
      toast.error('请填写所有必填项');
      return;
    }
    
    // 获取作物信息
    let cropInfo = selectedTask.crop;
    if (taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none') {
      const relatedPlan = operationPlans.find(p => p.id === taskForm.relatedPlanId);
      if (relatedPlan) {
        cropInfo = relatedPlan.crop;
      }
    }
    
    const updatedTask: Task = {
      ...selectedTask,
      name: taskForm.name,
      type: taskForm.type,
      fieldId: taskForm.fieldId,
      fieldName: taskForm.fieldName,
      crop: cropInfo,
      plannedStartDate: taskForm.plannedStartDate,
      plannedEndDate: taskForm.plannedEndDate,
      assignedTo: taskForm.assignedTo,
      teamName: taskForm.teamName,
      description: taskForm.description,
      requirements: taskForm.requirements.split('\n').filter(r => r.trim()),
      materials: materials.filter(m => m.name && m.amount > 0),
      safetyNotes: taskForm.safetyNotes.split('\n').filter(s => s.trim()),
      estimatedHours: taskForm.estimatedHours,
      planId: taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none' ? taskForm.relatedPlanId : undefined,
      source: taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none' ? '计划生成' : '手动创建',
    };
    
    setTasks(tasks.map(t => t.id === selectedTask.id ? updatedTask : t));
    toast.success('任务已更新');
    setShowEditTaskDialog(false);
    setSelectedTask(null);
  };
  
  const handleAddMaterial = () => {
    setMaterials([...materials, { name: '', amount: 0, unit: 'kg' }]);
  };
  
  // 打开农资选择器
  const handleSelectFromInventory = (index: number) => {
    setSelectingMaterialIndex(index);
    setShowMaterialSelector(true);
  };
  
  // 从农资库选择农资
  const handleMaterialSelect = (material: Material) => {
    if (selectingMaterialIndex !== null) {
      const updated = [...materials];
      updated[selectingMaterialIndex] = {
        ...updated[selectingMaterialIndex],
        name: material.name,
        unit: material.unit,
        materialId: material.id,
        currentStock: material.currentStock,
      };
      setMaterials(updated);
      setShowMaterialSelector(false);
      setSelectingMaterialIndex(null);
      toast.success(`已选择农资：${material.name}`);
    }
  };
  
  const handleUpdateMaterial = (index: number, field: string, value: any) => {
    const updated = [...materials];
    updated[index] = { ...updated[index], [field]: value };
    setMaterials(updated);
  };
  
  const handleRemoveMaterial = (index: number) => {
    setMaterials(materials.filter((_, i) => i !== index));
  };
  
  const handleSaveTask = () => {
    if (!taskForm.name || !taskForm.fieldId || !taskForm.assignedTo || !taskForm.plannedStartDate) {
      toast.error('请填写所有必填项');
      return;
    }
    
    // 如果关联了计划，获取作物信息
    let cropInfo = '水稻'; // 默认值
    if (taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none') {
      const relatedPlan = operationPlans.find(p => p.id === taskForm.relatedPlanId);
      if (relatedPlan) {
        cropInfo = relatedPlan.crop;
      }
    }
    
    const newTask: Task = {
      id: selectedTask ? selectedTask.id : `task-${Date.now()}`,
      name: taskForm.name,
      type: taskForm.type,
      fieldId: taskForm.fieldId,
      fieldName: taskForm.fieldName,
      fieldLocation: '东经120.15°, 北纬30.25°', // 实际应从地块数据获取
      crop: cropInfo,
      plannedStartDate: taskForm.plannedStartDate,
      plannedEndDate: taskForm.plannedEndDate,
      assignedTo: taskForm.assignedTo,
      teamName: taskForm.teamName,
      status: '未开始',
      description: taskForm.description,
      requirements: taskForm.requirements.split('\n').filter(r => r.trim()),
      materials: materials.filter(m => m.name && m.amount > 0),
      safetyNotes: taskForm.safetyNotes.split('\n').filter(s => s.trim()),
      estimatedHours: taskForm.estimatedHours,
      progress: 0,
      createdBy: '张三', // 实际应从当前用户获取
      createdAt: new Date().toISOString().split('T')[0],
      source: taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none' ? '计划生成' : '手动创建',
      planId: taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none' ? taskForm.relatedPlanId : undefined,
    };
    
    if (selectedTask) {
      setTasks(tasks.map(t => t.id === selectedTask.id ? newTask : t));
      toast.success('任务已更新');
    } else {
      setTasks([newTask, ...tasks]);
      toast.success('任务创建成功');
    }
    
    setShowTaskDialog(false);
  };

  const handleDeleteTask = (taskId: string) => {
    setTasks(tasks.filter(t => t.id !== taskId));
    toast.success('任务已删除');
  };

  const handleUpdateStatus = (taskId: string, newStatus: TaskStatus) => {
    setTasks(tasks.map(t => 
      t.id === taskId ? { ...t, status: newStatus } : t
    ));
    toast.success(`任务状态已更新为：${newStatus}`);
    
    // 发送通知
    if (newStatus === '待验收') {
      sendNotification(taskId, '验收通知');
    }
  };

  // 打开提交验收对话框
  const handleOpenSubmitDialog = (task: Task) => {
    setSelectedTask(task);
    // 初始化实际农资数据，基于计划农资
    const initialMaterials = task.materials.map(m => ({
      name: m.name,
      brand: '',
      amount: m.amount,
      unit: m.unit,
      batchNo: '',
    }));
    setSubmitData({
      actualMaterials: initialMaterials,
      submitNotes: '',
      images: [],
    });
    setShowSubmitDialog(true);
  };

  // 提交验收
  const handleSubmitAcceptance = () => {
    if (!selectedTask) return;

    // 更新任务状态为待验收，保存实际农资信息和现场图片
    setTasks(tasks.map(t => 
      t.id === selectedTask.id 
        ? { 
            ...t, 
            status: '待验收',
            actualMaterials: submitData.actualMaterials,
            images: submitData.images,
            submittedBy: '当前用户', // 实际应用中从登录信息获取
            submittedAt: new Date().toLocaleString('zh-CN'),
          } 
        : t
    ));
    
    toast.success('已提交验收申请，数据已同步至农事操作记录');
    setShowSubmitDialog(false);
    
    // 发送通知
    if (selectedTask) {
      sendNotification(selectedTask.id, '验收通知');
    }
  };

  // 打开验收对话框
  const handleOpenAcceptanceDialog = (task: Task) => {
    setSelectedTask(task);
    setAcceptanceData({
      rating: '优秀',
      qualityScore: 95,
      efficiencyScore: 90,
      standardScore: 92,
      comment: '',
      inspector: '',
      issues: '',
    });
    setShowAcceptanceDialog(true);
  };

  // 提交验收评价
  const handleSubmitAcceptanceEvaluation = () => {
    if (!selectedTask) return;
    
    if (!acceptanceData.inspector) {
      toast.error('请输入验收人');
      return;
    }

    // 更新任务状态和验收评价
    setTasks(tasks.map(t => 
      t.id === selectedTask.id 
        ? { 
            ...t, 
            status: '已完成',
            acceptanceRating: acceptanceData.rating,
          } 
        : t
    ));
    
    // 提示验收完成并同步至农事操作记录
    toast.success(`任务验收完成（评价：${acceptanceData.rating}），已同步至农事操作记录并标记为审核完成`);
    setShowAcceptanceDialog(false);
    setSelectedTask(null);
  };

  const handleAssignTask = (taskId: string) => {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      setSelectedTask(task);
      setShowNotificationDialog(true);
    }
  };
  
  const handleViewTaskDetail = (task: Task) => {
    setSelectedTask(task);
    setShowTaskDetailDialog(true);
  };

  // 生成统计报表数据
  const generateCostReport = () => {
    const report = filteredArchivedTasks.map(task => ({
      taskName: task.name,
      fieldName: task.fieldName,
      executor: task.assignedTo,
      laborCost: (task.actualHours || task.estimatedHours) * 50, // 假设每小时50元
      materialCost: task.materials.reduce((sum, m) => {
        const unitPrice = m.unit === 'kg' ? 5 : m.unit === 'L' ? 10 : 20;
        return sum + m.amount * unitPrice;
      }, 0),
      totalCost: 0,
      workHours: task.actualHours || task.estimatedHours,
      completedDate: task.actualEndDate || task.plannedEndDate,
    }));
    report.forEach(r => r.totalCost = r.laborCost + r.materialCost);
    return report;
  };
  
  const generatePerformanceReport = () => {
    // 按任务返回，包含验收评价
    return filteredArchivedTasks.map(task => ({
      taskName: task.name,
      fieldName: task.fieldName,
      executor: task.assignedTo,
      tasksCompleted: 1,
      totalHours: task.actualHours || task.estimatedHours,
      completedDate: task.actualEndDate || task.plannedEndDate,
      acceptanceRating: task.acceptanceRating || '待评价',
    }));
  };
  
  const generateTraceabilityReport = () => {
    const traceByField: Record<string, Task[]> = {};
    
    filteredArchivedTasks.forEach(task => {
      if (!traceByField[task.fieldId]) {
        traceByField[task.fieldId] = [];
      }
      traceByField[task.fieldId].push(task);
    });
    
    return Object.entries(traceByField).map(([fieldId, tasks]) => ({
      fieldId,
      fieldName: tasks[0].fieldName,
      crop: tasks[0].crop,
      operations: tasks.sort((a, b) => 
        (a.actualEndDate || a.plannedEndDate).localeCompare(b.actualEndDate || b.plannedEndDate)
      ),
    }));
  };
  
  const handleGenerateReport = (type: 'cost' | 'performance' | 'traceability') => {
    setReportType(type);
    setShowReportDialog(true);
  };
  
  const handleDownloadReport = () => {
    let reportData: any[] = [];
    let fileName = '';
    
    if (reportType === 'cost') {
      reportData = generateCostReport();
      fileName = '成本核算报表';
    } else if (reportType === 'performance') {
      reportData = generatePerformanceReport();
      fileName = '绩效考评报表';
    } else if (reportType === 'traceability') {
      reportData = generateTraceabilityReport();
      fileName = '生产追溯报表';
    }
    
    toast.success(`${fileName}已生成，共 ${reportData.length} 条记录`);
    setShowReportDialog(false);
  };

  const handleToggleChannel = (channel: keyof typeof notificationChannels) => {
    setNotificationChannels(prev => ({
      ...prev,
      [channel]: !prev[channel],
    }));
    
    const channelNames = {
      messageCenter: '消息中心',
      sms: '短信通知',
      email: '邮件通知',
      appPush: 'APP推送',
    };
    
    const newStatus = !notificationChannels[channel];
    toast.success(`${channelNames[channel]}已${newStatus ? '启用' : '禁用'}`);
  };

  const sendNotification = (taskId: string, type: '任务分配' | '任务变更' | '任务提醒' | '验收通知') => {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;

    // 根据启用的渠道生成channels数组
    const enabledChannels: NotificationChannel[] = [];
    if (notificationChannels.messageCenter) enabledChannels.push('消息中心');
    if (notificationChannels.sms) enabledChannels.push('短信');
    if (notificationChannels.email) enabledChannels.push('邮件');
    if (notificationChannels.appPush) enabledChannels.push('APP推送');

    // 检查是否有启用的渠道
    if (enabledChannels.length === 0) {
      toast.error('请至少启用一个通知渠道');
      return;
    }

    const newNotification: Notification = {
      id: `notif-${Date.now()}`,
      taskId: task.id,
      taskName: task.name,
      type,
      recipients: [task.assignedTo],
      channels: enabledChannels,
      content: generateNotificationContent(task, type),
      link: `/operation/task/management?id=${task.id}`,
      sentAt: new Date().toLocaleString('zh-CN'),
      status: '已发送',
    };

    setNotifications([newNotification, ...notifications]);
    toast.success(`已通过 ${enabledChannels.join('、')} 向 ${task.assignedTo} 发送${type}通知`);
  };

  const generateNotificationContent = (task: Task, type: string) => {
    switch (type) {
      case '任务分配':
        return `您有新的农事任务：${task.name}。地块位置：${task.fieldLocation}。计划开始时间：${task.plannedStartDate}。请按要求完成任务。`;
      case '任务变更':
        return `任务变更通知：${task.name}的执行计划已调整，请查看最新任务详情。`;
      case '任务提醒':
        return `任务提醒：${task.name}将于明天开始，请提前做好准备。地块位置：${task.fieldLocation}。`;
      case '验收通知':
        return `任务已完成，请验收：${task.name}。完成人：${task.assignedTo}。`;
      default:
        return '';
    }
  };

  const filteredTasks = tasks.filter(t => {
    if (filterStatus !== 'all' && t.status !== filterStatus) return false;
    if (filterType !== 'all' && t.type !== filterType) return false;
    return true;
  });
  
  // 归档任务（已完成的任务）
  const archivedTasks = tasks.filter(t => t.status === '已完成');
  
  // 多维度筛选归档任务
  const filteredArchivedTasks = archivedTasks.filter(t => {
    if (statisticsFilters.fieldId && t.fieldId !== statisticsFilters.fieldId) return false;
    if (statisticsFilters.crop && t.crop !== statisticsFilters.crop) return false;
    if (statisticsFilters.assignedTo && t.assignedTo !== statisticsFilters.assignedTo) return false;
    if (statisticsFilters.taskType && t.type !== statisticsFilters.taskType) return false;
    if (statisticsFilters.startDate && t.actualEndDate && t.actualEndDate < statisticsFilters.startDate) return false;
    if (statisticsFilters.endDate && t.actualEndDate && t.actualEndDate > statisticsFilters.endDate) return false;
    return true;
  });

  // 统计数据
  const tasksByStatus = {
    '未开始': tasks.filter(t => t.status === '未开始').length,
    '进行中': tasks.filter(t => t.status === '进行中').length,
    '待验收': tasks.filter(t => t.status === '待验收').length,
    '已完成': tasks.filter(t => t.status === '已完成').length,
  };

  const tasksByType = [
    { name: '播种', value: tasks.filter(t => t.type === '播种').length },
    { name: '施肥', value: tasks.filter(t => t.type === '施肥').length },
    { name: '灌溉', value: tasks.filter(t => t.type === '灌溉').length },
    { name: '除草', value: tasks.filter(t => t.type === '除草').length },
    { name: '病虫害防治', value: tasks.filter(t => t.type === '病虫害防治').length },
    { name: '采收', value: tasks.filter(t => t.type === '采收').length },
  ];

  const completionTrend = [
    { date: '3/1', 完成任务: 2, 新增任务: 3 },
    { date: '3/5', 完成任务: 3, 新增任务: 2 },
    { date: '3/10', 完成任务: 1, 新增任务: 4 },
    { date: '3/15', 完成任务: 4, 新增任务: 2 },
    { date: '3/20', 完成任务: 2, 新增任务: 1 },
  ];

  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-green-800">农事任务</h2>
          <p className="text-muted-foreground">
            任务管理、分配派发、状态监控与历史统计
          </p>
        </div>
        <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateTask}>
          <Plus className="w-4 h-4 mr-2" />
          新建任务
        </Button>
      </div>

      {/* 筛选器 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <Filter className="w-4 h-4 text-muted-foreground" />
          <Select value={filterStatus} onValueChange={setFilterStatus}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="任务状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="未开始">未开始</SelectItem>
              <SelectItem value="进行中">进行中</SelectItem>
              <SelectItem value="待验收">待���收</SelectItem>
              <SelectItem value="已完成">已完成</SelectItem>
            </SelectContent>
          </Select>
          <Select value={filterType} onValueChange={setFilterType}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="任务类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="播种">播种</SelectItem>
              <SelectItem value="施肥">施肥</SelectItem>
              <SelectItem value="灌溉">灌溉</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" />
          </div>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="management">任务管理</TabsTrigger>
          <TabsTrigger value="assignment">任务分配与派发</TabsTrigger>
          <TabsTrigger value="monitoring">任务状态监控</TabsTrigger>
          <TabsTrigger value="statistics">历史与统计</TabsTrigger>
        </TabsList>

        {/* 任务管理 */}
        <TabsContent value="management" className="space-y-4">
          <div className="grid gap-4">
            {filteredTasks.map(task => (
              <Card key={task.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className={`p-2 rounded-lg ${getTypeColor(task.type)}`}>
                      <ClipboardCheck className="w-6 h-6" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h3>{task.name}</h3>
                        <Badge className={getStatusColor(task.status)}>
                          {getStatusIcon(task.status)}
                          <span className="ml-1">{task.status}</span>
                        </Badge>
                        <Badge variant="outline">{task.type}</Badge>
                        <Badge variant="outline" className="text-xs">
                          {task.source}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        任务ID: {task.id} | 创建人: {task.createdBy} | 创建时间: {task.createdAt}
                      </p>
                    </div>
                  </div>
                  {task.status !== '已完成' && (
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleEditTask(task)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeleteTask(task.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-4 gap-4 mb-4">
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">地块信息</p>
                    <p className="mt-1 font-medium flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      {task.fieldName}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      {task.fieldLocation}
                    </p>
                  </div>
                  <div className="p-3 bg-green-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">负责人/班组</p>
                    <p className="mt-1 font-medium flex items-center gap-1">
                      <Users className="w-3 h-3" />
                      {task.assignedTo} / {task.teamName}
                    </p>
                  </div>
                  <div className="p-3 bg-purple-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">计划时间</p>
                    <p className="mt-1 text-sm flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {task.plannedStartDate} ~ {task.plannedEndDate}
                    </p>
                  </div>
                  <div className="p-3 bg-orange-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">工时</p>
                    <p className="mt-1 font-medium">
                      {task.actualHours || 0} / {task.estimatedHours} 小时
                    </p>
                  </div>
                </div>

                <div className="mb-4">
                  <p className="text-sm text-muted-foreground mb-2">任务描述</p>
                  <p className="text-sm">{task.description}</p>
                </div>

                <div className="grid grid-cols-3 gap-4 mb-4">
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground mb-2">操作要求</p>
                    <ul className="space-y-1">
                      {task.requirements.map((req, i) => (
                        <li key={i} className="text-xs flex items-start gap-1">
                          <CheckCircle2 className="w-3 h-3 mt-0.5 flex-shrink-0 text-green-600" />
                          <span>{req}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground mb-2">所需农资</p>
                    {task.materials.length > 0 ? (
                      <ul className="space-y-1">
                        {task.materials.map((mat, i) => (
                          <li key={i} className="text-xs flex items-center justify-between">
                            <span className="flex items-center gap-1">
                              <Package className="w-3 h-3 text-blue-600" />
                              {mat.name}
                            </span>
                            <span className="font-medium">{mat.amount}{mat.unit}</span>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <p className="text-xs text-muted-foreground">无需农资</p>
                    )}
                  </div>
                  <div className="p-3 bg-red-50 rounded-lg">
                    <p className="text-xs text-red-900 mb-2 flex items-center gap-1">
                      <Shield className="w-3 h-3" />
                      安全注意事项
                    </p>
                    <ul className="space-y-1">
                      {task.safetyNotes.map((note, i) => (
                        <li key={i} className="text-xs flex items-start gap-1 text-red-800">
                          <AlertTriangle className="w-3 h-3 mt-0.5 flex-shrink-0" />
                          <span>{note}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                <div className="mb-4">
                  <div className="flex items-center justify-between text-sm mb-2">
                    <span className="text-muted-foreground">任务进度</span>
                    <span className="font-medium">{task.progress}%</span>
                  </div>
                  <Progress value={task.progress} className="h-2" />
                </div>

                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => handleViewTaskDetail(task)}>
                    <FileText className="w-4 h-4 mr-2" />
                    查看详情
                  </Button>
                  {task.status === '未开始' && (
                    <Button
                      size="sm"
                      className="bg-orange-600 hover:bg-orange-700"
                      onClick={() => handleUpdateStatus(task.id, '进行中')}
                    >
                      <PlayCircle className="w-4 h-4 mr-2" />
                      开始任务
                    </Button>
                  )}
                  {task.status === '进行中' && (
                    <Button
                      size="sm"
                      className="bg-blue-600 hover:bg-blue-700"
                      onClick={() => handleOpenSubmitDialog(task)}
                    >
                      <ClipboardCheck className="w-4 h-4 mr-2" />
                      提交验收
                    </Button>
                  )}
                  {task.status === '待验收' && (
                    <Button
                      size="sm"
                      className="bg-green-600 hover:bg-green-700"
                      onClick={() => handleOpenAcceptanceDialog(task)}
                    >
                      <CheckCircle2 className="w-4 h-4 mr-2" />
                      验收任务
                    </Button>
                  )}
                </div>
              </Card>
            ))}
          </div>

          {filteredTasks.length === 0 && (
            <Card className="p-12 text-center">
              <ClipboardCheck className="w-16 h-16 mx-auto text-gray-400 mb-4" />
              <p className="text-muted-foreground mb-4">暂无任务</p>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateTask}>
                <Plus className="w-4 h-4 mr-2" />
                新建任务
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 任务分配与派发 */}
        <TabsContent value="assignment" className="space-y-4">
          {/* 通知渠道配置 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Bell className="w-5 h-5 text-green-600" />
                消息通知渠道
              </h3>
              <p className="text-sm text-muted-foreground">
                配置任务分配和通知时使用的消息推送渠道
              </p>
            </div>
            <div className="grid grid-cols-2 gap-4">
              {/* 消息中心 */}
              <div className={`p-4 rounded-lg border-2 transition-all ${
                notificationChannels.messageCenter 
                  ? 'bg-blue-50 border-blue-200' 
                  : 'bg-gray-50 border-gray-200 opacity-60'
              }`}>
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <MessageSquare className={`w-5 h-5 ${
                      notificationChannels.messageCenter ? 'text-blue-600' : 'text-gray-400'
                    }`} />
                    <span className="font-medium">消息中心</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className={notificationChannels.messageCenter ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'}>
                      {notificationChannels.messageCenter ? '已启用' : '已禁用'}
                    </Badge>
                    <Switch
                      checked={notificationChannels.messageCenter}
                      onCheckedChange={() => handleToggleChannel('messageCenter')}
                    />
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">系统内消息推送，实时到达</p>
              </div>

              {/* 短信通知 */}
              <div className={`p-4 rounded-lg border-2 transition-all ${
                notificationChannels.sms 
                  ? 'bg-green-50 border-green-200' 
                  : 'bg-gray-50 border-gray-200 opacity-60'
              }`}>
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Phone className={`w-5 h-5 ${
                      notificationChannels.sms ? 'text-green-600' : 'text-gray-400'
                    }`} />
                    <span className="font-medium">短信通知</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className={notificationChannels.sms ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'}>
                      {notificationChannels.sms ? '已启用' : '已禁用'}
                    </Badge>
                    <Switch
                      checked={notificationChannels.sms}
                      onCheckedChange={() => handleToggleChannel('sms')}
                    />
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">手机短信推送，确保必达</p>
              </div>

              {/* 邮件通知 */}
              <div className={`p-4 rounded-lg border-2 transition-all ${
                notificationChannels.email 
                  ? 'bg-purple-50 border-purple-200' 
                  : 'bg-gray-50 border-gray-200 opacity-60'
              }`}>
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Mail className={`w-5 h-5 ${
                      notificationChannels.email ? 'text-purple-600' : 'text-gray-400'
                    }`} />
                    <span className="font-medium">邮件通知</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className={notificationChannels.email ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'}>
                      {notificationChannels.email ? '已启用' : '已禁用'}
                    </Badge>
                    <Switch
                      checked={notificationChannels.email}
                      onCheckedChange={() => handleToggleChannel('email')}
                    />
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">电子邮件推送，详细内容</p>
              </div>

              {/* APP推送 */}
              <div className={`p-4 rounded-lg border-2 transition-all ${
                notificationChannels.appPush 
                  ? 'bg-orange-50 border-orange-200' 
                  : 'bg-gray-50 border-gray-200 opacity-60'
              }`}>
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Bell className={`w-5 h-5 ${
                      notificationChannels.appPush ? 'text-orange-600' : 'text-gray-400'
                    }`} />
                    <span className="font-medium">APP推送</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className={notificationChannels.appPush ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'}>
                      {notificationChannels.appPush ? '已启用' : '已禁用'}
                    </Badge>
                    <Switch
                      checked={notificationChannels.appPush}
                      onCheckedChange={() => handleToggleChannel('appPush')}
                    />
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">移动APP推送，即时提醒</p>
              </div>
            </div>

            {/* 启用渠道统计 */}
            <div className="mt-4 p-3 bg-gray-50 rounded-lg flex items-center justify-between">
              <span className="text-sm text-muted-foreground">
                已启用渠道数量：
              </span>
              <Badge variant="outline" className="text-base">
                {Object.values(notificationChannels).filter(Boolean).length} / 4
              </Badge>
            </div>
          </Card>

          {/* 通知记录 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <List className="w-5 h-5 text-blue-600" />
              通知发送记录
            </h3>
            <div className="space-y-4">
              {notifications.map(notif => (
                <Card key={notif.id} className="p-4 border-l-4 border-l-green-500">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${
                        notif.type === '任务分配' ? 'bg-blue-100 text-blue-600' :
                        notif.type === '任务变更' ? 'bg-orange-100 text-orange-600' :
                        notif.type === '任务提醒' ? 'bg-purple-100 text-purple-600' :
                        'bg-green-100 text-green-600'
                      }`}>
                        <Bell className="w-5 h-5" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{notif.taskName}</h4>
                          <Badge variant="outline">{notif.type}</Badge>
                          <Badge className={notif.status === '已发送' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'}>
                            {notif.status}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          通知ID: {notif.id} | 发送时间: {notif.sentAt}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">接收人</p>
                      <div className="flex gap-2">
                        {notif.recipients.map((recipient, i) => (
                          <Badge key={i} variant="outline">
                            <User className="w-3 h-3 mr-1" />
                            {recipient}
                          </Badge>
                        ))}
                      </div>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">发送渠道</p>
                      <div className="flex gap-2">
                        {notif.channels.map((channel, i) => (
                          <Badge key={i} variant="outline" className="text-xs">
                            {channel}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </div>

                  <div className="p-3 bg-blue-50 rounded-lg mb-3">
                    <p className="text-xs text-blue-900 mb-1">通知内容</p>
                    <p className="text-sm text-blue-800">{notif.content}</p>
                  </div>

                  <div className="flex items-center gap-2">
                    <Button size="sm" variant="outline">
                      <Eye className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                    <Button size="sm" variant="outline">
                      <Send className="w-4 h-4 mr-2" />
                      重新发送
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 通知说明 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <Bell className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">智能消息通知机制：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>任务分配</strong>: 新任务分配时，自动向执行人发送通知</li>
                  <li>• <strong>任务变更</strong>: 任务信息调整时，实时通知相关人员</li>
                  <li>• <strong>任务提醒</strong>: 任务开始前1天自动提醒</li>
                  <li>• <strong>验收通知</strong>: 任务完成后，通知管理员验收</li>
                  <li>• 通知内容包含：任务名称、地块位置、时间要求、超链接等关键信息</li>
                  <li>• 支持消息中心、短信、邮件、APP推送多渠道同步发送</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 任务状态监控 */}
        <TabsContent value="monitoring" className="space-y-4">
          {/* 状态统计 */}
          <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-gray-600">{tasksByStatus['未开始']}</p>
                </div>
                <Circle className="w-12 h-12 text-gray-600 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-orange-600">{tasksByStatus['进行中']}</p>
                </div>
                <PlayCircle className="w-12 h-12 text-orange-600 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-blue-600">{tasksByStatus['待验收']}</p>
                </div>
                <ClipboardCheck className="w-12 h-12 text-blue-600 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-green-600">{tasksByStatus['已完成']}</p>
                </div>
                <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 任务看板 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Eye className="w-5 h-5 text-purple-600" />
              任务实时监控看板
            </h3>
            <div className="grid grid-cols-4 gap-4">
              {Object.entries({
                '未开始': tasks.filter(t => t.status === '未开始'),
                '进行中': tasks.filter(t => t.status === '进行中'),
                '待验收': tasks.filter(t => t.status === '待验收'),
                '已完成': tasks.filter(t => t.status === '已完成'),
              }).map(([status, statusTasks]) => (
                <div key={status} className="space-y-3">
                  <div className={`p-3 rounded-lg ${
                    status === '未开始' ? 'bg-gray-100' :
                    status === '进行中' ? 'bg-orange-100' :
                    status === '待验收' ? 'bg-blue-100' :
                    'bg-green-100'
                  }`}>
                    <h4 className="flex items-center gap-2">
                      {getStatusIcon(status as TaskStatus)}
                      {status}
                      <Badge variant="outline" className="ml-auto">
                        {statusTasks.length}
                      </Badge>
                    </h4>
                  </div>
                  <div className="space-y-2">
                    {statusTasks.map(task => (
                      <Card key={task.id} className="p-3 hover:shadow-md transition-shadow">
                        <div className="flex items-start justify-between mb-2">
                          <h4 className="text-sm">{task.name}</h4>
                          <Badge className={getTypeColor(task.type)} variant="outline">
                            {task.type}
                          </Badge>
                        </div>
                        <div className="text-xs text-muted-foreground space-y-1">
                          <p className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            {task.fieldName}
                          </p>
                          <p className="flex items-center gap-1">
                            <User className="w-3 h-3" />
                            {task.assignedTo}
                          </p>
                          <p className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            {task.plannedStartDate}
                          </p>
                        </div>
                        {task.status === '进行中' && (
                          <div className="mt-2">
                            <Progress value={task.progress} className="h-1" />
                          </div>
                        )}
                      </Card>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* 监控说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Eye className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">任务状态说明：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>未开始</strong>: 任务已分配，等待执行人开始</li>
                  <li>• <strong>进行中</strong>: 任务正在执行中，可实时更新进度</li>
                  <li>• <strong>待验收</strong>: 任务已完成，等待管理员验收</li>
                  <li>• <strong>已完成</strong>: 任务已验收通过，自动归档</li>
                  <li>• 任务状态变更会自动触发消息通知</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 历史与统计 */}
        <TabsContent value="statistics" className="space-y-4">
          {/* 归档任务统计概览 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100 border-green-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-green-700">归档任务总数</p>
                  <p className="mt-2 text-3xl text-green-800">{archivedTasks.length}</p>
                </div>
                <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
              </div>
            </Card>
            
            <Card className="p-6 bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-blue-700">总工时</p>
                  <p className="mt-2 text-3xl text-blue-800">
                    {archivedTasks.reduce((sum, t) => sum + (t.actualHours || t.estimatedHours), 0)}h
                  </p>
                </div>
                <Clock className="w-12 h-12 text-blue-600 opacity-50" />
              </div>
            </Card>
            
            <Card className="p-6 bg-gradient-to-br from-yellow-50 to-yellow-100 border-yellow-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-yellow-700">总成本（估算）</p>
                  <p className="mt-2 text-3xl text-yellow-800">
                    ¥{(archivedTasks.reduce((sum, t) => sum + (t.actualHours || t.estimatedHours), 0) * 50).toLocaleString()}
                  </p>
                </div>
                <BarChart3 className="w-12 h-12 text-yellow-600 opacity-50" />
              </div>
            </Card>
            
            <Card className="p-6 bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-purple-700">涉及地块</p>
                  <p className="mt-2 text-3xl text-purple-800">
                    {new Set(archivedTasks.map(t => t.fieldId)).size}
                  </p>
                </div>
                <MapPin className="w-12 h-12 text-purple-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 多维度查询筛选 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Filter className="w-5 h-5 text-orange-600" />
              多维度组合查询
            </h3>
            <div className="grid grid-cols-6 gap-4 mb-4">
              <Select 
                value={statisticsFilters.fieldId || "all"}
                onValueChange={(value) => setStatisticsFilters({ ...statisticsFilters, fieldId: value === "all" ? "" : value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择地块" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部地块</SelectItem>
                  <SelectItem value="field-1">东区1号地</SelectItem>
                  <SelectItem value="field-2">西区2号地</SelectItem>
                  <SelectItem value="field-3">南区3号地</SelectItem>
                </SelectContent>
              </Select>
              
              <Select
                value={statisticsFilters.crop || "all"}
                onValueChange={(value) => setStatisticsFilters({ ...statisticsFilters, crop: value === "all" ? "" : value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择作物" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部作物</SelectItem>
                  <SelectItem value="水稻">水稻</SelectItem>
                  <SelectItem value="玉米">玉米</SelectItem>
                  <SelectItem value="蔬菜">蔬菜</SelectItem>
                </SelectContent>
              </Select>
              
              <Select
                value={statisticsFilters.assignedTo || "all"}
                onValueChange={(value) => setStatisticsFilters({ ...statisticsFilters, assignedTo: value === "all" ? "" : value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择人员" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部人员</SelectItem>
                  <SelectItem value="张三">张三</SelectItem>
                  <SelectItem value="李四">李四</SelectItem>
                  <SelectItem value="王五">王五</SelectItem>
                </SelectContent>
              </Select>
              
              <Select
                value={statisticsFilters.taskType || "all"}
                onValueChange={(value) => setStatisticsFilters({ ...statisticsFilters, taskType: value === "all" ? "" : value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="任务类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="播种">播种</SelectItem>
                  <SelectItem value="施肥">施肥</SelectItem>
                  <SelectItem value="灌溉">灌溉</SelectItem>
                  <SelectItem value="除草">除草</SelectItem>
                  <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                  <SelectItem value="采收">采收</SelectItem>
                </SelectContent>
              </Select>
              
              <Input 
                type="date" 
                placeholder="开始日期"
                value={statisticsFilters.startDate}
                onChange={(e) => setStatisticsFilters({ ...statisticsFilters, startDate: e.target.value })}
              />
              
              <Input 
                type="date" 
                placeholder="结束日期"
                value={statisticsFilters.endDate}
                onChange={(e) => setStatisticsFilters({ ...statisticsFilters, endDate: e.target.value })}
              />
            </div>
            <div className="flex items-center justify-between">
              <Badge variant="outline" className="text-base">
                筛选结果：{filteredArchivedTasks.length} 条记录
              </Badge>
              <Button 
                variant="outline"
                onClick={() => setStatisticsFilters({ fieldId: '', crop: '', assignedTo: '', startDate: '', endDate: '', taskType: '' })}
              >
                重置筛选
              </Button>
            </div>
          </Card>

          {/* 归档任务列表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <List className="w-5 h-5 text-green-600" />
              归档任务明细
              <Badge className="ml-2 bg-green-600 text-white">{filteredArchivedTasks.length}条</Badge>
            </h3>
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {filteredArchivedTasks.length > 0 ? (
                filteredArchivedTasks.map(task => (
                  <Card key={task.id} className="p-4 hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4>{task.name}</h4>
                          <Badge className={getTypeColor(task.type)} variant="outline">
                            {task.type}
                          </Badge>
                          <Badge className="bg-green-500 text-white">已完成</Badge>
                        </div>
                        <div className="grid grid-cols-5 gap-4 text-sm text-muted-foreground">
                          <div className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            {task.fieldName}
                          </div>
                          <div className="flex items-center gap-1">
                            <User className="w-3 h-3" />
                            {task.assignedTo}
                          </div>
                          <div className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            {task.actualHours || task.estimatedHours}小时
                          </div>
                          <div className="flex items-center gap-1">
                            <Package className="w-3 h-3" />
                            {task.materials.length}种农资
                          </div>
                          <div className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {task.actualEndDate || task.plannedEndDate}
                          </div>
                        </div>
                      </div>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => {
                          setSelectedTask(task);
                          setShowTaskDetailDialog(true);
                        }}
                      >
                        <Eye className="w-3 h-3 mr-1" />
                        查看详情
                      </Button>
                    </div>
                  </Card>
                ))
              ) : (
                <div className="text-center py-12 text-muted-foreground">
                  <FileText className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>没有符合条件的归档任务</p>
                </div>
              )}
            </div>
          </Card>

          {/* 统计图表 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <PieChart className="w-5 h-5 text-blue-600" />
                归档任务类型分布
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <RePieChart>
                    <Pie
                      data={tasksByType}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                      outerRadius={100}
                      fill="#8884d8"
                      dataKey="value"
                    >
                      {tasksByType.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </RePieChart>
                </ResponsiveContainer>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-green-600" />
                任务完成趋势
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={completionTrend}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Line type="monotone" dataKey="完成任务" stroke="#22c55e" strokeWidth={2} />
                    <Line type="monotone" dataKey="新增任务" stroke="#3b82f6" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </div>

          {/* 统计报表生成 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <FileText className="w-5 h-5 text-red-600" />
              统计报表生成
            </h3>
            <div className="grid grid-cols-3 gap-4">
              <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <h4 className="mb-2 flex items-center gap-2">
                  <BarChart3 className="w-4 h-4 text-yellow-600" />
                  成本核算报表
                </h4>
                <p className="text-xs text-muted-foreground mb-3">
                  统计人工成本、农资成本，用于成本分析
                </p>
                <div className="space-y-2 mb-3 text-xs">
                  <div className="flex justify-between">
                    <span>任务数量：</span>
                    <strong>{filteredArchivedTasks.length}个</strong>
                  </div>
                  <div className="flex justify-between">
                    <span>总工时：</span>
                    <strong>{filteredArchivedTasks.reduce((sum, t) => sum + (t.actualHours || t.estimatedHours), 0)}h</strong>
                  </div>
                </div>
                <Button 
                  size="sm" 
                  className="w-full bg-yellow-600 hover:bg-yellow-700"
                  onClick={() => handleGenerateReport('cost')}
                >
                  <Download className="w-4 h-4 mr-2" />
                  生成报表
                </Button>
              </div>

              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <h4 className="mb-2 flex items-center gap-2">
                  <TrendingUp className="w-4 h-4 text-green-600" />
                  绩效考评报表
                </h4>
                <p className="text-xs text-muted-foreground mb-3">
                  统计任务完成情况和验收评价
                </p>
                <div className="space-y-2 mb-3 text-xs">
                  <div className="flex justify-between">
                    <span>参与人员：</span>
                    <strong>{new Set(filteredArchivedTasks.map(t => t.assignedTo)).size}人</strong>
                  </div>
                  <div className="flex justify-between">
                    <span>完成任务：</span>
                    <strong>{filteredArchivedTasks.length}个</strong>
                  </div>
                </div>
                <Button 
                  size="sm" 
                  className="w-full bg-green-600 hover:bg-green-700"
                  onClick={() => handleGenerateReport('performance')}
                >
                  <Download className="w-4 h-4 mr-2" />
                  生成报表
                </Button>
              </div>

              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <h4 className="mb-2 flex items-center gap-2">
                  <FileText className="w-4 h-4 text-blue-600" />
                  生产追溯报表
                </h4>
                <p className="text-xs text-muted-foreground mb-3">
                  记录全流程操作，用于产品追溯
                </p>
                <div className="space-y-2 mb-3 text-xs">
                  <div className="flex justify-between">
                    <span>地块数量：</span>
                    <strong>{new Set(filteredArchivedTasks.map(t => t.fieldId)).size}块</strong>
                  </div>
                  <div className="flex justify-between">
                    <span>操作类型：</span>
                    <strong>{new Set(filteredArchivedTasks.map(t => t.type)).size}种</strong>
                  </div>
                </div>
                <Button 
                  size="sm" 
                  className="w-full bg-blue-600 hover:bg-blue-700"
                  onClick={() => handleGenerateReport('traceability')}
                >
                  <Download className="w-4 h-4 mr-2" />
                  生成报表
                </Button>
              </div>
            </div>
          </Card>

          {/* 统计说明 */}
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <BarChart3 className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">数据统计与应用说明：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动归档</strong>: 所有状态为"已完成"的任务自动归档，永久保存</li>
                  <li>• <strong>多维度查询</strong>: 支持按地块、时间、作物、人员、任务类型等条件组合筛选</li>
                  <li>• <strong>成本核算</strong>: 基于实际工时和农资用量，精确计算人工成本和物料成本（人工按50元/小时估算）</li>
                  <li>• <strong>绩效考评</strong>: 按任务统计完成情况，包含验收评价（优秀、良好、合格、不合格）</li>
                  <li>• <strong>生产追溯</strong>: 按地块记录完整作业历史，支持农产品质量追溯</li>
                  <li>• <strong>报表导出</strong>: 统计数据可导出为Excel、PDF等格式，支持打印和存档</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 创建/编辑任务对话框 */}
      <Dialog open={showTaskDialog} onOpenChange={setShowTaskDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedTask ? '编辑任务' : '新建任务'}</DialogTitle>
            <DialogDescription>
              {selectedTask ? '修改任务的详细信息' : '创建新的农事任务，填写完整的任务要求和安全规范'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
              <h4 className="mb-3 flex items-center gap-2">
                <ClipboardCheck className="w-4 h-4 text-blue-600" />
                基本信息
              </h4>
              <div className="space-y-3">
                {/* 关联农事计划选择器 */}
                {!selectedTask && (
                  <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                    <div className="flex items-start gap-2 mb-2">
                      <Calendar className="w-4 h-4 text-green-600 mt-1" />
                      <div className="flex-1">
                        <label className="text-green-800">关联农事计划（可选）</label>
                        <p className="text-xs text-green-700 mt-1">
                          选择一个现有的农事计划，系统将自动填充任务信息
                        </p>
                      </div>
                    </div>
                    <Select 
                      value={taskForm.relatedPlanId || "none"} 
                      onValueChange={handlePlanSelect}
                    >
                      <SelectTrigger className="mt-2 bg-white">
                        <SelectValue placeholder="不关联计划，手动创建" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">
                          <span className="text-muted-foreground">不关联计划，手动创建</span>
                        </SelectItem>
                        {operationPlans.filter(p => p.status === '已发布' || p.status === '进行中').map(plan => (
                          <SelectItem key={plan.id} value={plan.id}>
                            <div className="flex items-center gap-2">
                              <Badge 
                                className={plan.status === '进行中' ? 'bg-orange-500' : 'bg-blue-500'} 
                                variant="outline"
                              >
                                {plan.status}
                              </Badge>
                              <span>{plan.name}</span>
                              <span className="text-xs text-muted-foreground">
                                ({plan.crop} - {plan.plannedArea}亩)
                              </span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {taskForm.relatedPlanId && taskForm.relatedPlanId !== 'none' && selectedPlan && (
                      <div className="mt-2 p-2 bg-white rounded border border-green-300">
                        <p className="text-xs text-green-800 font-medium">
                          ✓ 已选择计划：{selectedPlan.name}
                        </p>
                        <p className="text-xs text-green-700 mt-1">
                          包含 {selectedPlan.activities.length} 个农事活动，选中 {selectedActivities.length} 个，将批量创建任务
                        </p>
                      </div>
                    )}
                  </div>
                )}
                
                {/* 批量任务创建界面 */}
                {!selectedTask && showBatchTaskCreation && selectedPlan && (
                  <div className="p-4 bg-gradient-to-br from-orange-50 to-yellow-50 rounded-lg border-2 border-orange-300">
                    <div className="flex items-center gap-2 mb-3">
                      <List className="w-5 h-5 text-orange-600" />
                      <h4 className="text-orange-900">批量任务创建</h4>
                      <Badge className="bg-orange-500">
                        {selectedActivities.length}/{selectedPlan.activities.length}
                      </Badge>
                    </div>
                    
                    {/* 选择要创建的活动 */}
                    <div className="mb-4 p-3 bg-white rounded-lg border border-orange-200">
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium">选择农事活动</label>
                        <div className="flex gap-2">
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => setSelectedActivities(selectedPlan.activities.map(a => a.id))}
                          >
                            全选
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => setSelectedActivities([])}
                          >
                            清空
                          </Button>
                        </div>
                      </div>
                      <div className="space-y-2 max-h-48 overflow-y-auto">
                        {selectedPlan.activities.map(activity => (
                          <div 
                            key={activity.id}
                            className="flex items-start gap-3 p-3 rounded-md hover:bg-gray-50 transition-colors"
                          >
                            <Checkbox 
                              checked={selectedActivities.includes(activity.id)}
                              onCheckedChange={() => handleToggleActivity(activity.id)}
                              className="mt-1"
                            />
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <span className="font-medium">{activity.name}</span>
                                <Badge className={getTypeColor(activity.type)} variant="outline">
                                  {activity.type}
                                </Badge>
                              </div>
                              <p className="text-xs text-muted-foreground">
                                {activity.description}
                              </p>
                              <div className="flex gap-4 text-xs text-muted-foreground mt-1">
                                <span>📅 {activity.startDate} 至 {activity.endDate}</span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                    
                    {/* 统一设置执行信息 */}
                    <div className="p-3 bg-white rounded-lg border border-orange-200">
                      <label className="text-sm font-medium mb-3 block">统一执行设置</label>
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="text-xs">执行地块 <span className="text-red-500">*</span></label>
                          <Select 
                            value={batchTaskSettings.fieldId} 
                            onValueChange={(value) => {
                              const fieldNames: Record<string, string> = {
                                'field-1': '东区1号地',
                                'field-2': '西区2号地',
                                'field-3': '南区3号地',
                                'field-4': '北区4号地',
                              };
                              setBatchTaskSettings({ 
                                ...batchTaskSettings, 
                                fieldId: value, 
                                fieldName: fieldNames[value] || '' 
                              });
                            }}
                          >
                            <SelectTrigger className="mt-1">
                              <SelectValue placeholder="选择地块" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="field-1">东区1号地</SelectItem>
                              <SelectItem value="field-2">西区2号地</SelectItem>
                              <SelectItem value="field-3">南区3号地</SelectItem>
                              <SelectItem value="field-4">北区4号地</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <label className="text-xs">所属班组</label>
                          <Select 
                            value={batchTaskSettings.teamName} 
                            onValueChange={(value) => setBatchTaskSettings({ ...batchTaskSettings, teamName: value })}
                          >
                            <SelectTrigger className="mt-1">
                              <SelectValue placeholder="选择班组" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="第一作业组">第一作业组</SelectItem>
                              <SelectItem value="第二作业组">第二作业组</SelectItem>
                              <SelectItem value="第三作业组">第三作业组</SelectItem>
                              <SelectItem value="第四作业组">第四作业组</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="col-span-2">
                          <label className="text-xs">负责人 <span className="text-red-500">*</span></label>
                          <Select 
                            value={batchTaskSettings.assignedTo} 
                            onValueChange={(value) => setBatchTaskSettings({ ...batchTaskSettings, assignedTo: value })}
                          >
                            <SelectTrigger className="mt-1">
                              <SelectValue placeholder="选择负责人" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="张三">张三</SelectItem>
                              <SelectItem value="李四">李四</SelectItem>
                              <SelectItem value="王五">王五</SelectItem>
                              <SelectItem value="赵六">赵六</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                      <div className="mt-3 p-2 bg-blue-50 rounded border border-blue-200">
                        <p className="text-xs text-blue-800">
                          💡 以上设置将应用于所有选中的任务。创建后，每个任务都将使用计划中对应活动的时间、类型和描述信息。
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {!showBatchTaskCreation && (
            <>
            <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>任务名称 <span className="text-red-500">*</span></label>
                    <Input 
                      placeholder="请输入任务名称" 
                      className="mt-2"
                      value={taskForm.name}
                      onChange={(e) => setTaskForm({ ...taskForm, name: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>任务类型 <span className="text-red-500">*</span></label>
                    <Select value={taskForm.type} onValueChange={(value) => setTaskForm({ ...taskForm, type: value as TaskType })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择任务类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {operationTypesData.map((opType) => (
                          <SelectItem key={opType.id} value={opType.name}>
                            {opType.icon} {opType.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground mt-1">
                      从农事执行的农事类��库中选择
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>执行地块 <span className="text-red-500">*</span></label>
                    <Select 
                      value={taskForm.fieldId} 
                      onValueChange={(value) => {
                        const fieldNames: Record<string, string> = {
                          'field-1': '东区1号地',
                          'field-2': '西区2号地',
                          'field-3': '南区3号地',
                          'field-4': '北区4号地',
                        };
                        setTaskForm({ ...taskForm, fieldId: value, fieldName: fieldNames[value] || '' });
                      }}
                    >
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择地块" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="field-1">东区1号地</SelectItem>
                        <SelectItem value="field-2">西区2号地</SelectItem>
                        <SelectItem value="field-3">南区3号地</SelectItem>
                        <SelectItem value="field-4">北区4号地</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <label>预计工时（小时）</label>
                    <Input 
                      type="number" 
                      placeholder="请输入预计工时"
                      className="mt-2"
                      value={taskForm.estimatedHours || ''}
                      onChange={(e) => setTaskForm({ ...taskForm, estimatedHours: parseInt(e.target.value) || 0 })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>负责人 <span className="text-red-500">*</span></label>
                    <Select value={taskForm.assignedTo} onValueChange={(value) => setTaskForm({ ...taskForm, assignedTo: value })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择负责人" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="张三">张三</SelectItem>
                        <SelectItem value="李四">李四</SelectItem>
                        <SelectItem value="王五">王五</SelectItem>
                        <SelectItem value="赵六">赵六</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <label>所属班组</label>
                    <Select value={taskForm.teamName} onValueChange={(value) => setTaskForm({ ...taskForm, teamName: value })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择班组" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="第一作业组">第一作业组</SelectItem>
                        <SelectItem value="第二作业组">第二作业组</SelectItem>
                        <SelectItem value="第三作业组">第三作业组</SelectItem>
                        <SelectItem value="第四作业组">第四作业组</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>计划开始时间 <span className="text-red-500">*</span></label>
                    <Input 
                      type="date" 
                      className="mt-2"
                      value={taskForm.plannedStartDate}
                      onChange={(e) => setTaskForm({ ...taskForm, plannedStartDate: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>计划结束时间</label>
                    <Input 
                      type="date" 
                      className="mt-2"
                      value={taskForm.plannedEndDate}
                      onChange={(e) => setTaskForm({ ...taskForm, plannedEndDate: e.target.value })}
                    />
                  </div>
                </div>

                <div>
                  <label>任务描述</label>
                  <Textarea 
                    placeholder="请输入任务描述" 
                    className="mt-2" 
                    rows={3}
                    value={taskForm.description}
                    onChange={(e) => setTaskForm({ ...taskForm, description: e.target.value })}
                  />
                </div>

                {/* 操作要求 */}
            <div className="p-4 bg-green-50 rounded-lg border border-green-200">
              <h4 className="mb-3 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-green-600" />
                操作要求
              </h4>
              <div>
                <label>作业规范（每行一条要求）</label>
                <Textarea 
                  placeholder="例如：&#10;种子需提前浸种12-24小时&#10;播种深度控制在2-3cm&#10;行距保持30cm" 
                  className="mt-2" 
                  rows={5}
                  value={taskForm.requirements}
                  onChange={(e) => setTaskForm({ ...taskForm, requirements: e.target.value })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  详细列出操作步骤和技术要求，确保作业人员清楚了解标准
                </p>
              </div>
            </div>

            {/* 所需农资 */}
            <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
              <h4 className="mb-3 flex items-center gap-2">
                <Package className="w-4 h-4 text-yellow-600" />
                所需农资
              </h4>
              <div className="space-y-3">
                {materials.map((material, index) => (
                  <div key={index} className="space-y-2">
                    <div className="flex gap-2 items-start">
                      <div className="flex-1 flex gap-2">
                        <Input 
                          placeholder="农资名称"
                          className="flex-1"
                          value={material.name}
                          onChange={(e) => handleUpdateMaterial(index, 'name', e.target.value)}
                        />
                        <Button
                          type="button"
                          size="sm"
                          variant="outline"
                          className="flex-shrink-0"
                          onClick={() => handleSelectFromInventory(index)}
                        >
                          <Search className="w-4 h-4 mr-1" />
                          从农资库选择
                        </Button>
                      </div>
                      <Input 
                        type="number"
                        placeholder="数量"
                        className="w-28"
                        value={material.amount || ''}
                        onChange={(e) => handleUpdateMaterial(index, 'amount', parseFloat(e.target.value) || 0)}
                      />
                      <Select 
                        value={material.unit} 
                        onValueChange={(value) => handleUpdateMaterial(index, 'unit', value)}
                      >
                        <SelectTrigger className="w-24">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="kg">kg</SelectItem>
                          <SelectItem value="g">g</SelectItem>
                          <SelectItem value="L">L</SelectItem>
                          <SelectItem value="mL">mL</SelectItem>
                          <SelectItem value="个">个</SelectItem>
                          <SelectItem value="包">包</SelectItem>
                          <SelectItem value="袋">袋</SelectItem>
                          <SelectItem value="桶">桶</SelectItem>
                          <SelectItem value="升">升</SelectItem>
                          <SelectItem value="公斤">公斤</SelectItem>
                          <SelectItem value="套">套</SelectItem>
                          <SelectItem value="条">条</SelectItem>
                        </SelectContent>
                      </Select>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleRemoveMaterial(index)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                    {material.currentStock !== undefined && (
                      <p className="text-xs text-muted-foreground ml-2 flex items-center gap-1">
                        <Package className="w-3 h-3" />
                        当前库存：{material.currentStock} {material.unit}
                        {material.amount > material.currentStock && (
                          <span className="text-red-600 ml-2">⚠️ 库存不足</span>
                        )}
                      </p>
                    )}
                  </div>
                ))}
                <Button 
                  variant="outline" 
                  className="w-full border-dashed"
                  onClick={handleAddMaterial}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加农资
                </Button>
                <p className="text-xs text-muted-foreground">
                  💡 可以手动输入或从农资库选择。列出完成任务所需的种子、肥料、农药等农资及用量
                </p>
              </div>
            </div>

            {/* 安全注意事项 */}
            <div className="p-4 bg-red-50 rounded-lg border border-red-200">
              <h4 className="mb-3 flex items-center gap-2">
                <Shield className="w-4 h-4 text-red-600" />
                安全注意事项
              </h4>
              <div>
                <label>安全规范（每行一条）</label>
                <Textarea 
                  placeholder="例如：&#10;作业时佩戴手套和口罩&#10;注意防止滑倒&#10;避免在雨天作业&#10;使用农药时穿戴防护服" 
                  className="mt-2" 
                  rows={5}
                  value={taskForm.safetyNotes}
                  onChange={(e) => setTaskForm({ ...taskForm, safetyNotes: e.target.value })}
                />
                <p className="text-xs text-red-800 mt-1">
                  ⚠️ 重要：列出所有安全隐患和防护措施，确保作业人员安全
                </p>
              </div>
            </div>
            </>
            )}

            <div className="flex gap-2 justify-end pt-4 border-t">
              <Button variant="outline" onClick={() => setShowTaskDialog(false)}>
                取消
              </Button>
              {showBatchTaskCreation ? (
                <Button className="bg-orange-600 hover:bg-orange-700" onClick={handleBatchCreateTasks}>
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  批量创建任务
                </Button>
              ) : (
                <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveTask}>
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  {selectedTask ? '保存修改' : '创建任务'}
                </Button>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 任务详情对话框 */}
      <Dialog open={showTaskDetailDialog} onOpenChange={setShowTaskDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>任务详情</DialogTitle>
            <DialogDescription>
              查看任务的完整信息和执行要求
            </DialogDescription>
          </DialogHeader>
          {selectedTask && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <ClipboardCheck className="w-4 h-4 text-blue-600" />
                  基本信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>任务名称</label>
                    <p className="field-value">{selectedTask.name}</p>
                  </div>
                  <div>
                    <label>任务类型</label>
                    <p className="field-value">
                      <Badge className={getTypeColor(selectedTask.type)}>{selectedTask.type}</Badge>
                    </p>
                  </div>
                  <div>
                    <label>任务状态</label>
                    <p className="field-value">
                      <Badge className={getStatusColor(selectedTask.status)}>
                        {getStatusIcon(selectedTask.status)}
                        <span className="ml-1">{selectedTask.status}</span>
                      </Badge>
                    </p>
                  </div>
                  <div>
                    <label>任务来源</label>
                    <p className="field-value">
                      <Badge variant="outline">{selectedTask.source}</Badge>
                    </p>
                  </div>
                  <div>
                    <label>执行地块</label>
                    <p className="field-value flex items-center gap-1">
                      <MapPin className="w-4 h-4 text-blue-600" />
                      {selectedTask.fieldName}
                    </p>
                  </div>
                  <div>
                    <label>地块位置</label>
                    <p className="field-value text-sm">{selectedTask.fieldLocation}</p>
                  </div>
                  <div>
                    <label>作物类型</label>
                    <p className="field-value">{selectedTask.crop}</p>
                  </div>
                  <div>
                    <label>负责人</label>
                    <p className="field-value flex items-center gap-1">
                      <User className="w-4 h-4 text-green-600" />
                      {selectedTask.assignedTo}
                    </p>
                  </div>
                  <div>
                    <label>所属班组</label>
                    <p className="field-value flex items-center gap-1">
                      <Users className="w-4 h-4 text-green-600" />
                      {selectedTask.teamName}
                    </p>
                  </div>
                  <div>
                    <label>创建人</label>
                    <p className="field-value">{selectedTask.createdBy}</p>
                  </div>
                  <div>
                    <label>创建时间</label>
                    <p className="field-value">{selectedTask.createdAt}</p>
                  </div>
                  <div>
                    <label>任务ID</label>
                    <p className="field-value text-xs text-muted-foreground">{selectedTask.id}</p>
                  </div>
                </div>
              </div>

              {/* 时间信息 */}
              <div className="p-4 bg-purple-50 rounded-lg border border-purple-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <Clock className="w-4 h-4 text-purple-600" />
                  时间与工时
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>计划开始时间</label>
                    <p className="field-value">{selectedTask.plannedStartDate}</p>
                  </div>
                  <div>
                    <label>计划结束时间</label>
                    <p className="field-value">{selectedTask.plannedEndDate}</p>
                  </div>
                  {selectedTask.actualStartDate && (
                    <div>
                      <label>实际开始时间</label>
                      <p className="field-value">{selectedTask.actualStartDate}</p>
                    </div>
                  )}
                  {selectedTask.actualEndDate && (
                    <div>
                      <label>实际结束时间</label>
                      <p className="field-value">{selectedTask.actualEndDate}</p>
                    </div>
                  )}
                  <div>
                    <label>预计工时</label>
                    <p className="field-value">{selectedTask.estimatedHours} 小时</p>
                  </div>
                  {selectedTask.actualHours && (
                    <div>
                      <label>实际工时</label>
                      <p className="field-value">{selectedTask.actualHours} 小时</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 任务描述 */}
              {selectedTask.description && (
                <div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <FileText className="w-4 h-4 text-gray-600" />
                    任务描述
                  </h4>
                  <p className="text-sm whitespace-pre-line">{selectedTask.description}</p>
                </div>
              )}

              {/* 操作要求 */}
              {selectedTask.requirements.length > 0 && (
                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600" />
                    操作要求
                  </h4>
                  <ul className="space-y-2">
                    {selectedTask.requirements.map((req, i) => (
                      <li key={i} className="text-sm flex items-start gap-2">
                        <CheckCircle2 className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-600" />
                        <span>{req}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* 所需农资 */}
              {selectedTask.materials.length > 0 && (
                <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Package className="w-4 h-4 text-yellow-600" />
                    所需农资
                  </h4>
                  <div className="grid grid-cols-2 gap-3">
                    {selectedTask.materials.map((mat, i) => (
                      <div key={i} className="flex items-center justify-between p-3 bg-white rounded-lg">
                        <span className="flex items-center gap-2">
                          <Package className="w-4 h-4 text-yellow-600" />
                          <span>{mat.name}</span>
                        </span>
                        <span className="font-medium">{mat.amount}{mat.unit}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 安全注意事项 */}
              {selectedTask.safetyNotes.length > 0 && (
                <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Shield className="w-4 h-4 text-red-600" />
                    安全注意事项
                  </h4>
                  <ul className="space-y-2">
                    {selectedTask.safetyNotes.map((note, i) => (
                      <li key={i} className="text-sm flex items-start gap-2 text-red-800">
                        <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-red-600" />
                        <span>{note}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* 任务进度 */}
              <div className="p-4 bg-orange-50 rounded-lg border border-orange-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <TrendingUp className="w-4 h-4 text-orange-600" />
                  任务进度
                </h4>
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm text-muted-foreground">完成进度</span>
                    <span className="font-medium">{selectedTask.progress}%</span>
                  </div>
                  <Progress value={selectedTask.progress} className="h-3" />
                </div>
              </div>

              {/* 现场图片 */}
              {selectedTask.images && selectedTask.images.length > 0 && (
                <div className="p-4 bg-purple-50 rounded-lg border border-purple-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <svg className="w-4 h-4 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    现场图片 ({selectedTask.images.length}张)
                  </h4>
                  <div className="grid grid-cols-4 gap-3">
                    {selectedTask.images.map((img, index) => (
                      <div key={index} className="relative group">
                        <img 
                          src={img} 
                          alt={`现场图片 ${index + 1}`}
                          className="w-full h-32 object-cover rounded-lg border-2 border-purple-200 cursor-pointer hover:border-purple-400 transition-colors"
                          onClick={() => window.open(img, '_blank')}
                        />
                        <div className="absolute bottom-1 left-1 bg-black/50 text-white text-xs px-2 py-1 rounded">
                          图片 {index + 1}
                        </div>
                      </div>
                    ))}
                  </div>
                  <p className="text-xs text-purple-600 mt-2">
                    点击图片可查看大图
                  </p>
                </div>
              )}

              <div className="flex gap-2 justify-end pt-2 border-t">
                <Button variant="outline" onClick={() => setShowTaskDetailDialog(false)}>
                  关闭
                </Button>
                {selectedTask.status !== '已完成' && (
                  <Button 
                    className="bg-green-600 hover:bg-green-700"
                    onClick={() => {
                      setShowTaskDetailDialog(false);
                      handleEditTask(selectedTask);
                    }}
                  >
                    <Edit className="w-4 h-4 mr-2" />
                    编辑任务
                  </Button>
                )}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 统计报表对话框 */}
      <Dialog open={showReportDialog} onOpenChange={setShowReportDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {reportType === 'cost' && '成本核算报表'}
              {reportType === 'performance' && '绩效考评报表'}
              {reportType === 'traceability' && '生产追溯报表'}
            </DialogTitle>
            <DialogDescription>
              {reportType === 'cost' && '基于已完成任务的人工成本和农资成本统计'}
              {reportType === 'performance' && '基于已完成任务的验收评价统计'}
              {reportType === 'traceability' && '基于地块的完整作业历史记录'}
            </DialogDescription>
          </DialogHeader>
          
          {reportType === 'cost' && (
            <div className="space-y-4">
              <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <h4 className="mb-2">成本汇总</h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">人工成本</p>
                    <p className="text-xl text-yellow-800">
                      ¥{generateCostReport().reduce((sum, r) => sum + r.laborCost, 0).toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">农资成本</p>
                    <p className="text-xl text-yellow-800">
                      ¥{generateCostReport().reduce((sum, r) => sum + r.materialCost, 0).toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">总成本</p>
                    <p className="text-xl text-yellow-800">
                      ¥{generateCostReport().reduce((sum, r) => sum + r.totalCost, 0).toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">任务数量</p>
                    <p className="text-xl text-yellow-800">{generateCostReport().length}</p>
                  </div>
                </div>
              </div>
              
              <div className="overflow-x-auto max-h-96">
                <table className="w-full text-sm">
                  <thead className="bg-gray-100 sticky top-0">
                    <tr>
                      <th className="p-2 text-left">任务名称</th>
                      <th className="p-2 text-left">地块</th>
                      <th className="p-2 text-left">执行人</th>
                      <th className="p-2 text-right">工时</th>
                      <th className="p-2 text-right">人工成本</th>
                      <th className="p-2 text-right">农资成本</th>
                      <th className="p-2 text-right">总成本</th>
                      <th className="p-2 text-left">完成日期</th>
                    </tr>
                  </thead>
                  <tbody>
                    {generateCostReport().map((row, index) => (
                      <tr key={index} className="border-b hover:bg-gray-50">
                        <td className="p-2">{row.taskName}</td>
                        <td className="p-2">{row.fieldName}</td>
                        <td className="p-2">{row.executor}</td>
                        <td className="p-2 text-right">{row.workHours}h</td>
                        <td className="p-2 text-right">¥{row.laborCost.toLocaleString()}</td>
                        <td className="p-2 text-right">¥{row.materialCost.toLocaleString()}</td>
                        <td className="p-2 text-right text-yellow-800">¥{row.totalCost.toLocaleString()}</td>
                        <td className="p-2">{row.completedDate}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
          
          {reportType === 'performance' && (
            <div className="space-y-4">
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <h4 className="mb-2">绩效汇总</h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">参与人员</p>
                    <p className="text-xl text-green-800">{new Set(generatePerformanceReport().map(r => r.executor)).size}人</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">完成任务</p>
                    <p className="text-xl text-green-800">
                      {generatePerformanceReport().length}个
                    </p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">总工时</p>
                    <p className="text-xl text-green-800">
                      {generatePerformanceReport().reduce((sum, r) => sum + r.totalHours, 0)}h
                    </p>
                  </div>
                </div>
              </div>
              
              <div className="overflow-x-auto max-h-96">
                <table className="w-full text-sm">
                  <thead className="bg-gray-100 sticky top-0">
                    <tr>
                      <th className="p-2 text-left">任务名称</th>
                      <th className="p-2 text-left">地块</th>
                      <th className="p-2 text-left">执行人</th>
                      <th className="p-2 text-right">工时</th>
                      <th className="p-2 text-left">完成日期</th>
                      <th className="p-2 text-center">验收评价</th>
                    </tr>
                  </thead>
                  <tbody>
                    {generatePerformanceReport().map((row, index) => (
                      <tr key={index} className="border-b hover:bg-gray-50">
                        <td className="p-2">{row.taskName}</td>
                        <td className="p-2">{row.fieldName}</td>
                        <td className="p-2">{row.executor}</td>
                        <td className="p-2 text-right">{row.totalHours}h</td>
                        <td className="p-2">{row.completedDate}</td>
                        <td className="p-2 text-center">
                          <Badge className={
                            row.acceptanceRating === '优秀' ? 'bg-green-600 text-white' :
                            row.acceptanceRating === '良好' ? 'bg-blue-600 text-white' :
                            row.acceptanceRating === '合格' ? 'bg-yellow-600 text-white' :
                            row.acceptanceRating === '不合格' ? 'bg-red-600 text-white' :
                            'bg-gray-400 text-white'
                          }>
                            {row.acceptanceRating}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
          
          {reportType === 'traceability' && (
            <div className="space-y-4">
              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <h4 className="mb-2">追溯汇总</h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">地块数量</p>
                    <p className="text-xl text-blue-800">{generateTraceabilityReport().length}块</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">作业记录</p>
                    <p className="text-xl text-blue-800">{filteredArchivedTasks.length}条</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">操作类型</p>
                    <p className="text-xl text-blue-800">
                      {new Set(filteredArchivedTasks.map(t => t.type)).size}种
                    </p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">涉及作物</p>
                    <p className="text-xl text-blue-800">
                      {new Set(filteredArchivedTasks.map(t => t.crop)).size}种
                    </p>
                  </div>
                </div>
              </div>
              
              <div className="space-y-4 max-h-96 overflow-y-auto">
                {generateTraceabilityReport().map((field, index) => (
                  <Card key={index} className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div>
                        <h4 className="flex items-center gap-2">
                          <MapPin className="w-4 h-4 text-blue-600" />
                          {field.fieldName}
                        </h4>
                        <p className="text-sm text-muted-foreground">作物：{field.crop}</p>
                      </div>
                      <Badge variant="outline">{field.operations.length}次作业</Badge>
                    </div>
                    <div className="space-y-2">
                      {field.operations.map((op, opIndex) => (
                        <div key={opIndex} className="flex items-center gap-3 p-2 bg-gray-50 rounded text-sm">
                          <Badge className={getTypeColor(op.type)} variant="outline">
                            {op.type}
                          </Badge>
                          <span>{op.name}</span>
                          <span className="text-muted-foreground">执行人：{op.assignedTo}</span>
                          <span className="text-muted-foreground">
                            {op.actualEndDate || op.plannedEndDate}
                          </span>
                          <span className="text-muted-foreground">{op.actualHours || op.estimatedHours}h</span>
                        </div>
                      ))}
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          )}
          
          <div className="flex gap-2 justify-end pt-4 border-t">
            <Button variant="outline" onClick={() => setShowReportDialog(false)}>
              关闭
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleDownloadReport}>
              <Download className="w-4 h-4 mr-2" />
              下载报表
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 发送通知对话框 */}
      <Dialog open={showNotificationDialog} onOpenChange={setShowNotificationDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>发送任务通知</DialogTitle>
            <DialogDescription>
              选择通知渠道和接收人，发送任务相关通知
            </DialogDescription>
          </DialogHeader>
          {selectedTask && (
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="mb-2">任务信息</h4>
                <p className="text-sm">
                  <strong>任务名称：</strong>{selectedTask.name}
                </p>
                <p className="text-sm">
                  <strong>负责人：</strong>{selectedTask.assignedTo} / {selectedTask.teamName}
                </p>
              </div>

              <div>
                <label>通知类型</label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择通知类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="任务分配">任务分配</SelectItem>
                    <SelectItem value="任务变更">任务变更</SelectItem>
                    <SelectItem value="任务提醒">任务提醒</SelectItem>
                    <SelectItem value="验收通知">验收通知</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label>通知渠道</label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  <div className="flex items-center gap-2">
                    <Checkbox id="channel-message" defaultChecked />
                    <label htmlFor="channel-message" className="text-sm cursor-pointer">
                      消息中心
                    </label>
                  </div>
                  <div className="flex items-center gap-2">
                    <Checkbox id="channel-sms" defaultChecked />
                    <label htmlFor="channel-sms" className="text-sm cursor-pointer">
                      短信通知
                    </label>
                  </div>
                  <div className="flex items-center gap-2">
                    <Checkbox id="channel-email" />
                    <label htmlFor="channel-email" className="text-sm cursor-pointer">
                      邮件通知
                    </label>
                  </div>
                  <div className="flex items-center gap-2">
                    <Checkbox id="channel-app" defaultChecked />
                    <label htmlFor="channel-app" className="text-sm cursor-pointer">
                      APP推送
                    </label>
                  </div>
                </div>
              </div>

              <div>
                <label>通知内容预览</label>
                <div className="mt-2 p-3 bg-blue-50 rounded-lg">
                  <p className="text-sm text-blue-900">
                    您有新的农事任务：{selectedTask.name}。地块位置：{selectedTask.fieldLocation}。
                    计划开始时间：{selectedTask.plannedStartDate}。请按要求完成任务。
                  </p>
                </div>
              </div>

              <div className="flex gap-2 justify-end">
                <Button variant="outline" onClick={() => setShowNotificationDialog(false)}>
                  取消
                </Button>
                <Button
                  className="bg-green-600 hover:bg-green-700"
                  onClick={() => {
                    sendNotification(selectedTask.id, '任务分配');
                    setShowNotificationDialog(false);
                  }}
                >
                  <Send className="w-4 h-4 mr-2" />
                  发送通知
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 提交验收对话框 */}
      <Dialog open={showSubmitDialog} onOpenChange={setShowSubmitDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>提交任务验收</DialogTitle>
            <DialogDescription>
              填写任务实际使用的农资信息，提交验收申请
            </DialogDescription>
          </DialogHeader>
          {selectedTask && (
            <div className="space-y-4">
              {/* 任务信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <FileText className="w-4 h-4 text-blue-600" />
                  任务信息
                </h4>
                <div className="grid grid-cols-3 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">任务名称：</span>
                    <span className="font-medium">{selectedTask.name}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">任务类型：</span>
                    <Badge className={getTypeColor(selectedTask.type)}>{selectedTask.type}</Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行地块：</span>
                    <span className="font-medium">{selectedTask.fieldName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行人员：</span>
                    <span className="font-medium">{selectedTask.assignedTo}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">计划时间：</span>
                    <span className="font-medium">{selectedTask.plannedStartDate}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">任务进度：</span>
                    <span className="font-medium text-green-600">{selectedTask.progress}%</span>
                  </div>
                </div>
              </Card>

              {/* 计划农资对比 */}
              {selectedTask.materials.length > 0 && (
                <Card className="p-4 bg-gray-50">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Package className="w-4 h-4 text-gray-600" />
                    计划农资清单
                  </h4>
                  <div className="space-y-2">
                    {selectedTask.materials.map((mat, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-white rounded text-sm">
                        <span>{mat.name}</span>
                        <span className="font-medium text-blue-600">{mat.amount} {mat.unit}</span>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 实际使用农资 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Package className="w-4 h-4 text-green-600" />
                  实际使用农资
                </h4>
                <div className="space-y-3">
                  {submitData.actualMaterials.map((mat, index) => (
                    <Card key={index} className="p-3 bg-green-50 border-green-200">
                      <div className="grid grid-cols-5 gap-3">
                        <div>
                          <label className="text-xs">农资名称</label>
                          <Input
                            className="mt-1"
                            value={mat.name}
                            onChange={(e) => {
                              const newMaterials = [...submitData.actualMaterials];
                              newMaterials[index].name = e.target.value;
                              setSubmitData({ ...submitData, actualMaterials: newMaterials });
                            }}
                          />
                        </div>
                        <div>
                          <label className="text-xs">品牌</label>
                          <Input
                            className="mt-1"
                            placeholder="如：隆平高科"
                            value={mat.brand}
                            onChange={(e) => {
                              const newMaterials = [...submitData.actualMaterials];
                              newMaterials[index].brand = e.target.value;
                              setSubmitData({ ...submitData, actualMaterials: newMaterials });
                            }}
                          />
                        </div>
                        <div>
                          <label className="text-xs">实际用量</label>
                          <div className="flex gap-1 mt-1">
                            <Input
                              type="number"
                              className="flex-1"
                              value={mat.amount}
                              onChange={(e) => {
                                const newMaterials = [...submitData.actualMaterials];
                                newMaterials[index].amount = parseFloat(e.target.value) || 0;
                                setSubmitData({ ...submitData, actualMaterials: newMaterials });
                              }}
                            />
                            <span className="flex items-center px-2 bg-gray-100 rounded text-xs">
                              {mat.unit}
                            </span>
                          </div>
                        </div>
                        <div>
                          <label className="text-xs">批次号</label>
                          <Input
                            className="mt-1"
                            placeholder="如：LP20240301"
                            value={mat.batchNo}
                            onChange={(e) => {
                              const newMaterials = [...submitData.actualMaterials];
                              newMaterials[index].batchNo = e.target.value;
                              setSubmitData({ ...submitData, actualMaterials: newMaterials });
                            }}
                          />
                        </div>
                        <div className="flex items-end">
                          <Button
                            size="sm"
                            variant="outline"
                            className="w-full"
                            onClick={() => {
                              const newMaterials = submitData.actualMaterials.filter((_, i) => i !== index);
                              setSubmitData({ ...submitData, actualMaterials: newMaterials });
                            }}
                          >
                            <Trash2 className="w-3 h-3 mr-1" />
                            删除
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                  
                  <Button
                    size="sm"
                    variant="outline"
                    className="w-full"
                    onClick={() => {
                      const newMaterials = [
                        ...submitData.actualMaterials,
                        { name: '', brand: '', amount: 0, unit: 'kg', batchNo: '' }
                      ];
                      setSubmitData({ ...submitData, actualMaterials: newMaterials });
                    }}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    添加农资
                  </Button>
                </div>
              </Card>

              {/* 提交说明 */}
              <Card className="p-4">
                <h4 className="mb-3">提交说明</h4>
                <Textarea
                  placeholder="请填写任务完成情况说明（选填）"
                  rows={4}
                  value={submitData.submitNotes}
                  onChange={(e) => setSubmitData({ ...submitData, submitNotes: e.target.value })}
                />
              </Card>

              {/* 现场图片上传 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <svg className="w-4 h-4 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                  现场图片
                </h4>
                
                {/* 图片预览区域 */}
                {submitData.images.length > 0 && (
                  <div className="mb-4 grid grid-cols-4 gap-3">
                    {submitData.images.map((img, index) => (
                      <div key={index} className="relative group">
                        <img 
                          src={img} 
                          alt={`现场图片 ${index + 1}`}
                          className="w-full h-32 object-cover rounded-lg border-2 border-gray-200"
                        />
                        <button
                          className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                          onClick={() => {
                            const newImages = submitData.images.filter((_, i) => i !== index);
                            setSubmitData({ ...submitData, images: newImages });
                          }}
                        >
                          <Trash2 className="w-3 h-3" />
                        </button>
                        <div className="absolute bottom-1 left-1 bg-black/50 text-white text-xs px-2 py-1 rounded">
                          图片 {index + 1}
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* 上传按钮 */}
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-purple-400 transition-colors cursor-pointer"
                  onClick={() => {
                    // 创建文件输入
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = 'image/*';
                    input.multiple = true;
                    input.onchange = (e) => {
                      const files = (e.target as HTMLInputElement).files;
                      if (files) {
                        const newImages: string[] = [];
                        Array.from(files).forEach(file => {
                          const reader = new FileReader();
                          reader.onload = (event) => {
                            if (event.target?.result) {
                              newImages.push(event.target.result as string);
                              if (newImages.length === files.length) {
                                setSubmitData({ 
                                  ...submitData, 
                                  images: [...submitData.images, ...newImages] 
                                });
                                toast.success(`已添加 ${newImages.length} 张图片`);
                              }
                            }
                          };
                          reader.readAsDataURL(file);
                        });
                      }
                    };
                    input.click();
                  }}
                >
                  <svg className="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                  </svg>
                  <p className="text-sm text-muted-foreground mb-1">
                    点击上传现场图片
                  </p>
                  <p className="text-xs text-muted-foreground">
                    支持 JPG、PNG 格式，可选择多张图片
                  </p>
                  {submitData.images.length > 0 && (
                    <p className="text-xs text-purple-600 mt-2">
                      已上传 {submitData.images.length} 张图片
                    </p>
                  )}
                </div>
              </Card>

              <div className="flex gap-2 justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowSubmitDialog(false)}>
                  取消
                </Button>
                <Button 
                  className="bg-blue-600 hover:bg-blue-700"
                  onClick={handleSubmitAcceptance}
                >
                  <Send className="w-4 h-4 mr-2" />
                  提交验收并同步至农事操作
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 验收评价对话框 */}
      <Dialog open={showAcceptanceDialog} onOpenChange={setShowAcceptanceDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>任务验收评价</DialogTitle>
            <DialogDescription>
              对任务执行质量进行评价，填写验收意见。验收完成后将自动同步至农事操作记录并标记为审核完成。
            </DialogDescription>
          </DialogHeader>
          {selectedTask && (
            <div className="space-y-4">
              {/* 同步提示 */}
              <div className="p-4 bg-gradient-to-r from-blue-50 to-green-50 dark:from-blue-900/20 dark:to-green-900/20 rounded-lg border-2 border-blue-200 dark:border-blue-700">
                <div className="flex items-start gap-3">
                  <div className="flex-shrink-0 mt-0.5">
                    <svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>
                  <div className="flex-1">
                    <h4 className="text-sm font-semibold text-blue-900 dark:text-blue-100 mb-1">
                      验收数据同步说明
                    </h4>
                    <p className="text-sm text-blue-800 dark:text-blue-200">
                      提交验收后，系统将自动执行以下操作：
                    </p>
                    <ul className="mt-2 space-y-1 text-sm text-blue-700 dark:text-blue-300">
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400 flex-shrink-0" />
                        <span>将验收结果同步至农事操作记录</span>
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400 flex-shrink-0" />
                        <span>农事操作记录状态标记为"审核完成"</span>
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400 flex-shrink-0" />
                        <span>保存验收评分、等级和意见至操作档案</span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* 任务信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <ClipboardCheck className="w-4 h-4 text-blue-600" />
                  任务信息
                </h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">任务名称：</span>
                    <span className="font-medium">{selectedTask.name}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">任务类型：</span>
                    <Badge className={getTypeColor(selectedTask.type)}>{selectedTask.type}</Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行地块：</span>
                    <span className="font-medium">{selectedTask.fieldName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行人员：</span>
                    <span className="font-medium">{selectedTask.assignedTo}</span>
                  </div>
                </div>
              </Card>

              {/* 实际使用农资 */}
              {selectedTask.actualMaterials && selectedTask.actualMaterials.length > 0 && (
                <Card className="p-4 bg-green-50 border-green-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Package className="w-4 h-4 text-green-600" />
                    实际使用农资
                  </h4>
                  <div className="space-y-2">
                    {selectedTask.actualMaterials.map((mat, index) => (
                      <div key={index} className="grid grid-cols-5 gap-3 p-2 bg-white rounded text-sm">
                        <div>
                          <span className="text-muted-foreground text-xs">农资名称</span>
                          <p className="font-medium">{mat.name}</p>
                        </div>
                        <div>
                          <span className="text-muted-foreground text-xs">品牌</span>
                          <p className="font-medium">{mat.brand || '-'}</p>
                        </div>
                        <div>
                          <span className="text-muted-foreground text-xs">实际用量</span>
                          <p className="font-medium text-blue-600">{mat.amount} {mat.unit}</p>
                        </div>
                        <div>
                          <span className="text-muted-foreground text-xs">批次号</span>
                          <p className="font-medium">{mat.batchNo || '-'}</p>
                        </div>
                        <div>
                          <span className="text-muted-foreground text-xs">与计划对比</span>
                          <p className={`font-medium ${
                            selectedTask.materials[index] && mat.amount === selectedTask.materials[index].amount 
                              ? 'text-green-600' 
                              : 'text-orange-600'
                          }`}>
                            {selectedTask.materials[index] 
                              ? `${mat.amount - selectedTask.materials[index].amount > 0 ? '+' : ''}${(mat.amount - selectedTask.materials[index].amount).toFixed(1)} ${mat.unit}`
                              : '新增'
                            }
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                  {selectedTask.submittedBy && (
                    <div className="mt-3 text-xs text-green-800">
                      提交人：{selectedTask.submittedBy} | 提交时间：{selectedTask.submittedAt}
                    </div>
                  )}
                </Card>
              )}

              {/* 现场图片 */}
              {selectedTask.images && selectedTask.images.length > 0 && (
                <Card className="p-4 bg-purple-50 border-purple-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <svg className="w-4 h-4 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    现场图片 ({selectedTask.images.length}张)
                  </h4>
                  <div className="grid grid-cols-3 gap-3">
                    {selectedTask.images.map((img, index) => (
                      <div key={index} className="relative group">
                        <img 
                          src={img} 
                          alt={`现场图片 ${index + 1}`}
                          className="w-full h-40 object-cover rounded-lg border-2 border-purple-200 cursor-pointer hover:border-purple-400 transition-colors"
                          onClick={() => window.open(img, '_blank')}
                        />
                        <div className="absolute bottom-2 left-2 bg-black/60 text-white text-xs px-2 py-1 rounded">
                          图片 {index + 1}
                        </div>
                      </div>
                    ))}
                  </div>
                  <p className="text-xs text-purple-600 mt-2">
                    提交人：{selectedTask.submittedBy} | 点击图片可查看大图
                  </p>
                </Card>
              )}

              {/* 验收评分 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <BarChart3 className="w-4 h-4 text-green-600" />
                  验收评分
                </h4>
                <div className="space-y-4">
                  <div>
                    <label className="flex items-center justify-between mb-2">
                      <span>质量评分</span>
                      <span className="text-green-600 font-medium">{acceptanceData.qualityScore} 分</span>
                    </label>
                    <Input
                      type="range"
                      min="0"
                      max="100"
                      value={acceptanceData.qualityScore}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        qualityScore: parseInt(e.target.value)
                      })}
                      className="w-full"
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      评价作业质量是否达标
                    </p>
                  </div>

                  <div>
                    <label className="flex items-center justify-between mb-2">
                      <span>效率评分</span>
                      <span className="text-blue-600 font-medium">{acceptanceData.efficiencyScore} 分</span>
                    </label>
                    <Input
                      type="range"
                      min="0"
                      max="100"
                      value={acceptanceData.efficiencyScore}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        efficiencyScore: parseInt(e.target.value)
                      })}
                      className="w-full"
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      评价作业效率和时间把控
                    </p>
                  </div>

                  <div>
                    <label className="flex items-center justify-between mb-2">
                      <span>规范评分</span>
                      <span className="text-purple-600 font-medium">{acceptanceData.standardScore} 分</span>
                    </label>
                    <Input
                      type="range"
                      min="0"
                      max="100"
                      value={acceptanceData.standardScore}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        standardScore: parseInt(e.target.value)
                      })}
                      className="w-full"
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      评价操作规范性和安全性
                    </p>
                  </div>
                </div>
              </Card>

              {/* 综合评价 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-green-600" />
                  综合评价
                </h4>
                <div className="space-y-4">
                  <div>
                    <label className="flex items-center gap-1">
                      <span className="text-red-500">*</span>
                      验收等级
                    </label>
                    <Select 
                      value={acceptanceData.rating}
                      onValueChange={(value: any) => setAcceptanceData({
                        ...acceptanceData,
                        rating: value
                      })}
                    >
                      <SelectTrigger className="mt-2">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="优秀">
                          <div className="flex items-center gap-2">
                            <div className="w-2 h-2 rounded-full bg-green-600"></div>
                            优秀 (90分以上)
                          </div>
                        </SelectItem>
                        <SelectItem value="良好">
                          <div className="flex items-center gap-2">
                            <div className="w-2 h-2 rounded-full bg-blue-600"></div>
                            良好 (80-89分)
                          </div>
                        </SelectItem>
                        <SelectItem value="合格">
                          <div className="flex items-center gap-2">
                            <div className="w-2 h-2 rounded-full bg-yellow-600"></div>
                            合格 (60-79分)
                          </div>
                        </SelectItem>
                        <SelectItem value="不合格">
                          <div className="flex items-center gap-2">
                            <div className="w-2 h-2 rounded-full bg-red-600"></div>
                            不合格 (60分以下)
                          </div>
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <label className="flex items-center gap-1">
                      <span className="text-red-500">*</span>
                      验收人
                    </label>
                    <Input
                      placeholder="请输入验收人姓名"
                      className="mt-2"
                      value={acceptanceData.inspector}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        inspector: e.target.value
                      })}
                    />
                  </div>

                  <div>
                    <label>验收意见</label>
                    <Textarea
                      placeholder="请填写验收意见，如发现问题请详细说明"
                      className="mt-2"
                      rows={4}
                      value={acceptanceData.comment}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        comment: e.target.value
                      })}
                    />
                  </div>

                  <div>
                    <label>存在问题</label>
                    <Textarea
                      placeholder="如有问题请详细描述（选填）"
                      className="mt-2"
                      rows={3}
                      value={acceptanceData.issues}
                      onChange={(e) => setAcceptanceData({
                        ...acceptanceData,
                        issues: e.target.value
                      })}
                    />
                  </div>
                </div>
              </Card>

              {/* 评分概览 */}
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">综合得分</p>
                    <p className="text-3xl font-medium text-green-600 mt-1">
                      {Math.round((acceptanceData.qualityScore + acceptanceData.efficiencyScore + acceptanceData.standardScore) / 3)}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-muted-foreground">验收等级</p>
                    <Badge className="mt-1 text-base px-3 py-1 bg-green-600">
                      {acceptanceData.rating}
                    </Badge>
                  </div>
                </div>
              </Card>

              <div className="flex gap-2 justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowAcceptanceDialog(false)}>
                  取消
                </Button>
                <Button 
                  className="bg-green-600 hover:bg-green-700"
                  onClick={handleSubmitAcceptanceEvaluation}
                >
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  提交验收并同步至农事操作
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 编辑任务对话框 */}
      <Dialog open={showEditTaskDialog} onOpenChange={setShowEditTaskDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>编辑任务</DialogTitle>
            <DialogDescription>
              修改任务的详细信息，包括基本信息、执行计划和农资需求
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 任务状态提示 */}
            {selectedTask && (
              <Card className="p-3 bg-blue-50 border-blue-200">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    {getStatusIcon(selectedTask.status)}
                    <div>
                      <p className="text-sm font-medium text-blue-900">当前状态：{selectedTask.status}</p>
                      <p className="text-xs text-blue-700 mt-0.5">
                        {selectedTask.source === '计划生成' && selectedTask.planId 
                          ? `来源：农事计划 (${selectedTask.planId})` 
                          : '来源：手动创建'}
                      </p>
                    </div>
                  </div>
                  <Badge className={getStatusColor(selectedTask.status)}>
                    {selectedTask.status}
                  </Badge>
                </div>
              </Card>
            )}

            {/* 基本信息 */}
            <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
              <h4 className="mb-3 flex items-center gap-2">
                <ClipboardCheck className="w-4 h-4 text-blue-600" />
                基本信息
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>任务名称 *</label>
                  <Input 
                    className="mt-2 bg-white"
                    placeholder="输入任务名称" 
                    value={taskForm.name}
                    onChange={(e) => setTaskForm({ ...taskForm, name: e.target.value })}
                  />
                </div>
                <div>
                  <label>任务类型 *</label>
                  <Select 
                    value={taskForm.type} 
                    onValueChange={(value: TaskType) => setTaskForm({ ...taskForm, type: value })}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="播种">播种</SelectItem>
                      <SelectItem value="施肥">施肥</SelectItem>
                      <SelectItem value="灌溉">灌溉</SelectItem>
                      <SelectItem value="除草">除草</SelectItem>
                      <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                      <SelectItem value="采收">采收</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 地块与人员 */}
            <div className="p-4 bg-green-50 rounded-lg border border-green-200">
              <h4 className="mb-3 flex items-center gap-2">
                <MapPin className="w-4 h-4 text-green-600" />
                地块与人员
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>执行地块 *</label>
                  <Input 
                    className="mt-2 bg-white"
                    placeholder="输入地块编号" 
                    value={taskForm.fieldId}
                    onChange={(e) => setTaskForm({ ...taskForm, fieldId: e.target.value })}
                  />
                </div>
                <div>
                  <label>地块名称 *</label>
                  <Input 
                    className="mt-2 bg-white"
                    placeholder="输入地块名称" 
                    value={taskForm.fieldName}
                    onChange={(e) => setTaskForm({ ...taskForm, fieldName: e.target.value })}
                  />
                </div>
                <div>
                  <label>负责人 *</label>
                  <Select 
                    value={taskForm.assignedTo} 
                    onValueChange={(value) => setTaskForm({ ...taskForm, assignedTo: value })}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue placeholder="选择负责人" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="张三">张三</SelectItem>
                      <SelectItem value="李四">李四</SelectItem>
                      <SelectItem value="王五">王五</SelectItem>
                      <SelectItem value="赵六">赵六</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <label>作业组</label>
                  <Input 
                    className="mt-2 bg-white"
                    placeholder="输入作业组名称" 
                    value={taskForm.teamName}
                    onChange={(e) => setTaskForm({ ...taskForm, teamName: e.target.value })}
                  />
                </div>
              </div>
            </div>

            {/* 时间计划 */}
            <div className="p-4 bg-purple-50 rounded-lg border border-purple-200">
              <h4 className="mb-3 flex items-center gap-2">
                <Clock className="w-4 h-4 text-purple-600" />
                时间计划
              </h4>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label>计划开始日期 *</label>
                  <Input 
                    className="mt-2 bg-white"
                    type="date" 
                    value={taskForm.plannedStartDate}
                    onChange={(e) => setTaskForm({ ...taskForm, plannedStartDate: e.target.value })}
                  />
                </div>
                <div>
                  <label>计划结束日期</label>
                  <Input 
                    className="mt-2 bg-white"
                    type="date" 
                    value={taskForm.plannedEndDate}
                    onChange={(e) => setTaskForm({ ...taskForm, plannedEndDate: e.target.value })}
                  />
                </div>
                <div>
                  <label>预计工时（小时）</label>
                  <Input 
                    className="mt-2 bg-white"
                    type="number" 
                    min="0"
                    value={taskForm.estimatedHours}
                    onChange={(e) => setTaskForm({ ...taskForm, estimatedHours: parseFloat(e.target.value) || 0 })}
                  />
                </div>
              </div>
            </div>

            {/* 任务描述 */}
            <div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
              <h4 className="mb-3 flex items-center gap-2">
                <FileText className="w-4 h-4 text-gray-600" />
                任务描述
              </h4>
              <div>
                <label>详细描述</label>
                <Textarea 
                  className="mt-2 bg-white"
                  placeholder="描述任务的目标、步骤和注意事项" 
                  rows={4}
                  value={taskForm.description}
                  onChange={(e) => setTaskForm({ ...taskForm, description: e.target.value })}
                />
              </div>
            </div>

            {/* 作业要求 */}
            <div className="p-4 bg-orange-50 rounded-lg border border-orange-200">
              <h4 className="mb-3 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-orange-600" />
                作业要求
              </h4>
              <div>
                <label>技术规范（每行一条）</label>
                <Textarea 
                  placeholder="例如：&#10;种子需提前浸种12-24小时&#10;播种深度控制在2-3cm&#10;行距保持30cm&#10;播种后及时覆土并轻压" 
                  className="mt-2 bg-white"
                  rows={5}
                  value={taskForm.requirements}
                  onChange={(e) => setTaskForm({ ...taskForm, requirements: e.target.value })}
                />
              </div>
            </div>

            {/* 农资需求 */}
            <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
              <h4 className="mb-3 flex items-center gap-2">
                <Package className="w-4 h-4 text-yellow-600" />
                农资需求
              </h4>
              <div className="space-y-3">
                {materials.map((material, index) => (
                  <div key={index} className="space-y-2">
                    <div className="flex gap-2">
                      <Input 
                        placeholder="农资名称" 
                        className="flex-1 bg-white"
                        value={material.name}
                        onChange={(e) => handleUpdateMaterial(index, 'name', e.target.value)}
                      />
                      <Input 
                        type="number" 
                        placeholder="数量" 
                        className="w-32 bg-white"
                        value={material.amount || ''}
                        onChange={(e) => handleUpdateMaterial(index, 'amount', parseFloat(e.target.value) || 0)}
                      />
                      <Select 
                        value={material.unit} 
                        onValueChange={(value) => handleUpdateMaterial(index, 'unit', value)}
                      >
                        <SelectTrigger className="w-24 bg-white">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="kg">kg</SelectItem>
                          <SelectItem value="L">L</SelectItem>
                          <SelectItem value="袋">袋</SelectItem>
                          <SelectItem value="瓶">瓶</SelectItem>
                        </SelectContent>
                      </Select>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleSelectFromInventory(index)}
                      >
                        <Package className="w-4 h-4" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleRemoveMaterial(index)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                    {material.currentStock !== undefined && (
                      <p className="text-xs text-muted-foreground ml-2 flex items-center gap-1">
                        <Package className="w-3 h-3" />
                        当前库存：{material.currentStock} {material.unit}
                        {material.amount > material.currentStock && (
                          <span className="text-red-600 ml-2">⚠️ 库存不足</span>
                        )}
                      </p>
                    )}
                  </div>
                ))}
                <Button 
                  variant="outline" 
                  className="w-full border-dashed"
                  onClick={handleAddMaterial}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加农资
                </Button>
                <p className="text-xs text-muted-foreground">
                  💡 可以手动输入或从农资库选择。列出完成任务所需的种子、肥料、农药等农资及用量
                </p>
              </div>
            </div>

            {/* 安全注意事项 */}
            <div className="p-4 bg-red-50 rounded-lg border border-red-200">
              <h4 className="mb-3 flex items-center gap-2">
                <Shield className="w-4 h-4 text-red-600" />
                安全注意事项
              </h4>
              <div>
                <label>安全规范（每行一条）</label>
                <Textarea 
                  placeholder="例如：&#10;作业时佩戴手套和口罩&#10;注意防止滑倒&#10;避免在雨天作业&#10;使用农药时穿戴防护服" 
                  className="mt-2 bg-white"
                  rows={5}
                  value={taskForm.safetyNotes}
                  onChange={(e) => setTaskForm({ ...taskForm, safetyNotes: e.target.value })}
                />
                <p className="text-xs text-red-800 mt-1">
                  ⚠️ 重要：列出所有安全隐患和防护措施，确保作业人员安全
                </p>
              </div>
            </div>

            {/* 关联计划信息（只读） */}
            {selectedTask && selectedTask.planId && (
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-start gap-2">
                  <Calendar className="w-4 h-4 text-green-600 mt-1" />
                  <div className="flex-1">
                    <label className="text-green-800">关联的农事计划</label>
                    <p className="text-sm text-green-700 mt-1">
                      计划ID: {selectedTask.planId}
                    </p>
                    <p className="text-xs text-green-600 mt-1">
                      此任务由农事计划自动生成，修改后仍保持关联关系
                    </p>
                  </div>
                </div>
              </Card>
            )}

            {/* 操作按钮 */}
            <div className="flex gap-2 justify-end pt-4 border-t">
              <Button variant="outline" onClick={() => setShowEditTaskDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleUpdateTask}>
                <CheckCircle2 className="w-4 h-4 mr-2" />
                保存修改
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 农资选择器对话框 */}
      <Dialog open={showMaterialSelector} onOpenChange={setShowMaterialSelector}>
        <DialogContent className="max-w-4xl max-h-[80vh]">
          <DialogHeader>
            <DialogTitle>从农资库选择</DialogTitle>
            <DialogDescription>
              选择现有的农资物料，系统将自动填充名称和单位信息
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            {/* 农资库统计 */}
            <div className="grid grid-cols-4 gap-4">
              <Card className="p-4 bg-blue-50 border-blue-200">
                <p className="text-xs text-muted-foreground">可用农资</p>
                <p className="mt-1 text-2xl text-blue-600">{availableMaterials.length}</p>
              </Card>
              <Card className="p-4 bg-green-50 border-green-200">
                <p className="text-xs text-muted-foreground">种子/化肥</p>
                <p className="mt-1 text-2xl text-green-600">
                  {availableMaterials.filter(m => m.type === '种子' || m.type === '化肥').length}
                </p>
              </Card>
              <Card className="p-4 bg-orange-50 border-orange-200">
                <p className="text-xs text-muted-foreground">农药</p>
                <p className="mt-1 text-2xl text-orange-600">
                  {availableMaterials.filter(m => m.type === '农药').length}
                </p>
              </Card>
              <Card className="p-4 bg-purple-50 border-purple-200">
                <p className="text-xs text-muted-foreground">其他</p>
                <p className="mt-1 text-2xl text-purple-600">
                  {availableMaterials.filter(m => m.type !== '种子' && m.type !== '化肥' && m.type !== '农药').length}
                </p>
              </Card>
            </div>

            {/* 农资列表 */}
            <div className="max-h-96 overflow-y-auto space-y-2">
              {availableMaterials.length > 0 ? (
                availableMaterials.map((material) => (
                  <Card 
                    key={material.id}
                    className="p-4 cursor-pointer hover:border-green-500 transition-colors"
                    onClick={() => handleMaterialSelect(material)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4>{material.name}</h4>
                          <Badge 
                            className={
                              material.type === '种子' ? 'bg-green-500' :
                              material.type === '化肥' ? 'bg-blue-500' :
                              material.type === '农药' ? 'bg-red-500' :
                              material.type === '配件' ? 'bg-purple-500' :
                              material.type === '耗材' ? 'bg-orange-500' :
                              'bg-gray-500'
                            }
                            variant="outline"
                          >
                            {material.type}
                          </Badge>
                          <Badge 
                            className={
                              material.status === '正常' ? 'bg-green-500' :
                              material.status === '库存预警' ? 'bg-orange-500' :
                              material.status === '临期预警' ? 'bg-yellow-500' :
                              'bg-red-500'
                            }
                          >
                            {material.status}
                          </Badge>
                        </div>
                        <div className="grid grid-cols-4 gap-4 text-sm text-muted-foreground">
                          <div>
                            <span className="text-xs">编码：</span>
                            <span>{material.code}</span>
                          </div>
                          <div>
                            <span className="text-xs">规格：</span>
                            <span>{material.spec}</span>
                          </div>
                          <div>
                            <span className="text-xs">供应商：</span>
                            <span>{material.supplier}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Package className="w-3 h-3" />
                            <span className="text-xs">库存：</span>
                            <span className={material.currentStock < 10 ? 'text-red-600 font-medium' : ''}>
                              {material.currentStock} {material.unit}
                            </span>
                          </div>
                        </div>
                      </div>
                      <Button size="sm" variant="outline">
                        选择
                      </Button>
                    </div>
                  </Card>
                ))
              ) : (
                <Card className="p-8 text-center">
                  <Package className="w-12 h-12 mx-auto text-gray-400 mb-2" />
                  <p className="text-muted-foreground mb-2">暂无可用农资</p>
                  <p className="text-xs text-muted-foreground">
                    请先在"农资管理"中添加农资物料
                  </p>
                </Card>
              )}
            </div>

            {/* 提示信息 */}
            <Card className="p-3 bg-blue-50 border-blue-200">
              <div className="flex items-start gap-2 text-sm text-blue-800">
                <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium">使用说明</p>
                  <ul className="mt-1 space-y-1 text-xs">
                    <li>• 点击农资卡片即可选择该农资</li>
                    <li>• 选择后将自动填充农资名称和单位，您只需输入所需数量</li>
                    <li>• 系统会显示当前库存，如果用量超出库存会给出提示</li>
                    <li>• 也可以手动输入农资信息，不一定要从库中选择</li>
                  </ul>
                </div>
              </div>
            </Card>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
