import { useState, useEffect, useRef } 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, DialogTrigger } from '../ui/dialog';
import { Progress } from '../ui/progress';
import {
  Calendar,
  Plus,
  Edit,
  Trash2,
  FileText,
  Users,
  MapPin,
  Sprout,
  Clock,
  CheckCircle2,
  AlertTriangle,
  PlayCircle,
  Circle,
  Filter,
  Search,
  ChevronRight,
  TrendingUp,
  Activity,
  Target,
  Zap,
  Package,
  User,
  ClipboardList,
  Calculator,
  Layers,
  UserCheck,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { operationTypesData, OperationType } from '../../lib/operationTypes';

interface OperationPlanningProps {
  activePath?: string;
}

type PlanType = '年度计划' | '季度计划';
type ActivityType = OperationType; // 使用农事执行的农事类型
type PlanStatus = '草稿' | '已发布' | '进行中' | '已完成';
type WorkOrderStatus = '待开始' | '进行中' | '已完成' | '已延误';

interface Activity {
  id: string;
  name: string;
  type: ActivityType;
  startDate: string;
  endDate: string;
  duration: number;
  description: string;
}

interface Plan {
  id: string;
  name: string;
  type: PlanType;
  year: number;
  quarter?: number;
  crop: string;
  variety: string;
  plannedArea: number;
  startDate: string;
  endDate: string;
  activities: Activity[];
  status: PlanStatus;
  createdBy: string;
  createdAt: string;
}

interface WorkOrder {
  id: string;
  planId: string;
  planName: string;
  activityType: ActivityType;
  fieldId: string;
  fieldName: string;
  assignedTo: string;
  teamName: string;
  scheduledDate: string;
  area: number;
  estimatedHours: number;
  estimatedMaterials: { name: string; amount: number; unit: string }[];
  status: WorkOrderStatus;
  actualHours?: number;
  completedDate?: string;
  notes?: string;
}

export function OperationPlanning({ activePath }: OperationPlanningProps) {
  const [activeTab, setActiveTab] = useState('creation');
  const [showPlanDialog, setShowPlanDialog] = useState(false);
  const [showWorkOrderDialog, setShowWorkOrderDialog] = useState(false);
  const [showPlanDetailDialog, setShowPlanDetailDialog] = useState(false);
  const [showWorkOrderGenerateDialog, setShowWorkOrderGenerateDialog] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState<WorkOrder | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [planDialogTab, setPlanDialogTab] = useState('basic');
  const [editingActivities, setEditingActivities] = useState<Activity[]>([]);
  
  // 甘特图月份选择
  const [selectedMonth, setSelectedMonth] = useState(new Date());
  const [isDragging, setIsDragging] = useState(false);
  const [dragInfo, setDragInfo] = useState<{
    activityIndex: number;
    type: 'move' | 'resize-left' | 'resize-right';
    startX: number;
    originalStartDate: string;
    originalEndDate: string;
  } | null>(null);
  const ganttRef = useRef<HTMLDivElement>(null);
  
  // 时间轴拖动平移
  const [isTimelineDragging, setIsTimelineDragging] = useState(false);
  const [timelineDragStart, setTimelineDragStart] = useState({ x: 0, startMonth: new Date() });

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

  // 模拟计划数据
  const [plans, setPlans] = useState<Plan[]>([
    {
      id: 'plan-1',
      name: '2024年春季水稻种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 1,
      crop: '水稻',
      variety: '优质稻1号',
      plannedArea: 200,
      startDate: '2024-03-01',
      endDate: '2024-06-30',
      status: '进行中',
      createdBy: '张三',
      createdAt: '2024-02-15',
      activities: [
        {
          id: 'act-1',
          name: '春季播种',
          type: '播种',
          startDate: '2024-03-01',
          endDate: '2024-03-15',
          duration: 15,
          description: '进行水稻种子浸种催芽并播种',
        },
        {
          id: 'act-2',
          name: '基肥施用',
          type: '施肥',
          startDate: '2024-03-10',
          endDate: '2024-03-20',
          duration: 11,
          description: '施用有机肥和复合肥作为基肥',
        },
        {
          id: 'act-3',
          name: '灌溉管理',
          type: '灌溉',
          startDate: '2024-03-15',
          endDate: '2024-06-15',
          duration: 93,
          description: '根据生长期进行科学灌溉',
        },
        {
          id: 'act-4',
          name: '追肥',
          type: '施肥',
          startDate: '2024-04-15',
          endDate: '2024-04-25',
          duration: 11,
          description: '分蘖期追肥',
        },
        {
          id: 'act-5',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-05-01',
          endDate: '2024-05-31',
          duration: 31,
          description: '预防和治理水稻常见病虫害',
        },
        {
          id: 'act-6',
          name: '收获',
          type: '采收',
          startDate: '2024-06-20',
          endDate: '2024-06-30',
          duration: 11,
          description: '水稻成熟收获',
        },
      ],
    },
    {
      id: 'plan-2',
      name: '2024年夏季玉米种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 2,
      crop: '玉米',
      variety: '登海605',
      plannedArea: 150,
      startDate: '2024-05-01',
      endDate: '2024-08-31',
      status: '进行中',
      createdBy: '李四',
      createdAt: '2024-04-10',
      activities: [
        {
          id: 'act-7',
          name: '夏玉米播种',
          type: '播种',
          startDate: '2024-05-01',
          endDate: '2024-05-10',
          duration: 10,
          description: '夏玉米播种',
        },
        {
          id: 'act-8',
          name: '施基肥',
          type: '施肥',
          startDate: '2024-05-05',
          endDate: '2024-05-15',
          duration: 11,
          description: '施用底肥',
        },
        {
          id: 'act-9',
          name: '田间除草',
          type: '除草',
          startDate: '2024-06-01',
          endDate: '2024-06-10',
          duration: 10,
          description: '玉米苗期除草',
        },
        {
          id: 'act-10',
          name: '追肥及灌溉',
          type: '施肥',
          startDate: '2024-06-15',
          endDate: '2024-06-25',
          duration: 11,
          description: '拔节期追肥及灌溉',
        },
        {
          id: 'act-11',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-07-01',
          endDate: '2024-07-20',
          duration: 20,
          description: '预防玉米螟等害虫',
        },
        {
          id: 'act-12',
          name: '收获',
          type: '采收',
          startDate: '2024-08-20',
          endDate: '2024-08-31',
          duration: 12,
          description: '玉米成熟收获',
        },
      ],
    },
    {
      id: 'plan-3',
      name: '2024年秋季小麦种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 3,
      crop: '小麦',
      variety: '济麦22',
      plannedArea: 180,
      startDate: '2024-09-01',
      endDate: '2024-12-31',
      status: '进行中',
      createdBy: '王五',
      createdAt: '2024-08-20',
      activities: [
        {
          id: 'act-13',
          name: '整地施基肥',
          type: '施肥',
          startDate: '2024-09-01',
          endDate: '2024-09-15',
          duration: 15,
          description: '整地并施用有机肥作为基肥',
        },
        {
          id: 'act-14',
          name: '秋播',
          type: '播种',
          startDate: '2024-09-20',
          endDate: '2024-10-05',
          duration: 16,
          description: '小麦播种',
        },
        {
          id: 'act-15',
          name: '冬前灌溉',
          type: '灌溉',
          startDate: '2024-10-20',
          endDate: '2024-10-30',
          duration: 11,
          description: '越冬前浇灌冻水',
        },
        {
          id: 'act-16',
          name: '除草',
          type: '除草',
          startDate: '2024-11-01',
          endDate: '2024-11-10',
          duration: 10,
          description: '冬前化学除草',
        },
        {
          id: 'act-17',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-11-15',
          endDate: '2024-11-30',
          duration: 16,
          description: '预防小麦纹枯病',
        },
      ],
    },
    {
      id: 'plan-4',
      name: '2024年大豆种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 2,
      crop: '大豆',
      variety: '中黄39',
      plannedArea: 120,
      startDate: '2024-06-01',
      endDate: '2024-09-30',
      status: '进行中',
      createdBy: '赵六',
      createdAt: '2024-05-15',
      activities: [
        {
          id: 'act-18',
          name: '播种',
          type: '播种',
          startDate: '2024-06-01',
          endDate: '2024-06-10',
          duration: 10,
          description: '夏大豆播种',
        },
        {
          id: 'act-19',
          name: '苗期施肥',
          type: '施肥',
          startDate: '2024-06-20',
          endDate: '2024-06-25',
          duration: 6,
          description: '苗期追施氮肥',
        },
        {
          id: 'act-20',
          name: '中耕除草',
          type: '除草',
          startDate: '2024-07-01',
          endDate: '2024-07-15',
          duration: 15,
          description: '中耕除草松土',
        },
        {
          id: 'act-21',
          name: '开花期管理',
          type: '灌溉',
          startDate: '2024-07-20',
          endDate: '2024-08-10',
          duration: 22,
          description: '开花结荚期灌溉管理',
        },
        {
          id: 'act-22',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-08-15',
          endDate: '2024-08-31',
          duration: 17,
          description: '防治豆荚螟等害虫',
        },
        {
          id: 'act-23',
          name: '收获',
          type: '采收',
          startDate: '2024-09-20',
          endDate: '2024-09-30',
          duration: 11,
          description: '大豆成熟收获',
        },
      ],
    },
    {
      id: 'plan-5',
      name: '2024年马铃薯春季种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 1,
      crop: '马铃薯',
      variety: '克新一号',
      plannedArea: 80,
      startDate: '2024-03-15',
      endDate: '2024-07-31',
      status: '进行中',
      createdBy: '孙七',
      createdAt: '2024-03-01',
      activities: [
        {
          id: 'act-24',
          name: '播种',
          type: '播种',
          startDate: '2024-03-15',
          endDate: '2024-03-25',
          duration: 11,
          description: '春季马铃薯播种',
        },
        {
          id: 'act-25',
          name: '出苗期管理',
          type: '灌溉',
          startDate: '2024-04-01',
          endDate: '2024-04-15',
          duration: 15,
          description: '出苗期浇水管理',
        },
        {
          id: 'act-26',
          name: '中耕培土',
          type: '除草',
          startDate: '2024-04-20',
          endDate: '2024-05-05',
          duration: 16,
          description: '中耕除草并培土',
        },
        {
          id: 'act-27',
          name: '追肥',
          type: '施肥',
          startDate: '2024-05-10',
          endDate: '2024-05-20',
          duration: 11,
          description: '块茎膨大期追肥',
        },
        {
          id: 'act-28',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-06-01',
          endDate: '2024-06-30',
          duration: 30,
          description: '防治晚疫病和地下害虫',
        },
        {
          id: 'act-29',
          name: '收获',
          type: '采收',
          startDate: '2024-07-15',
          endDate: '2024-07-31',
          duration: 17,
          description: '马铃薯成熟收获',
        },
      ],
    },
    {
      id: 'plan-6',
      name: '2024年全年蔬菜种植计划',
      type: '年度计划',
      year: 2024,
      crop: '多种蔬菜',
      variety: '时令蔬菜',
      plannedArea: 100,
      startDate: '2024-01-01',
      endDate: '2024-12-31',
      status: '草稿',
      createdBy: '周八',
      createdAt: '2024-01-05',
      activities: [],
    },
    // 新增4条未生成工单的计划
    {
      id: 'plan-7',
      name: '2024年秋季花生种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 3,
      crop: '花生',
      variety: '鲁花11号',
      plannedArea: 95,
      startDate: '2024-07-10',
      endDate: '2024-10-31',
      status: '已发布',
      createdBy: '张三',
      createdAt: '2024-06-28',
      activities: [
        {
          id: 'act-30',
          name: '整地施基肥',
          type: '施肥',
          startDate: '2024-07-10',
          endDate: '2024-07-20',
          duration: 11,
          description: '整地并施用有机肥和复合肥',
        },
        {
          id: 'act-31',
          name: '播种',
          type: '播种',
          startDate: '2024-07-25',
          endDate: '2024-08-05',
          duration: 12,
          description: '花生播种作业',
        },
        {
          id: 'act-32',
          name: '苗期管理',
          type: '灌溉',
          startDate: '2024-08-10',
          endDate: '2024-08-25',
          duration: 16,
          description: '苗期灌溉及田间管理',
        },
        {
          id: 'act-33',
          name: '中耕除草',
          type: '除草',
          startDate: '2024-08-28',
          endDate: '2024-09-10',
          duration: 14,
          description: '中耕除草松土',
        },
        {
          id: 'act-34',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-09-15',
          endDate: '2024-09-30',
          duration: 16,
          description: '防治叶斑病和地下害虫',
        },
        {
          id: 'act-35',
          name: '收获',
          type: '采收',
          startDate: '2024-10-15',
          endDate: '2024-10-31',
          duration: 17,
          description: '花生成熟收获',
        },
      ],
    },
    {
      id: 'plan-8',
      name: '2024年冬季油菜种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 4,
      crop: '油菜',
      variety: '中油杂19',
      plannedArea: 130,
      startDate: '2024-09-20',
      endDate: '2024-12-31',
      status: '已发布',
      createdBy: '李四',
      createdAt: '2024-09-05',
      activities: [
        {
          id: 'act-36',
          name: '整地作畦',
          type: '施肥',
          startDate: '2024-09-20',
          endDate: '2024-09-30',
          duration: 11,
          description: '整地施底肥并作畦',
        },
        {
          id: 'act-37',
          name: '播种',
          type: '播种',
          startDate: '2024-10-05',
          endDate: '2024-10-15',
          duration: 11,
          description: '油菜直播或移栽',
        },
        {
          id: 'act-38',
          name: '间苗定苗',
          type: '除草',
          startDate: '2024-10-20',
          endDate: '2024-10-30',
          duration: 11,
          description: '间苗定苗及除草',
        },
        {
          id: 'act-39',
          name: '苗期追肥',
          type: '施肥',
          startDate: '2024-11-05',
          endDate: '2024-11-15',
          duration: 11,
          description: '苗期追施复合肥',
        },
        {
          id: 'act-40',
          name: '冬前管理',
          type: '灌溉',
          startDate: '2024-11-20',
          endDate: '2024-12-10',
          duration: 21,
          description: '冬前浇灌冻水',
        },
        {
          id: 'act-41',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-12-15',
          endDate: '2024-12-31',
          duration: 17,
          description: '预防菌核病和蚜虫',
        },
      ],
    },
    {
      id: 'plan-9',
      name: '2024年高粱种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 2,
      crop: '高粱',
      variety: '辽杂19号',
      plannedArea: 75,
      startDate: '2024-05-15',
      endDate: '2024-09-15',
      status: '进行中',
      createdBy: '王五',
      createdAt: '2024-05-01',
      activities: [
        {
          id: 'act-42',
          name: '播前整地',
          type: '施肥',
          startDate: '2024-05-15',
          endDate: '2024-05-25',
          duration: 11,
          description: '深耕整地施基肥',
        },
        {
          id: 'act-43',
          name: '播种',
          type: '播种',
          startDate: '2024-05-28',
          endDate: '2024-06-05',
          duration: 9,
          description: '高粱种子播种',
        },
        {
          id: 'act-44',
          name: '间苗定苗',
          type: '除草',
          startDate: '2024-06-10',
          endDate: '2024-06-20',
          duration: 11,
          description: '间苗定苗及除草',
        },
        {
          id: 'act-45',
          name: '追肥管理',
          type: '施肥',
          startDate: '2024-06-25',
          endDate: '2024-07-05',
          duration: 11,
          description: '拔节期追施氮肥',
        },
        {
          id: 'act-46',
          name: '灌溉作业',
          type: '灌溉',
          startDate: '2024-07-10',
          endDate: '2024-07-30',
          duration: 21,
          description: '抽穗期灌溉管理',
        },
        {
          id: 'act-47',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-08-01',
          endDate: '2024-08-20',
          duration: 20,
          description: '防治高粱蚜虫和黑穗病',
        },
        {
          id: 'act-48',
          name: '收获',
          type: '采收',
          startDate: '2024-09-01',
          endDate: '2024-09-15',
          duration: 15,
          description: '高粱成熟收获',
        },
      ],
    },
    {
      id: 'plan-10',
      name: '2024年红薯种植计划',
      type: '季度计划',
      year: 2024,
      quarter: 2,
      crop: '红薯',
      variety: '烟薯25',
      plannedArea: 65,
      startDate: '2024-05-01',
      endDate: '2024-10-20',
      status: '已发布',
      createdBy: '赵六',
      createdAt: '2024-04-18',
      activities: [
        {
          id: 'act-49',
          name: '起垄施基肥',
          type: '施肥',
          startDate: '2024-05-01',
          endDate: '2024-05-10',
          duration: 10,
          description: '起垄并施用有机肥',
        },
        {
          id: 'act-50',
          name: '扦插栽苗',
          type: '播种',
          startDate: '2024-05-15',
          endDate: '2024-05-25',
          duration: 11,
          description: '红薯秧苗扦插',
        },
        {
          id: 'act-51',
          name: '缓苗期管理',
          type: '灌溉',
          startDate: '2024-05-28',
          endDate: '2024-06-10',
          duration: 14,
          description: '缓苗期浇水管理',
        },
        {
          id: 'act-52',
          name: '中耕除草',
          type: '除草',
          startDate: '2024-06-15',
          endDate: '2024-06-28',
          duration: 14,
          description: '中耕除草松土',
        },
        {
          id: 'act-53',
          name: '膨大期追肥',
          type: '施肥',
          startDate: '2024-07-05',
          endDate: '2024-07-15',
          duration: 11,
          description: '薯块膨大期追施钾肥',
        },
        {
          id: 'act-54',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2024-08-01',
          endDate: '2024-08-31',
          duration: 31,
          description: '防治地下害虫和病害',
        },
        {
          id: 'act-55',
          name: '收获',
          type: '采收',
          startDate: '2024-10-05',
          endDate: '2024-10-20',
          duration: 16,
          description: '红薯成熟收获',
        },
      ],
    },
  ]);

  // 模拟地块数据（从地块管理模块获取）
  const mockFields = [
    { id: 'field-1', name: '东区1号地', area: 50.5 },
    { id: 'field-2', name: '西区2号地', area: 45.2 },
    { id: 'field-3', name: '南区3号地', area: 62.8 },
    { id: 'field-4', name: '北区4号地', area: 38.5 },
    { id: 'field-5', name: '中央5号地', area: 55.0 },
  ];

  // 模拟班组数据（从人员管理模块获取）
  const mockTeams = [
    { team: '第一作业组', leader: '张三', specialty: ['播种', '灌溉', '采收'] },
    { team: '第二作业组', leader: '李四', specialty: ['施肥', '除草'] },
    { team: '第三作业组', leader: '王五', specialty: ['病虫害防治', '除草'] },
    { team: '第四作业组', leader: '赵六', specialty: ['播种', '施肥', '采收'] },
  ];

  // 模拟工单数据
  const [workOrders, setWorkOrders] = useState<WorkOrder[]>([
    // 水稻计划的工单
    {
      id: 'wo-1',
      planId: 'plan-1',
      planName: '2024年春季水稻种植计划',
      activityType: '播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-03-01',
      area: 50.5,
      estimatedHours: 24,
      estimatedMaterials: [
        { name: '水稻种子', amount: 15, unit: 'kg' },
        { name: '浸种剂', amount: 0.5, unit: 'L' },
      ],
      status: '已完成',
      actualHours: 22,
      completedDate: '2024-03-02',
      notes: '播种顺利完成，种子发芽率良好',
    },
    {
      id: 'wo-2',
      planId: 'plan-1',
      planName: '2024年春季水稻种植计划',
      activityType: '施肥',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-03-10',
      area: 50.5,
      estimatedHours: 16,
      estimatedMaterials: [
        { name: '有机肥', amount: 500, unit: 'kg' },
        { name: '复合肥', amount: 200, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 15,
      completedDate: '2024-03-20',
      notes: '基肥施用完成',
    },
    {
      id: 'wo-3',
      planId: 'plan-1',
      planName: '2024年春季水稻种植计划',
      activityType: '灌溉',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '王五',
      teamName: '第一作业组',
      scheduledDate: '2024-03-15',
      area: 45.2,
      estimatedHours: 8,
      estimatedMaterials: [],
      status: '进行中',
      actualHours: 4,
      notes: '灌溉进行中',
    },
    {
      id: 'wo-4',
      planId: 'plan-1',
      planName: '2024年春季水稻种植计划',
      activityType: '施肥',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-04-15',
      area: 50.5,
      estimatedHours: 12,
      estimatedMaterials: [
        { name: '尿素', amount: 150, unit: 'kg' },
      ],
      status: '待开始',
    },
    
    // 玉米计划的工单
    {
      id: 'wo-5',
      planId: 'plan-2',
      planName: '2024年夏季玉米种植计划',
      activityType: '播种',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-05-01',
      area: 62.8,
      estimatedHours: 20,
      estimatedMaterials: [
        { name: '玉米种子', amount: 12, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 19,
      completedDate: '2024-05-10',
      notes: '播种完成，出苗良好',
    },
    {
      id: 'wo-6',
      planId: 'plan-2',
      planName: '2024年夏季玉米种植计划',
      activityType: '施肥',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-05-05',
      area: 62.8,
      estimatedHours: 16,
      estimatedMaterials: [
        { name: '复合肥', amount: 300, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 14,
      completedDate: '2024-05-15',
      notes: '基肥施用完成',
    },
    {
      id: 'wo-7',
      planId: 'plan-2',
      planName: '2024年夏季玉米种植计划',
      activityType: '除草',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      assignedTo: '王五',
      teamName: '第三作业组',
      scheduledDate: '2024-06-01',
      area: 62.8,
      estimatedHours: 14,
      estimatedMaterials: [
        { name: '除草剂', amount: 2, unit: 'L' },
      ],
      status: '已完成',
      actualHours: 13,
      completedDate: '2024-06-10',
      notes: '除草完成',
    },
    {
      id: 'wo-8',
      planId: 'plan-2',
      planName: '2024年夏季玉米种植计划',
      activityType: '施肥',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-06-15',
      area: 62.8,
      estimatedHours: 12,
      estimatedMaterials: [
        { name: '尿素', amount: 200, unit: 'kg' },
      ],
      status: '进行中',
      actualHours: 6,
      notes: '追肥进行中',
    },
    {
      id: 'wo-9',
      planId: 'plan-2',
      planName: '2024年夏季玉米种植计划',
      activityType: '病虫害防治',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      assignedTo: '赵六',
      teamName: '第三作业组',
      scheduledDate: '2024-07-01',
      area: 62.8,
      estimatedHours: 18,
      estimatedMaterials: [
        { name: '杀虫剂', amount: 3, unit: 'L' },
      ],
      status: '待开始',
    },
    
    // 小麦计划的工单
    {
      id: 'wo-10',
      planId: 'plan-3',
      planName: '2024年秋季小麦种植计划',
      activityType: '施肥',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-09-01',
      area: 38.5,
      estimatedHours: 14,
      estimatedMaterials: [
        { name: '有机肥', amount: 400, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 13,
      completedDate: '2024-09-15',
      notes: '整地施肥完成',
    },
    {
      id: 'wo-11',
      planId: 'plan-3',
      planName: '2024年秋季小麦种植计划',
      activityType: '播种',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-09-20',
      area: 38.5,
      estimatedHours: 18,
      estimatedMaterials: [
        { name: '小麦种子', amount: 25, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 16,
      completedDate: '2024-10-05',
      notes: '秋播完成',
    },
    {
      id: 'wo-12',
      planId: 'plan-3',
      planName: '2024年秋季小麦种植计划',
      activityType: '灌溉',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      assignedTo: '王五',
      teamName: '第一作业组',
      scheduledDate: '2024-10-20',
      area: 38.5,
      estimatedHours: 10,
      estimatedMaterials: [],
      status: '进行中',
      actualHours: 5,
      notes: '冬前灌溉进行中',
    },
    {
      id: 'wo-13',
      planId: 'plan-3',
      planName: '2024年秋季小麦种植计划',
      activityType: '除草',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      assignedTo: '赵六',
      teamName: '第三作业组',
      scheduledDate: '2024-11-01',
      area: 38.5,
      estimatedHours: 8,
      estimatedMaterials: [
        { name: '除草剂', amount: 1.5, unit: 'L' },
      ],
      status: '待开始',
    },
    
    // 大豆计划的工单
    {
      id: 'wo-14',
      planId: 'plan-4',
      planName: '2024年大豆种植计划',
      activityType: '播种',
      fieldId: 'field-5',
      fieldName: '中央5号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-06-01',
      area: 55.0,
      estimatedHours: 16,
      estimatedMaterials: [
        { name: '大豆种子', amount: 18, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 15,
      completedDate: '2024-06-10',
      notes: '播种完成',
    },
    {
      id: 'wo-15',
      planId: 'plan-4',
      planName: '2024年大豆种植计划',
      activityType: '施肥',
      fieldId: 'field-5',
      fieldName: '中央5号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-06-20',
      area: 55.0,
      estimatedHours: 10,
      estimatedMaterials: [
        { name: '氮肥', amount: 100, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 9,
      completedDate: '2024-06-25',
      notes: '苗期施肥完成',
    },
    {
      id: 'wo-16',
      planId: 'plan-4',
      planName: '2024年大豆种植计划',
      activityType: '除草',
      fieldId: 'field-5',
      fieldName: '中央5号地',
      assignedTo: '王五',
      teamName: '第三作业组',
      scheduledDate: '2024-07-01',
      area: 55.0,
      estimatedHours: 12,
      estimatedMaterials: [],
      status: '已完成',
      actualHours: 11,
      completedDate: '2024-07-15',
      notes: '中耕除草完成',
    },
    {
      id: 'wo-17',
      planId: 'plan-4',
      planName: '2024年大豆种植计划',
      activityType: '灌溉',
      fieldId: 'field-5',
      fieldName: '中央5号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-07-20',
      area: 55.0,
      estimatedHours: 14,
      estimatedMaterials: [],
      status: '进行中',
      actualHours: 7,
      notes: '开花期灌溉进行中',
    },
    {
      id: 'wo-18',
      planId: 'plan-4',
      planName: '2024年大豆种植计划',
      activityType: '病虫害防治',
      fieldId: 'field-5',
      fieldName: '中央5号地',
      assignedTo: '赵六',
      teamName: '第三作业组',
      scheduledDate: '2024-08-15',
      area: 55.0,
      estimatedHours: 16,
      estimatedMaterials: [
        { name: '杀虫剂', amount: 2.5, unit: 'L' },
      ],
      status: '待开始',
    },
    
    // 马铃薯计划的工单
    {
      id: 'wo-19',
      planId: 'plan-5',
      planName: '2024年马铃薯春季种植计划',
      activityType: '播种',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '张三',
      teamName: '第一作业组',
      scheduledDate: '2024-03-15',
      area: 45.2,
      estimatedHours: 18,
      estimatedMaterials: [
        { name: '马铃薯种薯', amount: 200, unit: 'kg' },
      ],
      status: '已完成',
      actualHours: 17,
      completedDate: '2024-03-25',
      notes: '播种完成',
    },
    {
      id: 'wo-20',
      planId: 'plan-5',
      planName: '2024年马铃薯春季种植计划',
      activityType: '灌溉',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '王五',
      teamName: '第一作业组',
      scheduledDate: '2024-04-01',
      area: 45.2,
      estimatedHours: 10,
      estimatedMaterials: [],
      status: '已完成',
      actualHours: 9,
      completedDate: '2024-04-15',
      notes: '出苗期浇水完成',
    },
    {
      id: 'wo-21',
      planId: 'plan-5',
      planName: '2024年马铃薯春季种植计划',
      activityType: '除草',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '赵六',
      teamName: '第三作业组',
      scheduledDate: '2024-04-20',
      area: 45.2,
      estimatedHours: 14,
      estimatedMaterials: [],
      status: '已完成',
      actualHours: 13,
      completedDate: '2024-05-05',
      notes: '中耕培土完成',
    },
    {
      id: 'wo-22',
      planId: 'plan-5',
      planName: '2024年马铃薯春季种植计划',
      activityType: '施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '李四',
      teamName: '第二作业组',
      scheduledDate: '2024-05-10',
      area: 45.2,
      estimatedHours: 12,
      estimatedMaterials: [
        { name: '钾肥', amount: 150, unit: 'kg' },
      ],
      status: '进行中',
      actualHours: 6,
      notes: '追肥进行中',
    },
    {
      id: 'wo-23',
      planId: 'plan-5',
      planName: '2024年马铃薯春季种植计划',
      activityType: '病虫害防治',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      assignedTo: '赵六',
      teamName: '第三作业组',
      scheduledDate: '2024-06-01',
      area: 45.2,
      estimatedHours: 20,
      estimatedMaterials: [
        { name: '杀菌剂', amount: 2, unit: 'L' },
        { name: '杀虫剂', amount: 1.5, unit: 'L' },
      ],
      status: '待开始',
    },
  ]);

  const getStatusColor = (status: PlanStatus | WorkOrderStatus) => {
    switch (status) {
      case '草稿': return 'bg-muted-foreground text-primary-foreground';
      case '已发布': return 'bg-info text-primary-foreground';
      case '待开始': return 'bg-accent text-primary-foreground';
      case '进行中': return 'bg-warning text-primary-foreground';
      case '已完成': return 'bg-success text-primary-foreground';
      case '已延误': return 'bg-error text-primary-foreground';
      default: return 'bg-muted-foreground text-primary-foreground';
    }
  };

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

  const getActivityColor = (type: ActivityType) => {
    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-accent-muted text-accent-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 [historyTemplates] = useState<Plan[]>([
    {
      id: 'template-1',
      name: '2023年春季水稻标准种植计划',
      type: '季度计划',
      year: 2023,
      quarter: 1,
      crop: '水稻',
      variety: '优质稻1号',
      plannedArea: 200,
      startDate: '2023-03-01',
      endDate: '2023-06-30',
      status: '已完成',
      createdBy: '张三',
      createdAt: '2023-02-15',
      activities: [
        {
          id: 'tpl-act-1',
          name: '春季播种',
          type: '播种',
          startDate: '2023-03-01',
          endDate: '2023-03-15',
          duration: 15,
          description: '进行水稻种子浸种催芽并播种',
        },
        {
          id: 'tpl-act-2',
          name: '基肥施用',
          type: '施肥',
          startDate: '2023-03-10',
          endDate: '2023-03-20',
          duration: 11,
          description: '施用有机肥和复合肥作为基肥',
        },
        {
          id: 'tpl-act-3',
          name: '灌溉管理',
          type: '灌溉',
          startDate: '2023-03-15',
          endDate: '2023-06-15',
          duration: 93,
          description: '根据生长期进行科学灌溉',
        },
        {
          id: 'tpl-act-4',
          name: '追肥',
          type: '施肥',
          startDate: '2023-04-15',
          endDate: '2023-04-25',
          duration: 11,
          description: '分蘖期追肥',
        },
        {
          id: 'tpl-act-5',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2023-05-01',
          endDate: '2023-05-31',
          duration: 31,
          description: '预防和治理水稻常见病虫害',
        },
        {
          id: 'tpl-act-6',
          name: '收获',
          type: '采收',
          startDate: '2023-06-20',
          endDate: '2023-06-30',
          duration: 11,
          description: '水稻成熟收获',
        },
      ],
    },
    {
      id: 'template-2',
      name: '2023年玉米高产种植计划',
      type: '季度计划',
      year: 2023,
      quarter: 2,
      crop: '玉米',
      variety: '登海605',
      plannedArea: 150,
      startDate: '2023-05-01',
      endDate: '2023-08-31',
      status: '已完成',
      createdBy: '李四',
      createdAt: '2023-04-10',
      activities: [
        {
          id: 'tpl-act-7',
          name: '夏玉米播种',
          type: '播种',
          startDate: '2023-05-01',
          endDate: '2023-05-10',
          duration: 10,
          description: '夏玉米播种',
        },
        {
          id: 'tpl-act-8',
          name: '施基肥',
          type: '施肥',
          startDate: '2023-05-05',
          endDate: '2023-05-10',
          duration: 6,
          description: '施用底肥',
        },
        {
          id: 'tpl-act-9',
          name: '追肥及除草',
          type: '施肥',
          startDate: '2023-06-01',
          endDate: '2023-06-15',
          duration: 15,
          description: '拔节期追肥除草',
        },
        {
          id: 'tpl-act-10',
          name: '病虫害防治',
          type: '病虫害防治',
          startDate: '2023-07-01',
          endDate: '2023-07-20',
          duration: 20,
          description: '预防玉米螟等害虫',
        },
        {
          id: 'tpl-act-11',
          name: '收获',
          type: '采收',
          startDate: '2023-08-20',
          endDate: '2023-08-31',
          duration: 12,
          description: '玉米成熟收获',
        },
      ],
    },
  ]);

  const handleCreatePlan = () => {
    setSelectedPlan(null);
    setEditingActivities([]);
    setPlanDialogTab('basic');
    setShowPlanDialog(true);
  };

  const handleEditPlan = (plan: Plan) => {
    setSelectedPlan(plan);
    setEditingActivities([...plan.activities]);
    setPlanDialogTab('basic');
    setShowPlanDialog(true);
  };

  const handleViewPlanDetail = (plan: Plan) => {
    setSelectedPlan(plan);
    setShowPlanDetailDialog(true);
  };

  // 打开工单生成对话框
  const handleGenerateWorkOrders = (plan: Plan) => {
    if (plan.activities.length === 0) {
      toast.error('该计划暂无农事活动，无法生成工单');
      return;
    }
    setSelectedPlan(plan);
    setShowWorkOrderGenerateDialog(true);
  };

  const handleViewWorkOrder = (workOrder: WorkOrder) => {
    setSelectedWorkOrder(workOrder);
    setShowWorkOrderDialog(true);
  };

  const handleUpdateWorkOrderStatus = (workOrderId: string, status: WorkOrderStatus) => {
    setWorkOrders(workOrders.map(wo =>
      wo.id === workOrderId ? { ...wo, status } : wo
    ));
    toast.success('工单状态已更新');
  };

  const handleDeleteWorkOrder = (workOrderId: string) => {
    setWorkOrders(workOrders.filter(wo => wo.id !== workOrderId));
    toast.success('工单已删除');
  };

  const handleCopyFromTemplate = (template: Plan) => {
    const currentYear = new Date().getFullYear();
    const activities = template.activities.map(act => {
      // 调整年份到当前年
      const newStartDate = act.startDate.replace(/^\d{4}/, currentYear.toString());
      const newEndDate = act.endDate.replace(/^\d{4}/, currentYear.toString());
      return {
        ...act,
        id: `act-${Date.now()}-${Math.random()}`,
        startDate: newStartDate,
        endDate: newEndDate,
      };
    });
    
    setEditingActivities(activities);
    toast.success(`已加载模板"${template.name}"的活动安排`);
    setPlanDialogTab('gantt');
  };

  const handleAddActivity = () => {
    const newActivity: Activity = {
      id: `act-${Date.now()}`,
      name: '',
      type: '播种',
      startDate: new Date().toISOString().split('T')[0],
      endDate: new Date().toISOString().split('T')[0],
      duration: 1,
      description: '',
    };
    setEditingActivities([...editingActivities, newActivity]);
  };

  const handleUpdateActivity = (index: number, field: string, value: any) => {
    const updated = [...editingActivities];
    updated[index] = { ...updated[index], [field]: value };
    
    // 自动计算持续时间
    if (field === 'startDate' || field === 'endDate') {
      const start = new Date(updated[index].startDate);
      const end = new Date(updated[index].endDate);
      const duration = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
      updated[index].duration = duration > 0 ? duration : 1;
    }
    
    setEditingActivities(updated);
  };

  const handleDeleteActivity = (index: number) => {
    setEditingActivities(editingActivities.filter((_, i) => i !== index));
    toast.success('活动已删除');
  };

  // 获取月份的天数
  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth();
    return new Date(year, month + 1, 0).getDate();
  };

  // 生成月份的所有日期
  const getMonthDates = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth();
    const daysInMonth = getDaysInMonth(date);
    const dates: Date[] = [];
    for (let day = 1; day <= daysInMonth; day++) {
      dates.push(new Date(year, month, day));
    }
    return dates;
  };

  // 计算活动在月份视图中的位置
  const getActivityPosition = (activity: Activity, monthStart: Date, monthEnd: Date) => {
    const actStart = new Date(activity.startDate);
    const actEnd = new Date(activity.endDate);
    
    // 如果活动完全在月份范围外，返回null
    if (actEnd < monthStart || actStart > monthEnd) {
      return null;
    }
    
    // 裁剪到月份范围内
    const displayStart = actStart < monthStart ? monthStart : actStart;
    const displayEnd = actEnd > monthEnd ? monthEnd : actEnd;
    
    const totalDays = getDaysInMonth(monthStart);
    const offsetDays = Math.floor((displayStart.getTime() - monthStart.getTime()) / (1000 * 60 * 60 * 24));
    const durationDays = Math.ceil((displayEnd.getTime() - displayStart.getTime()) / (1000 * 60 * 60 * 24)) + 1;
    
    return {
      left: (offsetDays / totalDays) * 100,
      width: (durationDays / totalDays) * 100,
      isPartial: actStart < monthStart || actEnd > monthEnd,
      clipLeft: actStart < monthStart,
      clipRight: actEnd > monthEnd,
    };
  };

  // 处理甘特图拖动开始
  const handleGanttMouseDown = (
    e: React.MouseEvent,
    activityIndex: number,
    type: 'move' | 'resize-left' | 'resize-right'
  ) => {
    e.stopPropagation();
    const activity = editingActivities[activityIndex];
    setIsDragging(true);
    setDragInfo({
      activityIndex,
      type,
      startX: e.clientX,
      originalStartDate: activity.startDate,
      originalEndDate: activity.endDate,
    });
  };

  // 处理甘特图拖动
  const handleGanttMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !dragInfo || !ganttRef.current) return;

    const rect = ganttRef.current.getBoundingClientRect();
    const totalDays = getDaysInMonth(selectedMonth);
    const deltaX = e.clientX - dragInfo.startX;
    const daysMoved = Math.round((deltaX / rect.width) * totalDays);

    if (daysMoved === 0) return;

    const activity = editingActivities[dragInfo.activityIndex];
    const startDate = new Date(dragInfo.originalStartDate);
    const endDate = new Date(dragInfo.originalEndDate);

    let newStartDate: Date;
    let newEndDate: Date;

    if (dragInfo.type === 'move') {
      // 移动整个活动
      newStartDate = new Date(startDate);
      newStartDate.setDate(startDate.getDate() + daysMoved);
      newEndDate = new Date(endDate);
      newEndDate.setDate(endDate.getDate() + daysMoved);
    } else if (dragInfo.type === 'resize-left') {
      // 调整开始日期
      newStartDate = new Date(startDate);
      newStartDate.setDate(startDate.getDate() + daysMoved);
      newEndDate = endDate;
      
      // 确保开始日期不晚于结束日期
      if (newStartDate >= newEndDate) {
        newStartDate = new Date(newEndDate);
        newStartDate.setDate(newEndDate.getDate() - 1);
      }
    } else {
      // 调整结束日期
      newStartDate = startDate;
      newEndDate = new Date(endDate);
      newEndDate.setDate(endDate.getDate() + daysMoved);
      
      // 确保结束日期不早于开始日期
      if (newEndDate <= newStartDate) {
        newEndDate = new Date(newStartDate);
        newEndDate.setDate(newStartDate.getDate() + 1);
      }
    }

    const duration = Math.ceil((newEndDate.getTime() - newStartDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;

    const updated = [...editingActivities];
    updated[dragInfo.activityIndex] = {
      ...activity,
      startDate: newStartDate.toISOString().split('T')[0],
      endDate: newEndDate.toISOString().split('T')[0],
      duration,
    };

    setEditingActivities(updated);
  };

  // 处理甘特图拖动结束
  const handleGanttMouseUp = () => {
    if (isDragging && dragInfo) {
      const activity = editingActivities[dragInfo.activityIndex];
      toast.success(`已更新"${activity.name}"的时间：${activity.startDate} ~ ${activity.endDate}`);
    }
    setIsDragging(false);
    setDragInfo(null);
  };

  // 全局鼠标事件监听
  useEffect(() => {
    if (isDragging) {
      const handleMouseUp = () => {
        handleGanttMouseUp();
      };
      window.addEventListener('mouseup', handleMouseUp);
      return () => window.removeEventListener('mouseup', handleMouseUp);
    }
  }, [isDragging]);

  // 切换月份
  const changeMonth = (offset: number) => {
    const newMonth = new Date(selectedMonth);
    newMonth.setMonth(newMonth.getMonth() + offset);
    setSelectedMonth(newMonth);
  };

  // 时间轴拖动开始
  const handleTimelineDragStart = (e: React.MouseEvent) => {
    // 如果点击的是活动条，不启动时间轴拖动
    const target = e.target as HTMLElement;
    if (target.closest('.gantt-activity-bar')) {
      return;
    }
    
    setIsTimelineDragging(true);
    setTimelineDragStart({
      x: e.clientX,
      startMonth: new Date(selectedMonth),
    });
  };

  // 时间轴拖动中
  const handleTimelineDragMove = (e: React.MouseEvent) => {
    if (!isTimelineDragging || !ganttRef.current) return;

    const deltaX = e.clientX - timelineDragStart.x;
    const threshold = 100; // 拖动超过100px才切换月份

    if (Math.abs(deltaX) > threshold) {
      const monthOffset = deltaX > 0 ? -1 : 1;
      const newMonth = new Date(timelineDragStart.startMonth);
      newMonth.setMonth(newMonth.getMonth() + monthOffset);
      setSelectedMonth(newMonth);
      
      // 重置拖动起点
      setTimelineDragStart({
        x: e.clientX,
        startMonth: newMonth,
      });
    }
  };

  // 时间轴拖动结束
  const handleTimelineDragEnd = () => {
    setIsTimelineDragging(false);
  };

  // 全局时间轴拖动监听
  useEffect(() => {
    if (isTimelineDragging) {
      const handleMouseUp = () => {
        handleTimelineDragEnd();
      };
      window.addEventListener('mouseup', handleMouseUp);
      return () => window.removeEventListener('mouseup', handleMouseUp);
    }
  }, [isTimelineDragging]);

  // 键盘快捷键支持
  useEffect(() => {
    if (planDialogTab !== 'gantt') return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft' && !e.shiftKey) {
        e.preventDefault();
        changeMonth(-1);
      } else if (e.key === 'ArrowRight' && !e.shiftKey) {
        e.preventDefault();
        changeMonth(1);
      } else if (e.key === 'Home') {
        e.preventDefault();
        setSelectedMonth(new Date());
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [planDialogTab, selectedMonth]);

  const handleDeletePlan = (planId: string) => {
    setPlans(plans.filter(p => p.id !== planId));
    toast.success('计划已删除');
  };

  const handlePublishPlan = (planId: string) => {
    setPlans(plans.map(p => 
      p.id === planId ? { ...p, status: '已发布' as PlanStatus } : p
    ));
    toast.success('计划已发布');
  };

  const filteredPlans = filterStatus === 'all' ? plans : plans.filter(p => p.status === filterStatus);
  const filteredWorkOrders = filterStatus === 'all' ? workOrders : workOrders.filter(wo => wo.status === filterStatus);

  // 甘特图数据处理
  const getGanttData = (plan: Plan) => {
    const startDate = new Date(plan.startDate);
    const endDate = new Date(plan.endDate);
    const totalDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
    
    return {
      totalDays,
      startDate,
      activities: plan.activities.map(activity => {
        const actStart = new Date(activity.startDate);
        const actEnd = new Date(activity.endDate);
        const offsetDays = Math.ceil((actStart.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
        const widthPercent = (activity.duration / totalDays) * 100;
        const leftPercent = (offsetDays / totalDays) * 100;
        
        return {
          ...activity,
          offsetDays,
          widthPercent,
          leftPercent,
        };
      }),
    };
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">农事计划</h2>
          <p className="text-muted-foreground">
            计划制定、工单拆解与进度跟踪
          </p>
        </div>
        <div className="flex gap-2">
          <Button className="bg-success hover:bg-success/90" onClick={handleCreatePlan}>
            <Plus className="w-4 h-4 mr-2" />
            新建计划
          </Button>
        </div>
      </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>
              <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-3">
          <TabsTrigger value="creation">计划制定</TabsTrigger>
          <TabsTrigger value="allocation">资源分配规划</TabsTrigger>
          <TabsTrigger value="progress">计划进度跟踪</TabsTrigger>
        </TabsList>

        {/* 计划制定 */}
        <TabsContent value="creation" className="space-y-4">
          <div className="grid gap-4">
            {filteredPlans.map(plan => {
              const ganttData = getGanttData(plan);
              
              return (
                <Card key={plan.id} className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-start gap-3">
                      <div className="p-2 bg-success-muted rounded-lg">
                        <Calendar className="w-6 h-6 text-success" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h3>{plan.name}</h3>
                          <Badge className={getStatusColor(plan.status)}>
                            {plan.status}
                          </Badge>
                          <Badge variant="outline">{plan.type}</Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          创建人: {plan.createdBy} | 创建时间: {plan.createdAt}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      {plan.status === '草稿' && (
                        <Button 
                          size="sm" 
                          className="bg-success hover:bg-success/90"
                          onClick={() => handlePublishPlan(plan.id)}
                        >
                          <CheckCircle2 className="w-4 h-4 mr-1" />
                          发布
                        </Button>
                      )}
                      <Button size="sm" variant="outline" onClick={() => handleEditPlan(plan)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeletePlan(plan.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-info-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">作物品种</p>
                      <p className="mt-1 font-medium flex items-center gap-1">
                        <Sprout className="w-4 h-4 text-success" />
                        {plan.crop} - {plan.variety}
                      </p>
                    </div>
                    <div className="p-3 bg-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">计划面积</p>
                      <p className="mt-1 font-medium">{plan.plannedArea} 亩</p>
                    </div>
                    <div className="p-3 bg-warning-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">计划周期</p>
                      <p className="mt-1 text-sm">{plan.startDate} 至 {plan.endDate}</p>
                    </div>
                    <div className="p-3 bg-success-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">农事活动</p>
                      <p className="mt-1 font-medium">{plan.activities.length} 项</p>
                    </div>
                  </div>

                  {/* 甘特图 */}
                  {plan.activities.length > 0 && (
                    <div className="p-4 bg-muted rounded-lg">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Activity className="w-4 h-4 text-blue-600" />
                        农事活动时间轴
                      </h4>
                      <div className="space-y-3">
                        {ganttData.activities.map(activity => (
                          <div key={activity.id} className="space-y-1">
                            <div className="flex items-center justify-between text-sm">
                              <div className="flex items-center gap-2">
                                <Badge className={getActivityColor(activity.type)} variant="outline">
                                  {activity.type}
                                </Badge>
                                <span>{activity.name}</span>
                              </div>
                              <span className="text-xs text-muted-foreground">
                                {activity.startDate} ~ {activity.endDate} ({activity.duration}天)
                              </span>
                            </div>
                            <div className="relative h-8 bg-background rounded border">
                              <div
                                className="absolute h-full rounded flex items-center px-2 text-xs text-white"
                                style={{
                                  left: `${activity.leftPercent}%`,
                                  width: `${activity.widthPercent}%`,
                                  backgroundColor: 
                                    activity.type === '播种' ? '#22c55e' :
                                    activity.type === '施肥' ? '#eab308' :
                                    activity.type === '灌溉' ? '#3b82f6' :
                                    activity.type === '除草' ? '#a855f7' :
                                    activity.type === '病虫害防治' ? '#ef4444' :
                                    '#f97316',
                                }}
                              >
                                <span className="truncate">{activity.name}</span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                      
                      {/* 时间刻度 */}
                      <div className="mt-4 flex justify-between text-xs text-muted-foreground border-t pt-2">
                        <span>{ganttData.startDate.toLocaleDateString('zh-CN')}</span>
                        <span>总计 {ganttData.totalDays} 天</span>
                        <span>{new Date(plan.endDate).toLocaleDateString('zh-CN')}</span>
                      </div>
                    </div>
                  )}

                  <div className="mt-4 flex gap-2">
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => handleViewPlanDetail(plan)}
                    >
                      <FileText className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                  </div>
                </Card>
              );
            })}
          </div>

          {filteredPlans.length === 0 && (
            <Card className="p-12 text-center">
              <Calendar 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={handleCreatePlan}>
                <Plus className="w-4 h-4 mr-2" />
                新建计划
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 资源分配规划 */}
        <TabsContent value="allocation" className="space-y-4">
          {/* 计划选择器 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Calendar className="w-5 h-5 text-green-600" />
              选择计划生成工单
            </h3>
            <div className="grid gap-3">
              {plans.filter(p => p.status === '已发布' || p.status === '进行中').map(plan => (
                <div key={plan.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-green-100 rounded">
                      <Sprout className="w-5 h-5 text-green-600" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{plan.name}</h4>
                        <Badge className={getStatusColor(plan.status)}>{plan.status}</Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {plan.crop} - {plan.variety} | {plan.plannedArea}亩 | {plan.activities.length}项活动
                      </p>
                    </div>
                  </div>
                  <Button
                    className="bg-blue-600 hover:bg-blue-700"
                    onClick={() => handleGenerateWorkOrders(plan)}
                    disabled={plan.activities.length === 0 || workOrders.some(wo => wo.planId === plan.id)}
                  >
                    <Target className="w-4 h-4 mr-2" />
                    {workOrders.some(wo => wo.planId === plan.id) ? '已生成工单' : '生成工单'}
                  </Button>
                </div>
              ))}
              
              {plans.filter(p => p.status === '已发布' || p.status === '进行中').length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  <Calendar className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>暂无可用计划</p>
                  <p className="text-sm mt-1">请先在"计划制定"中创建并发布计划</p>
                </div>
              )}
            </div>
          </Card>

          {/* 工单统计 */}
          <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-purple-600">
                    {workOrders.filter(wo => wo.status === '待开始').length}
                  </p>
                </div>
                <Circle className="w-12 h-12 text-purple-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">
                    {workOrders.filter(wo => wo.status === '进行中').length}
                  </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-green-600">
                    {workOrders.filter(wo => wo.status === '已完成').length}
                  </p>
                </div>
                <CheckCircle2 className="w-12 h-12 text-green-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-red-600">
                    {workOrders.filter(wo => wo.status === '已延误').length}
                  </p>
                </div>
                <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 工单列表 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <ClipboardList className="w-5 h-5 text-blue-600" />
                工单列表
              </h3>
            </div>
            <div className="space-y-4">
              {filteredWorkOrders.map(workOrder => (
                <Card key={workOrder.id} className="p-4 border-l-4" style={{
                  borderLeftColor:
                    workOrder.status === '待开始' ? '#a855f7' :
                    workOrder.status === '进行中' ? '#f97316' :
                    workOrder.status === '已完成' ? '#22c55e' : '#ef4444'
                }}>
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${getActivityColor(workOrder.activityType)}`}>
                        <Target className="w-5 h-5" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{workOrder.planName}</h4>
                          <Badge className={getStatusColor(workOrder.status)}>
                            {getStatusIcon(workOrder.status)}
                            <span className="ml-1">{workOrder.status}</span>
                          </Badge>
                          <Badge variant="outline">{workOrder.activityType}</Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          工单编号: {workOrder.id}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4 mb-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">地块信息</p>
                      <p className="text-sm font-medium flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {workOrder.fieldName} ({workOrder.area}亩)
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">负责人/班组</p>
                      <p className="text-sm font-medium flex items-center gap-1">
                        <Users className="w-3 h-3" />
                        {workOrder.assignedTo} / {workOrder.teamName}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">计划日期</p>
                      <p className="text-sm font-medium flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {workOrder.scheduledDate}
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-blue-900 mb-1">预计工时</p>
                      <p className="text-sm text-blue-800 font-medium">
                        {workOrder.estimatedHours} 小时
                        {workOrder.actualHours && (
                          <span className="ml-2 text-xs">
                            (实际: {workOrder.actualHours}小时)
                          </span>
                        )}
                      </p>
                    </div>
                    <div className="p-3 bg-green-50 rounded-lg">
                      <p className="text-xs text-green-900 mb-1">农资用量</p>
                      <div className="text-sm text-green-800">
                        {workOrder.estimatedMaterials.length > 0 ? (
                          workOrder.estimatedMaterials.map((mat, i) => (
                            <span key={i} className="mr-3">
                              {mat.name}: {mat.amount}{mat.unit}
                            </span>
                          ))
                        ) : (
                          <span className="text-muted-foreground">无需农资</span>
                        )}
                      </div>
                    </div>
                  </div>

                  {workOrder.notes && (
                    <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg mb-3">
                      <p className="text-xs text-yellow-900 mb-1">备注</p>
                      <p className="text-sm text-yellow-800">{workOrder.notes}</p>
                    </div>
                  )}

                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => handleViewWorkOrder(workOrder)}>
                      <FileText className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          </Card>


        </TabsContent>

        {/* 计划进度跟踪 */}
        <TabsContent value="progress" className="space-y-4">
          {/* 进度总览 */}
          <div className="grid grid-cols-3 gap-4">
            {plans.filter(p => p.status === '进行中').map(plan => {
              const totalWorkOrders = workOrders.filter(wo => wo.planId === plan.id).length;
              const completedWorkOrders = workOrders.filter(wo => wo.planId === plan.id && wo.status === '已完成').length;
              const progressPercent = totalWorkOrders > 0 ? (completedWorkOrders / totalWorkOrders) * 100 : 0;

              return (
                <Card key={plan.id} className="p-6">
                  <div className="flex items-center gap-3 mb-3">
                    <div className="p-2 bg-green-100 rounded-lg">
                      <TrendingUp className="w-5 h-5 text-green-600" />
                    </div>
                    <div className="flex-1">
                      <h4>{plan.name}</h4>
                      <p className="text-xs text-muted-foreground">{plan.crop} - {plan.variety}</p>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted-foreground">总体进度</span>
                      <span className="font-medium">{progressPercent.toFixed(0)}%</span>
                    </div>
                    <Progress value={progressPercent} className="h-2" />
                  </div>

                  <div className="mt-4 grid grid-cols-2 gap-2 text-xs">
                    <div className="p-2 bg-gray-50 rounded">
                      <p className="text-muted-foreground">总工单</p>
                      <p className="font-medium">{totalWorkOrders}</p>
                    </div>
                    <div className="p-2 bg-green-50 rounded">
                      <p className="text-muted-foreground">已完成</p>
                      <p className="font-medium text-green-600">{completedWorkOrders}</p>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>

          {/* 详细进度表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5 text-purple-600" />
              计划执行明细
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">计划名称</th>
                    <th className="px-4 py-3 text-left text-xs">作物品种</th>
                    <th className="px-4 py-3 text-center text-xs">计划周期</th>
                    <th className="px-4 py-3 text-center text-xs">总工单</th>
                    <th className="px-4 py-3 text-center text-xs">已完成</th>
                    <th className="px-4 py-3 text-center text-xs">进行中</th>
                    <th className="px-4 py-3 text-center text-xs">已延误</th>
                    <th className="px-4 py-3 text-center text-xs">完成率</th>
                    <th className="px-4 py-3 text-center text-xs">状态</th>
                  </tr>
                </thead>
                <tbody>
                  {plans.map(plan => {
                    const planWorkOrders = workOrders.filter(wo => wo.planId === plan.id);
                    const completed = planWorkOrders.filter(wo => wo.status === '已完成').length;
                    const inProgress = planWorkOrders.filter(wo => wo.status === '进行中').length;
                    const delayed = planWorkOrders.filter(wo => wo.status === '已延误').length;
                    const completionRate = planWorkOrders.length > 0 ? (completed / planWorkOrders.length * 100).toFixed(0) : 0;

                    return (
                      <tr key={plan.id} className="border-t hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm">{plan.name}</td>
                        <td className="px-4 py-3 text-sm">{plan.crop} - {plan.variety}</td>
                        <td className="px-4 py-3 text-center text-sm">
                          {plan.startDate} ~ {plan.endDate}
                        </td>
                        <td className="px-4 py-3 text-center text-sm">{planWorkOrders.length}</td>
                        <td className="px-4 py-3 text-center text-sm text-green-600 font-medium">
                          {completed}
                        </td>
                        <td className="px-4 py-3 text-center text-sm text-orange-600 font-medium">
                          {inProgress}
                        </td>
                        <td className="px-4 py-3 text-center text-sm text-red-600 font-medium">
                          {delayed}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <div className="flex items-center gap-2">
                            <Progress value={Number(completionRate)} className="flex-1 h-2" />
                            <span className="text-sm font-medium">{completionRate}%</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <Badge className={getStatusColor(plan.status)}>
                            {plan.status}
                          </Badge>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          {/* 进度提示 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <CheckCircle2 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>: 工单已完成并验收</li>
                  <li>• <strong>已延误</strong>: 超过计划时间未完成的工单</li>
                  <li>��� 系统自动计算各计划的整体进度和完成率</li>
                  <li>• 支持查看每个工单的详细执行情况</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 创建/编辑计划对话框 */}
      <Dialog open={showPlanDialog} onOpenChange={setShowPlanDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedPlan ? '编辑计划' : '新建计划'}</DialogTitle>
            <DialogDescription>
              {selectedPlan ? '修改农事计划的基本信息和活动安排' : '创建新的农事计划，可视化编排农事活动，或从往年模板快速创建'}
            </DialogDescription>
          </DialogHeader>
          
          <Tabs value={planDialogTab} onValueChange={setPlanDialogTab}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="basic">基本信息</TabsTrigger>
              <TabsTrigger value="gantt">活动编排（甘特图）</TabsTrigger>
              <TabsTrigger value="template">往年模板</TabsTrigger>
            </TabsList>

            {/* 基本信息 */}
            <TabsContent value="basic" className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>计划名称</label>
                  <Input placeholder="请输入计划名称" className="mt-2" />
                </div>
                <div>
                  <label>计划类型</label>
                  <Select>
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择计划类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="year">年度计划</SelectItem>
                      <SelectItem value="quarter">季度计划</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>作物</label>
                  <Input placeholder="如：水稻" className="mt-2" />
                </div>
                <div>
                  <label>品种</label>
                  <Input placeholder="如：优质稻1号" className="mt-2" />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>计划面积 (亩)</label>
                  <Input type="number" placeholder="请输入计划面积" className="mt-2" />
                </div>
                <div>
                  <label>年份/季度</label>
                  <div className="flex gap-2 mt-2">
                    <Input type="number" placeholder="年份" className="flex-1" />
                    <Select>
                      <SelectTrigger className="flex-1">
                        <SelectValue placeholder="季度" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1">第一季度</SelectItem>
                        <SelectItem value="2">第二季度</SelectItem>
                        <SelectItem value="3">第三季度</SelectItem>
                        <SelectItem value="4">第四季度</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>开始日期</label>
                  <Input type="date" className="mt-2" />
                </div>
                <div>
                  <label>结束日期</label>
                  <Input type="date" className="mt-2" />
                </div>
              </div>

              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-start gap-2">
                  <Zap className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-blue-900">
                    <p className="mb-2">下一步：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 点击"活动编排"标签页，使用甘特图可视化编排农事活动</li>
                      <li>• 或点击"往年模板"标签页，从历史计划中快速复制活动安排</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </TabsContent>

            {/* 活动编排（甘特图） */}
            <TabsContent value="gantt" className="space-y-4 mt-4">
              <div className="flex items-center justify-between">
                <h4 className="flex items-center gap-2">
                  <Layers className="w-5 h-5 text-green-600" />
                  农事活动甘特图
                </h4>
                <Button size="sm" onClick={handleAddActivity}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加活动
                </Button>
              </div>

              {editingActivities.length === 0 ? (
                <Card className="p-12 text-center">
                  <Activity className="w-16 h-16 mx-auto text-gray-400 mb-4" />
                  <p className="text-muted-foreground mb-4">暂无活动，请添加农事活动</p>
                  <Button onClick={handleAddActivity}>
                    <Plus className="w-4 h-4 mr-2" />
                    添加第一个活动
                  </Button>
                </Card>
              ) : (
                <div className="space-y-4">
                  {/* 活动列表和编辑 */}
                  <div className="space-y-3 max-h-[400px] overflow-y-auto">
                    {editingActivities.map((activity, index) => (
                      <Card key={activity.id} className="p-4">
                        <div className="flex items-start gap-3">
                          <div className="flex-1 space-y-3">
                            <div className="grid grid-cols-2 gap-3">
                              <div>
                                <label>活动名称</label>
                                <Input
                                  value={activity.name}
                                  onChange={(e) => handleUpdateActivity(index, 'name', e.target.value)}
                                  placeholder="如：春季播种"
                                  className="mt-2"
                                />
                              </div>
                              <div>
                                <label>活动类型</label>
                                <Select
                                  value={activity.type}
                                  onValueChange={(value) => handleUpdateActivity(index, 'type', value)}
                                >
                                  <SelectTrigger className="mt-2">
                                    <SelectValue />
                                  </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-3 gap-3">
                              <div>
                                <label>开始日期</label>
                                <Input
                                  type="date"
                                  value={activity.startDate}
                                  onChange={(e) => handleUpdateActivity(index, 'startDate', e.target.value)}
                                  className="mt-2"
                                />
                              </div>
                              <div>
                                <label>结束日期</label>
                                <Input
                                  type="date"
                                  value={activity.endDate}
                                  onChange={(e) => handleUpdateActivity(index, 'endDate', e.target.value)}
                                  className="mt-2"
                                />
                              </div>
                              <div>
                                <label>持续天数</label>
                                <div className="field-value">{activity.duration} 天</div>
                              </div>
                            </div>

                            <div>
                              <label>活动描述</label>
                              <Textarea
                                value={activity.description}
                                onChange={(e) => handleUpdateActivity(index, 'description', e.target.value)}
                                placeholder="详细说明该活动的具体内容..."
                                rows={2}
                                className="mt-2"
                              />
                            </div>
                          </div>

                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleDeleteActivity(index)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </Card>
                    ))}
                  </div>

                  {/* 甘特图可视化 */}
                  {editingActivities.length > 0 && editingActivities[0].startDate && (
                    <Card className="p-6 bg-muted">
                      {/* 月份选择器 */}
                      <div className="flex items-center justify-between mb-4">
                        <div>
                          <h4 className="flex items-center gap-2">
                            <Activity className="w-5 h-5 text-blue-600" />
                            甘特图 - 可拖动调整时间
                          </h4>
                          <p className="text-xs text-muted-foreground mt-1">
                            👆 拖动空白处可左右平移时间轴
                          </p>
                        </div>
                        <div className="flex items-center gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => changeMonth(-1)}
                            title="上一月"
                          >
                            <ChevronRight className="w-4 h-4 rotate-180" />
                          </Button>
                          <div className="px-4 py-1 bg-background rounded border min-w-[120px] text-center">
                            <span className="text-sm font-medium">
                              {selectedMonth.getFullYear()}年{selectedMonth.getMonth() + 1}月
                            </span>
                          </div>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => changeMonth(1)}
                            title="下一月"
                          >
                            <ChevronRight className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => setSelectedMonth(new Date())}
                          >
                            本月
                          </Button>
                        </div>
                      </div>

                      {/* 日期刻度 */}
                      <div className={`mb-2 relative h-8 bg-background rounded border overflow-hidden transition-all ${
                        isTimelineDragging ? 'ring-2 ring-blue-500 shadow-lg' : ''
                      }`}>
                        <div className="flex h-full">
                          {getMonthDates(selectedMonth).map((date, index) => {
                            const isToday = 
                              date.getFullYear() === new Date().getFullYear() &&
                              date.getMonth() === new Date().getMonth() &&
                              date.getDate() === new Date().getDate();
                            
                            return (
                              <div
                                key={index}
                                className={`flex-1 border-r last:border-r-0 flex items-center justify-center text-xs transition-colors ${
                                  isToday ? 'bg-blue-100' : (date.getDay() === 0 || date.getDay() === 6 ? 'bg-muted' : '')
                                }`}
                              >
                                <div className="text-center">
                                  <div className={`${isToday ? 'text-blue-600 font-bold' : 'text-muted-foreground'}`}>
                                    {date.getDate()}
                                  </div>
                                  {date.getDate() === 1 && (
                                    <div className="text-xs text-blue-600 font-medium">
                                      {date.getMonth() + 1}月
                                    </div>
                                  )}
                                  {isToday && (
                                    <div className="text-xs text-blue-600">
                                      今
                                    </div>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>

                      {/* 甘特图活动条 */}
                      <div
                        ref={ganttRef}
                        className="space-y-3 select-none relative p-4 rounded-lg bg-card"
                        onMouseDown={handleTimelineDragStart}
                        onMouseMove={(e) => {
                          handleTimelineDragMove(e);
                          handleGanttMouseMove(e);
                        }}
                        style={{ 
                          cursor: isTimelineDragging ? 'grabbing' : (isDragging ? 'grabbing' : 'grab')
                        }}
                      >
                        {/* 拖动提示 */}
                        {isTimelineDragging && (
                          <div className="absolute inset-0 bg-blue-500/5 border-2 border-blue-500 border-dashed rounded-lg flex items-center justify-center pointer-events-none z-10">
                            <div className="bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg">
                              <div className="flex items-center gap-2">
                                <ChevronRight className="w-5 h-5 rotate-180 animate-pulse" />
                                <span>左右拖动切换月份</span>
                                <ChevronRight className="w-5 h-5 animate-pulse" />
                              </div>
                            </div>
                          </div>
                        )}
                        {(() => {
                          const year = selectedMonth.getFullYear();
                          const month = selectedMonth.getMonth();
                          const monthStart = new Date(year, month, 1);
                          const monthEnd = new Date(year, month + 1, 0);

                          return editingActivities.map((activity, index) => {
                            const position = getActivityPosition(activity, monthStart, monthEnd);
                            
                            if (!position) return null;

                            const activityColor =
                              activity.type === '播种' ? '#22c55e' :
                              activity.type === '施肥' ? '#eab308' :
                              activity.type === '灌溉' ? '#3b82f6' :
                              activity.type === '除草' ? '#a855f7' :
                              activity.type === '病虫害防治' ? '#ef4444' :
                              '#f97316';

                            return (
                              <div key={activity.id} className="space-y-1">
                                <div className="flex items-center justify-between text-sm">
                                  <div className="flex items-center gap-2">
                                    <Badge className={getActivityColor(activity.type)} variant="outline">
                                      {activity.type}
                                    </Badge>
                                    <span>{activity.name || `活动 ${index + 1}`}</span>
                                  </div>
                                  <span className="text-xs text-muted-foreground">
                                    {activity.startDate} ~ {activity.endDate} ({activity.duration}天)
                                  </span>
                                </div>
                                <div className="relative h-10 bg-background rounded border">
                                  <div
                                    className="gantt-activity-bar absolute h-full rounded flex items-center px-2 text-xs text-white transition-all group"
                                    style={{
                                      left: `${position.left}%`,
                                      width: `${position.width}%`,
                                      backgroundColor: activityColor,
                                      cursor: isDragging ? 'grabbing' : 'grab',
                                      borderLeft: position.clipLeft ? '3px dashed rgba(255,255,255,0.6)' : 'none',
                                      borderRight: position.clipRight ? '3px dashed rgba(255,255,255,0.6)' : 'none',
                                    }}
                                    onMouseDown={(e) => {
                                      e.stopPropagation();
                                      handleGanttMouseDown(e, index, 'move');
                                    }}
                                  >
                                    {/* 左边缘调整手柄 */}
                                    {!position.clipLeft && (
                                      <div
                                        className="absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize hover:bg-white/30 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                        onMouseDown={(e) => {
                                          e.stopPropagation();
                                          handleGanttMouseDown(e, index, 'resize-left');
                                        }}
                                      >
                                        <div className="w-1 h-8 bg-white/80 rounded"></div>
                                      </div>
                                    )}
                                    
                                    <span className="truncate flex-1 text-center">
                                      {activity.name || `活动 ${index + 1}`}
                                    </span>
                                    
                                    {/* 右边缘调整手柄 */}
                                    {!position.clipRight && (
                                      <div
                                        className="absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize hover:bg-white/30 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                        onMouseDown={(e) => {
                                          e.stopPropagation();
                                          handleGanttMouseDown(e, index, 'resize-right');
                                        }}
                                      >
                                        <div className="w-1 h-8 bg-white/80 rounded"></div>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </div>
                            );
                          });
                        })()}
                      </div>

                      {/* 操作提示 */}
                      <Card className="mt-4 p-3 bg-blue-50 border-blue-200">
                        <div className="flex items-start gap-2">
                          <Zap className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                          <div className="text-xs text-blue-900">
                            <div className="grid grid-cols-2 gap-3">
                              <div>
                                <p className="mb-1 font-medium">🖱️ 鼠标操作：</p>
                                <ul className="space-y-0.5">
                                  <li>• <strong>拖动空白处</strong> - 左右平移时间轴</li>
                                  <li>• <strong>拖动活动条</strong> - 调整活动时间</li>
                                  <li>• <strong>拖动边缘</strong> - 调整持续时间</li>
                                </ul>
                              </div>
                              <div>
                                <p className="mb-1 font-medium">⌨️ 键盘快捷键：</p>
                                <ul className="space-y-0.5">
                                  <li>• <strong>← →</strong> - 切换上/下月</li>
                                  <li>• <strong>Home</strong> - 回到本月</li>
                                  <li>• 虚线边框表示跨月活动</li>
                                </ul>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Card>
                    </Card>
                  )}
                </div>
              )}
            </TabsContent>

            {/* 往年模板 */}
            <TabsContent value="template" className="space-y-4 mt-4">
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-start gap-2">
                  <Layers 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>• 选择一个历史计划模板，系统会自动将活动安排复制到当前计划</li>
                      <li>• 日期会自动调整到当前年份</li>
                      <li>• 复制后可在"活动编排"标签页中进一步调整</li>
                    </ul>
                  </div>
                </div>
              </Card>

              <div className="grid gap-4">
                {historyTemplates.map(template => (
                  <Card key={template.id} className="p-4 hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-start gap-3">
                        <div className="p-2 bg-purple-100 rounded-lg">
                          <FileText className="w-5 h-5 text-purple-600" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{template.name}</h4>
                            <Badge variant="outline">{template.year}年</Badge>
                            <Badge className="bg-green-500 text-white">
                              已完成
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {template.crop} - {template.variety} | 面积: {template.plannedArea}亩
                          </p>
                        </div>
                      </div>
                      <Button
                        size="sm"
                        onClick={() => handleCopyFromTemplate(template)}
                      >
                        <FileText className="w-4 h-4 mr-2" />
                        使用此模板
                      </Button>
                    </div>

                    <div className="p-3 bg-muted rounded-lg">
                      <p className="text-xs text-muted-foreground mb-2">包含活动：</p>
                      <div className="flex flex-wrap gap-2">
                        {template.activities.map(act => (
                          <Badge key={act.id} className={getActivityColor(act.type)} variant="outline">
                            {act.type}: {act.name}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex gap-2 justify-end pt-4 border-t">
            <Button variant="outline" onClick={() => setShowPlanDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700">
              保存计划
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 工单详情对话框 */}
      <Dialog open={showWorkOrderDialog} onOpenChange={setShowWorkOrderDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>工单详情</DialogTitle>
            <DialogDescription>
              查看和管理工单的地块分配、人员安排、工时预估和农资用量信息
            </DialogDescription>
          </DialogHeader>
          {selectedWorkOrder && (
            <div className="space-y-4">
              <div className="p-4 bg-muted rounded-lg">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-xs text-muted-foreground">工单编号</p>
                    <p className="text-sm font-medium mt-1">{selectedWorkOrder.id}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">所属计划</p>
                    <p className="text-sm font-medium mt-1">{selectedWorkOrder.planName}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">作业类型</p>
                    <Badge className={`mt-1 ${getActivityColor(selectedWorkOrder.activityType)}`}>
                      {selectedWorkOrder.activityType}
                    </Badge>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">工单状态</p>
                    <Badge className={`mt-1 ${getStatusColor(selectedWorkOrder.status)}`}>
                      {selectedWorkOrder.status}
                    </Badge>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>地块</label>
                  <div className="field-value">{selectedWorkOrder.fieldName}</div>
                </div>
                <div>
                  <label>作业面积</label>
                  <div className="field-value">{selectedWorkOrder.area} 亩</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>负责人</label>
                  <div className="field-value">{selectedWorkOrder.assignedTo}</div>
                </div>
                <div>
                  <label>班组</label>
                  <div className="field-value">{selectedWorkOrder.teamName}</div>
                </div>
              </div>

              <div>
                <label>计划日期</label>
                <div className="field-value">{selectedWorkOrder.scheduledDate}</div>
              </div>

              <div>
                <label>预计工时</label>
                <div className="field-value">{selectedWorkOrder.estimatedHours} 小时</div>
              </div>

              {selectedWorkOrder.estimatedMaterials.length > 0 && (
                <div>
                  <label>农资用量</label>
                  <div className="mt-2 space-y-2">
                    {selectedWorkOrder.estimatedMaterials.map((mat, i) => (
                      <div key={i} className="flex items-center justify-between p-3 bg-gray-50 rounded">
                        <span className="text-sm">{mat.name}</span>
                        <span className="text-sm font-medium">{mat.amount} {mat.unit}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {selectedWorkOrder.notes && (
                <div>
                  <label>备注</label>
                  <div className="field-value">{selectedWorkOrder.notes}</div>
                </div>
              )}

              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowWorkOrderDialog(false)}>
                  关闭
                </Button>
                <Button className="bg-blue-600 hover:bg-blue-700">
                  <Edit className="w-4 h-4 mr-2" />
                  编辑工单
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 计划详情对话框 */}
      <Dialog open={showPlanDetailDialog} onOpenChange={setShowPlanDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>计划详情</DialogTitle>
            <DialogDescription>
              查看农事计划的完整信息和活动安排
            </DialogDescription>
          </DialogHeader>
          {selectedPlan && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Calendar className="w-5 h-5 text-green-600" />
                  基本信息
                </h4>
                <div className="p-4 bg-gray-50 rounded-lg">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs text-muted-foreground">计划名称</p>
                      <p className="text-sm font-medium mt-1">{selectedPlan.name}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">计划状态</p>
                      <Badge className={`mt-1 ${getStatusColor(selectedPlan.status)}`}>
                        {selectedPlan.status}
                      </Badge>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">计划类型</p>
                      <p className="text-sm mt-1">{selectedPlan.type}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">年份/季度</p>
                      <p className="text-sm mt-1">
                        {selectedPlan.year}年
                        {selectedPlan.quarter && ` 第${selectedPlan.quarter}季度`}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* 作物信息 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Sprout className="w-5 h-5 text-green-600" />
                  作物信息
                </h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-4 bg-green-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">作物</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.crop}</p>
                  </div>
                  <div className="p-4 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">品种</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.variety}</p>
                  </div>
                  <div className="p-4 bg-purple-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">计划面积</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.plannedArea} 亩</p>
                  </div>
                </div>
              </div>

              {/* 计划周期 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Clock className="w-5 h-5 text-orange-600" />
                  计划周期
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-4 bg-orange-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">开始日期</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.startDate}</p>
                  </div>
                  <div className="p-4 bg-orange-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">结束日期</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.endDate}</p>
                  </div>
                </div>
              </div>

              {/* 农事活动 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Activity className="w-5 h-5 text-blue-600" />
                  农事活动 ({selectedPlan.activities.length}项)
                </h4>
                <div className="space-y-3">
                  {selectedPlan.activities.map((activity, index) => (
                    <Card key={activity.id} className="p-4">
                      <div className="flex items-start gap-3">
                        <div className={`px-3 py-1 rounded ${getActivityColor(activity.type)}`}>
                          <span className="text-xs text-white">{index + 1}</span>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h5>{activity.name}</h5>
                            <Badge className={getActivityColor(activity.type)} variant="outline">
                              {activity.type}
                            </Badge>
                          </div>
                          <div className="grid grid-cols-2 gap-4 text-sm">
                            <div>
                              <span className="text-muted-foreground">时间：</span>
                              <span className="ml-1">{activity.startDate} 至 {activity.endDate}</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">持续时间：</span>
                              <span className="ml-1">{activity.duration} 天</span>
                            </div>
                          </div>
                          {activity.description && (
                            <p className="mt-2 text-sm text-muted-foreground">
                              {activity.description}
                            </p>
                          )}
                        </div>
                      </div>
                    </Card>
                  ))}
                  
                  {selectedPlan.activities.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      <Activity className="w-12 h-12 mx-auto mb-2 opacity-50" />
                      <p>暂无农事活动</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 创建信息 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <User className="w-5 h-5 text-gray-600" />
                  创建信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-4 bg-muted rounded-lg">
                    <p className="text-xs text-muted-foreground">创建人</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.createdBy}</p>
                  </div>
                  <div className="p-4 bg-muted rounded-lg">
                    <p className="text-xs text-muted-foreground">创建时间</p>
                    <p className="text-sm font-medium mt-1">{selectedPlan.createdAt}</p>
                  </div>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex gap-2 justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowPlanDetailDialog(false)}>
                  关闭
                </Button>
                <Button 
                  variant="outline" 
                  onClick={() => {
                    setShowPlanDetailDialog(false);
                    handleEditPlan(selectedPlan);
                  }}
                >
                  <Edit className="w-4 h-4 mr-2" />
                  编辑计划
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 工单生成对话框 */}
      <WorkOrderGenerateDialog
        open={showWorkOrderGenerateDialog}
        onClose={() => setShowWorkOrderGenerateDialog(false)}
        plan={selectedPlan}
        onGenerate={(newOrders) => {
          setWorkOrders([...workOrders, ...newOrders]);
          setShowWorkOrderGenerateDialog(false);
          toast.success(`成功生成 ${newOrders.length} 个工单`);
        }}
      />
    </div>
  );
}

// 工单生成对话框组件
interface WorkOrderGenerateDialogProps {
  open: boolean;
  onClose: () => void;
  plan: Plan | null;
  onGenerate: (workOrders: WorkOrder[]) => void;
}

function WorkOrderGenerateDialog({ open, onClose, plan, onGenerate }: WorkOrderGenerateDialogProps) {
  const [activityWorkOrders, setActivityWorkOrders] = useState<{
    activityId: string;
    fieldId: string;
    fieldName: string;
    area: number;
    assignedTo: string;
    teamName: string;
    scheduledStartDate: string;
    scheduledEndDate: string;
    estimatedHours: number;
    materials: { id: string; name: string; amount: number; unit: string }[];
  }[]>([]);

  // 从localStorage获取地块数据
  const getAvailableFields = () => {
    const fieldsData = localStorage.getItem('smart_agriculture_fields');
    if (fieldsData) {
      try {
        return JSON.parse(fieldsData);
      } catch (e) {
        return [];
      }
    }
    return [];
  };

  // 从localStorage获取员工数据
  const getAvailableEmployees = () => {
    const employeesData = localStorage.getItem('smart_agriculture_employees');
    if (employeesData) {
      try {
        const employees = JSON.parse(employeesData);
        return employees.filter((e: any) => e.status === '在职');
      } catch (e) {
        return [];
      }
    }
    // 默认员工
    return [
      { id: 'emp-1', name: '张三', position: '班组长', team: '第一作业组' },
      { id: 'emp-2', name: '李四', position: '班组长', team: '第二作业组' },
      { id: 'emp-3', name: '王五', position: '班组长', team: '第三作业组' },
      { id: 'emp-4', name: '赵六', position: '班组长', team: '第四作业组' },
    ];
  };

  // 从localStorage获取农资数据
  const getAvailableMaterials = () => {
    const materialsData = localStorage.getItem('smart_agriculture_materials');
    if (materialsData) {
      try {
        const materials = JSON.parse(materialsData);
        return materials.filter((m: any) => m.quantity > 0);
      } catch (e) {
        return [];
      }
    }
    // 默认农资
    return [
      { id: 'mat-1', name: '有机肥', unit: 'kg', quantity: 10000 },
      { id: 'mat-2', name: '复合肥', unit: 'kg', quantity: 5000 },
      { id: 'mat-3', name: '尿素', unit: 'kg', quantity: 3000 },
      { id: 'mat-4', name: '杀虫剂', unit: 'L', quantity: 200 },
      { id: 'mat-5', name: '杀菌剂', unit: 'L', quantity: 150 },
      { id: 'mat-6', name: '除草剂', unit: 'L', quantity: 100 },
      { id: 'mat-7', name: '水稻种子', unit: 'kg', quantity: 800 },
      { id: 'mat-8', name: '玉米种子', unit: 'kg', quantity: 600 },
      { id: 'mat-9', name: '小麦种子', unit: 'kg', quantity: 1000 },
    ];
  };

  const fields = getAvailableFields();
  const employees = getAvailableEmployees();
  const materials = getAvailableMaterials();

  // 初始化活动工单数据
  useEffect(() => {
    if (open && plan) {
      const initialOrders = plan.activities.map(activity => ({
        activityId: activity.id,
        fieldId: '',
        fieldName: '',
        area: 0,
        assignedTo: '',
        teamName: '',
        scheduledStartDate: activity.startDate,
        scheduledEndDate: activity.endDate,
        estimatedHours: 0,
        materials: [],
      }));
      setActivityWorkOrders(initialOrders);
    }
  }, [open, plan]);

  // 计算工时（基于面积和活动类型）
  const calculateEstimatedHours = (activityType: ActivityType, area: number): number => {
    const hourPerMu: Record<ActivityType, number> = {
      '播种': 0.5,
      '施肥': 0.3,
      '灌溉': 0.15,
      '除草': 0.4,
      '病虫害防治': 0.25,
      '采收': 0.8,
    };
    return Math.ceil(area * (hourPerMu[activityType] || 0.3));
  };

  // 自动推荐农资
  const getRecommendedMaterials = (activityType: ActivityType, area: number, crop: string) => {
    const recommended: { id: string; name: string; amount: number; unit: string }[] = [];
    
    if (activityType === '播种') {
      const seedName = `${crop}种子`;
      const seed = materials.find(m => m.name.includes(crop) && m.name.includes('种子'));
      if (seed) {
        recommended.push({
          id: seed.id,
          name: seed.name,
          amount: parseFloat((area * 3.5).toFixed(1)),
          unit: seed.unit,
        });
      }
    } else if (activityType === '施肥') {
      const organicFertilizer = materials.find(m => m.name.includes('有机肥'));
      const compoundFertilizer = materials.find(m => m.name.includes('复合肥'));
      if (organicFertilizer) {
        recommended.push({
          id: organicFertilizer.id,
          name: organicFertilizer.name,
          amount: Math.ceil(area * 400),
          unit: organicFertilizer.unit,
        });
      }
      if (compoundFertilizer) {
        recommended.push({
          id: compoundFertilizer.id,
          name: compoundFertilizer.name,
          amount: Math.ceil(area * 40),
          unit: compoundFertilizer.unit,
        });
      }
    } else if (activityType === '病虫害防治') {
      const pesticide = materials.find(m => m.name.includes('杀虫剂'));
      const fungicide = materials.find(m => m.name.includes('杀菌剂'));
      if (pesticide) {
        recommended.push({
          id: pesticide.id,
          name: pesticide.name,
          amount: parseFloat((area * 0.04).toFixed(2)),
          unit: pesticide.unit,
        });
      }
      if (fungicide) {
        recommended.push({
          id: fungicide.id,
          name: fungicide.name,
          amount: parseFloat((area * 0.03).toFixed(2)),
          unit: fungicide.unit,
        });
      }
    } else if (activityType === '除草') {
      const herbicide = materials.find(m => m.name.includes('除草剂'));
      if (herbicide) {
        recommended.push({
          id: herbicide.id,
          name: herbicide.name,
          amount: parseFloat((area * 0.05).toFixed(2)),
          unit: herbicide.unit,
        });
      }
    }
    
    return recommended;
  };

  // 处理地块选择
  const handleFieldSelect = (activityId: string, fieldId: string) => {
    const field = fields.find((f: any) => f.id === fieldId);
    if (!field) return;

    const activity = plan?.activities.find(a => a.id === activityId);
    if (!activity) return;

    const area = field.area || 0;
    const estimatedHours = calculateEstimatedHours(activity.type, area);

    setActivityWorkOrders(prev =>
      prev.map(order =>
        order.activityId === activityId
          ? {
              ...order,
              fieldId: field.id,
              fieldName: field.name,
              area,
              estimatedHours,
            }
          : order
      )
    );
  };

  // 处理人员选择
  const handleEmployeeSelect = (activityId: string, employeeId: string) => {
    const employee = employees.find((e: any) => e.id === employeeId);
    if (!employee) return;

    setActivityWorkOrders(prev =>
      prev.map(order =>
        order.activityId === activityId
          ? {
              ...order,
              assignedTo: employee.name,
              teamName: employee.team || employee.position,
            }
          : order
      )
    );
  };

  // 处理农资选择和数量设置
  const handleMaterialSelect = (activityId: string, materialId: string, amount: number) => {
    const material = materials.find((m: any) => m.id === materialId);
    if (!material) return;

    setActivityWorkOrders(prev =>
      prev.map(order => {
        if (order.activityId === activityId) {
          // 检查是否已存在
          const existingIndex = order.materials.findIndex(m => m.id === materialId);
          if (existingIndex >= 0) {
            // 更新数量
            return {
              ...order,
              materials: order.materials.map(m =>
                m.id === materialId ? { ...m, amount } : m
              ),
            };
          } else {
            // 添加新农资
            return {
              ...order,
              materials: [
                ...order.materials,
                {
                  id: material.id,
                  name: material.name,
                  amount,
                  unit: material.unit,
                },
              ],
            };
          }
        }
        return order;
      })
    );
  };

  // 处理日期变更
  const handleDateChange = (activityId: string, field: 'scheduledStartDate' | 'scheduledEndDate', value: string) => {
    setActivityWorkOrders(prev =>
      prev.map(order =>
        order.activityId === activityId
          ? { ...order, [field]: value }
          : order
      )
    );
  };

  // 生成工单
  const handleGenerate = () => {
    if (!plan) return;

    // 验证所有活动都已配置
    const invalidOrders = activityWorkOrders.filter(
      order => !order.fieldId || !order.assignedTo
    );

    if (invalidOrders.length > 0) {
      toast.error('请为所有活动选择地块和人员');
      return;
    }

    const newWorkOrders: WorkOrder[] = plan.activities.map((activity, index) => {
      const orderData = activityWorkOrders[index];
      // 过滤掉用量为0的农资
      const validMaterials = orderData.materials.filter(m => m.amount > 0);
      
      return {
        id: `wo-${Date.now()}-${index}`,
        planId: plan.id,
        planName: plan.name,
        activityType: activity.type,
        fieldId: orderData.fieldId,
        fieldName: orderData.fieldName,
        assignedTo: orderData.assignedTo,
        teamName: orderData.teamName,
        scheduledDate: orderData.scheduledStartDate,
        area: orderData.area,
        estimatedHours: orderData.estimatedHours,
        estimatedMaterials: validMaterials.map(m => ({
          name: m.name,
          amount: m.amount,
          unit: m.unit,
        })),
        status: '待开始',
      };
    });

    onGenerate(newWorkOrders);
  };

  if (!plan) return null;

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Target className="w-6 h-6 text-blue-600" />
            生成工单 - {plan.name}
          </DialogTitle>
          <DialogDescription>
            为每个农事活动配置地块、人员和农资
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 计划信息 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="grid grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">作物品种：</span>
                <span className="ml-2 font-medium">{plan.crop} - {plan.variety}</span>
              </div>
              <div>
                <span className="text-muted-foreground">计划面积：</span>
                <span className="ml-2 font-medium">{plan.plannedArea} 亩</span>
              </div>
              <div>
                <span className="text-muted-foreground">活动数量：</span>
                <span className="ml-2 font-medium">{plan.activities.length} 项</span>
              </div>
              <div>
                <span className="text-muted-foreground">计划周期：</span>
                <span className="ml-2 font-medium">{plan.startDate} ~ {plan.endDate}</span>
              </div>
            </div>
          </Card>

          {/* 活动配置列表 */}
          {plan.activities.map((activity, index) => {
            const orderData = activityWorkOrders[index];
            if (!orderData) return null;

            return (
              <Card key={activity.id} className="p-6">
                <div className="mb-4">
                  <div className="flex items-center gap-3 mb-2">
                    <Badge className={getActivityColor(activity.type)}>
                      {activity.type}
                    </Badge>
                    <h4>{activity.name}</h4>
                    <Badge variant="outline">
                      {activity.startDate} ~ {activity.endDate}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground">{activity.description}</p>
                </div>

                <div className="space-y-4">
                  {/* 基本信息：地块、人员、日期 */}
                  <div className="grid grid-cols-2 gap-4">
                    {/* 地块选择 */}
                    <div>
                      <label className="flex items-center gap-2">
                        <MapPin className="w-4 h-4" />
                        选择地块
                      </label>
                      <Select
                        value={orderData.fieldId}
                        onValueChange={(value) => handleFieldSelect(activity.id, value)}
                      >
                        <SelectTrigger className="mt-2">
                          <SelectValue placeholder="请选择地块" />
                        </SelectTrigger>
                        <SelectContent>
                          {fields.length === 0 ? (
                            <div className="p-4 text-center text-sm text-muted-foreground">
                              暂无地块数据
                            </div>
                          ) : (
                            fields.map((field: any) => (
                              <SelectItem key={field.id} value={field.id}>
                                {field.name} - {field.area || 0} 亩
                              </SelectItem>
                            ))
                          )}
                        </SelectContent>
                      </Select>
                      {orderData.fieldId && (
                        <div className="mt-2 p-2 bg-blue-50 rounded text-sm">
                          <div className="flex items-center justify-between">
                            <span className="text-muted-foreground">地块面积：</span>
                            <span className="font-medium">{orderData.area} 亩</span>
                          </div>
                          <div className="flex items-center justify-between mt-1">
                            <span className="text-muted-foreground">预计工时：</span>
                            <span className="font-medium text-blue-600">
                              {orderData.estimatedHours} 小时
                            </span>
                          </div>
                        </div>
                      )}
                    </div>

                    {/* 人员选择 */}
                    <div>
                      <label className="flex items-center gap-2">
                        <UserCheck className="w-4 h-4" />
                        分配人员
                      </label>
                      <Select
                        value={orderData.assignedTo}
                        onValueChange={(value) => handleEmployeeSelect(activity.id, value)}
                      >
                        <SelectTrigger className="mt-2">
                          <SelectValue placeholder="请选择负责人" />
                        </SelectTrigger>
                        <SelectContent>
                          {employees.length === 0 ? (
                            <div className="p-4 text-center text-sm text-muted-foreground">
                              暂无员工数据
                            </div>
                          ) : (
                            employees.map((emp: any) => (
                              <SelectItem key={emp.id} value={emp.id}>
                                {emp.name} - {emp.team || emp.position}
                              </SelectItem>
                            ))
                          )}
                        </SelectContent>
                      </Select>
                      {orderData.assignedTo && (
                        <div className="mt-2 p-2 bg-green-50 rounded text-sm">
                          <span className="text-muted-foreground">班组：</span>
                          <span className="ml-2 font-medium">{orderData.teamName}</span>
                        </div>
                      )}
                    </div>

                    {/* 计划开始日期 */}
                    <div>
                      <label className="flex items-center gap-2">
                        <Clock className="w-4 h-4" />
                        计划开始日期
                      </label>
                      <Input
                        type="date"
                        value={orderData.scheduledStartDate}
                        onChange={(e) => handleDateChange(activity.id, 'scheduledStartDate', e.target.value)}
                        className="mt-2"
                      />
                    </div>

                    {/* 计划结束日期 */}
                    <div>
                      <label className="flex items-center gap-2">
                        <Clock className="w-4 h-4" />
                        计划结束日期
                      </label>
                      <Input
                        type="date"
                        value={orderData.scheduledEndDate}
                        onChange={(e) => handleDateChange(activity.id, 'scheduledEndDate', e.target.value)}
                        className="mt-2"
                      />
                    </div>
                  </div>

                  {/* 农资配置 */}
                  <div>
                    <label className="flex items-center gap-2 mb-3">
                      <Package className="w-4 h-4" />
                      农资配置
                    </label>
                    <div className="space-y-2 max-h-64 overflow-y-auto border rounded-lg p-3 bg-gray-50">
                      {materials.length === 0 ? (
                        <div className="p-4 text-center text-sm text-muted-foreground">
                          暂无可用农资
                        </div>
                      ) : (
                        materials.map((material: any) => {
                          const selectedMaterial = orderData.materials.find(m => m.id === material.id);
                          const amount = selectedMaterial?.amount || 0;
                          
                          return (
                            <div
                              key={material.id}
                              className="flex items-center gap-3 p-2 bg-white rounded border"
                            >
                              <div className="flex-1">
                                <div className="flex items-center gap-2">
                                  <span className="text-sm font-medium">{material.name}</span>
                                  <Badge variant="outline" className="text-xs">
                                    库存: {material.quantity} {material.unit}
                                  </Badge>
                                </div>
                              </div>
                              <div className="flex items-center gap-2">
                                <Input
                                  type="number"
                                  min="0"
                                  step="0.1"
                                  value={amount}
                                  onChange={(e) =>
                                    handleMaterialSelect(
                                      activity.id,
                                      material.id,
                                      parseFloat(e.target.value) || 0
                                    )
                                  }
                                  placeholder="用量"
                                  className="w-24 h-9"
                                />
                                <span className="text-sm text-muted-foreground w-12">
                                  {material.unit}
                                </span>
                              </div>
                            </div>
                          );
                        })
                      )}
                    </div>
                    <p className="text-xs text-muted-foreground mt-2">
                      💡 直接在农资行输入用量，大于0的农资将自动添加到工单
                    </p>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>

        {/* 底部操作按钮 */}
        <div className="flex items-center justify-between pt-4 border-t">
          <div className="text-sm text-muted-foreground">
            共 {plan.activities.length} 项活动，将生成 {plan.activities.length} 个工单
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleGenerate}>
              <Target className="w-4 h-4 mr-2" />
              生成工单
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 辅助函数：获取活动颜色
function getActivityColor(type: ActivityType) {
  switch (type) {
    case '播种': return 'bg-green-100 text-green-800';
    case '施肥': return 'bg-yellow-100 text-yellow-800';
    case '灌溉': return 'bg-blue-100 text-blue-800';
    case '除草': return 'bg-purple-100 text-purple-800';
    case '病虫害防治': return 'bg-red-100 text-red-800';
    case '采收': return 'bg-orange-100 text-orange-800';
    default: return 'bg-gray-100 text-gray-800';
  }
}

// Note: Copy icon has been completely removed from this file
