import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Plus, Clock, CheckCircle, XCircle, AlertTriangle, Eye, MessageSquare, Upload, X } from 'lucide-react';
import { DriverTask as DriverTaskType, DriverRecord, TaskStatus, TaskIssue } from '../../../types/driver';
import { MachineryRecord } from '../../../types/machinery';
import { Field } from '../../../types/field';
import { DataDictionary } from '../../../types/system-params';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../../ui/alert-dialog';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Textarea } from '../../ui/textarea';
import { toast } from 'sonner@2.0.3';
import { useForm } from 'react-hook-form@7.55.0';
import { usePagination } from '../../../lib/usePagination';
import { DataPagination } from '../../ui/data-pagination';

export function DriverTask() {
  const [tasks, setTasks] = useState<DriverTaskType[]>([]);
  const [drivers, setDrivers] = useState<DriverRecord[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [fields, setFields] = useState<Field[]>([]);
  const [operationTypes, setOperationTypes] = useState<DataDictionary[]>([]);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showIssueDialog, setShowIssueDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedTask, setSelectedTask] = useState<DriverTaskType | null>(null);
  const [issuePhotos, setIssuePhotos] = useState<string[]>([]);
  
  // AlertDialog 状态
  const [showAcceptConfirm, setShowAcceptConfirm] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showCompleteConfirm, setShowCompleteConfirm] = useState(false);
  const [showTerminateConfirm, setShowTerminateConfirm] = useState(false);
  const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    // 加载驾驶员
    const driversData = localStorage.getItem('smart_agriculture_drivers');
    if (driversData) {
      setDrivers(JSON.parse(driversData));
    }

    // 加载农机
    setMachinery(machineryStorage.getAllMachinery());

    // 加载地块
    const fieldsData = localStorage.getItem('smart_agriculture_fields');
    if (fieldsData) {
      setFields(JSON.parse(fieldsData));
    }

    // 加载作业类型（从数据字典）
    const dictData = localStorage.getItem('smart_agriculture_data_dictionary');
    if (dictData) {
      const allDicts: DataDictionary[] = JSON.parse(dictData);
      const operationTypeDicts = allDicts.filter(
        dict => dict.category === 'operation_type' && dict.isActive
      );
      setOperationTypes(operationTypeDicts);
    }

    // 加载任务
    const tasksData = localStorage.getItem('smart_agriculture_driver_tasks');
    if (tasksData) {
      setTasks(JSON.parse(tasksData));
    } else {
      // 初始化示例任务
      const mockTasks: DriverTaskType[] = [
        // 待接收任务
        {
          id: 'task-1',
          taskNumber: 'T202510160001',
          machineryId: machinery[0]?.id || 'machinery-1',
          machineryName: machinery[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-1',
          driverName: '张三',
          fieldId: 'field-1',
          fieldName: '东一地块',
          operationType: '耕地',
          description: '对东一地块进行深耕作业，准备春播',
          plannedStartTime: '2025-10-17T08:00:00',
          plannedEndTime: '2025-10-17T17:00:00',
          status: '待接收',
          issues: [],
          priority: 'high',
          assignedBy: '调度中心',
          assignedAt: '2025-10-16T14:30:00',
          createdAt: '2025-10-16T14:30:00',
          updatedAt: '2025-10-16T14:30:00',
        },
        {
          id: 'task-2',
          taskNumber: 'T202510160002',
          machineryId: machinery[1]?.id || 'machinery-2',
          machineryName: machinery[1]?.name || '久保田播种机',
          driverId: 'driver-2',
          driverName: '李四',
          fieldId: 'field-2',
          fieldName: '西二地块',
          operationType: '播种',
          description: '玉米播种作业，注意播种深度控制在3-5cm',
          plannedStartTime: '2025-10-18T07:00:00',
          plannedEndTime: '2025-10-18T16:00:00',
          status: '待接收',
          issues: [],
          priority: 'medium',
          assignedBy: '调度中心',
          assignedAt: '2025-10-16T15:00:00',
          createdAt: '2025-10-16T15:00:00',
          updatedAt: '2025-10-16T15:00:00',
        },
        {
          id: 'task-3',
          taskNumber: 'T202510160003',
          machineryId: machinery[2]?.id || 'machinery-3',
          machineryName: machinery[2]?.name || '雷沃施肥机',
          driverId: 'driver-3',
          driverName: '王五',
          fieldId: 'field-3',
          fieldName: '南三地块',
          operationType: '施肥',
          description: '追肥作业，使用复合肥，每亩用量30kg',
          plannedStartTime: '2025-10-19T08:30:00',
          plannedEndTime: '2025-10-19T15:30:00',
          status: '待接收',
          issues: [],
          priority: 'low',
          assignedBy: '调度中心',
          assignedAt: '2025-10-16T15:30:00',
          createdAt: '2025-10-16T15:30:00',
          updatedAt: '2025-10-16T15:30:00',
        },
        
        // 已接收任务
        {
          id: 'task-4',
          taskNumber: 'T202510150004',
          machineryId: machinery[0]?.id || 'machinery-1',
          machineryName: machinery[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-4',
          driverName: '赵六',
          fieldId: 'field-4',
          fieldName: '北四地块',
          operationType: '耙地',
          description: '整地作业，确保地面平整',
          plannedStartTime: '2025-10-16T13:00:00',
          plannedEndTime: '2025-10-16T18:00:00',
          status: '已接收',
          issues: [],
          priority: 'medium',
          assignedBy: '调度中心',
          assignedAt: '2025-10-15T16:00:00',
          createdAt: '2025-10-15T16:00:00',
          updatedAt: '2025-10-16T09:20:00',
        },
        
        // 进行中任务
        {
          id: 'task-5',
          taskNumber: 'T202510160005',
          machineryId: machinery[1]?.id || 'machinery-2',
          machineryName: machinery[1]?.name || '大疆植保无人机',
          driverId: 'driver-5',
          driverName: '钱七',
          fieldId: 'field-5',
          fieldName: '东五地块',
          operationType: '喷药',
          description: '病虫害防治，喷洒杀虫剂和杀菌剂',
          plannedStartTime: '2025-10-16T09:00:00',
          plannedEndTime: '2025-10-16T12:00:00',
          actualStartTime: '2025-10-16T09:10:00',
          status: '进行中',
          issues: [],
          priority: 'high',
          assignedBy: '调度中心',
          assignedAt: '2025-10-15T18:00:00',
          createdAt: '2025-10-15T18:00:00',
          updatedAt: '2025-10-16T09:10:00',
        },
        {
          id: 'task-6',
          taskNumber: 'T202510160006',
          machineryId: machinery[2]?.id || 'machinery-3',
          machineryName: machinery[2]?.name || '洋马收割机',
          driverId: 'driver-6',
          driverName: '孙八',
          fieldId: 'field-6',
          fieldName: '西六地块',
          operationType: '收获',
          description: '小麦收获作业，注意收割高度',
          plannedStartTime: '2025-10-16T07:30:00',
          plannedEndTime: '2025-10-16T17:30:00',
          actualStartTime: '2025-10-16T07:45:00',
          status: '进行中',
          issues: [],
          priority: 'high',
          assignedBy: '调度中心',
          assignedAt: '2025-10-15T17:00:00',
          createdAt: '2025-10-15T17:00:00',
          updatedAt: '2025-10-16T07:45:00',
        },
        
        // 已取消任务（有问题上报）
        {
          id: 'task-7',
          taskNumber: 'T202510160007',
          machineryId: machinery[0]?.id || 'machinery-1',
          machineryName: machinery[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-7',
          driverName: '周九',
          fieldId: 'field-7',
          fieldName: '南七地块',
          operationType: '灌溉',
          description: '滴灌作业，确保灌溉均匀',
          plannedStartTime: '2025-10-16T06:00:00',
          plannedEndTime: '2025-10-16T14:00:00',
          actualStartTime: '2025-10-16T06:10:00',
          status: '已取消',
          issues: [
            {
              id: 'issue-1',
              taskId: 'task-7',
              type: '设备故障',
              description: '滴灌管道出现破损，需要更换',
              photos: [],
              reportedAt: '2025-10-16T10:30:00',
              reportedBy: '周九',
              status: 'pending',
            },
          ],
          priority: 'medium',
          assignedBy: '调度中心',
          assignedAt: '2025-10-15T20:00:00',
          createdAt: '2025-10-15T20:00:00',
          updatedAt: '2025-10-16T10:30:00',
        },
        
        // 已完成任务
        {
          id: 'task-8',
          taskNumber: 'T202510150008',
          machineryId: machinery[1]?.id || 'machinery-2',
          machineryName: machinery[1]?.name || '久保田播种机',
          driverId: 'driver-1',
          driverName: '张三',
          fieldId: 'field-8',
          fieldName: '东八地块',
          operationType: '播种',
          description: '大豆播种作业',
          plannedStartTime: '2025-10-15T08:00:00',
          plannedEndTime: '2025-10-15T16:00:00',
          actualStartTime: '2025-10-15T08:10:00',
          actualEndTime: '2025-10-15T15:50:00',
          status: '已完成',
          issues: [],
          priority: 'medium',
          assignedBy: '调度中心',
          assignedAt: '2025-10-14T18:00:00',
          createdAt: '2025-10-14T18:00:00',
          updatedAt: '2025-10-15T15:50:00',
        },
        {
          id: 'task-9',
          taskNumber: 'T202510140009',
          machineryId: machinery[2]?.id || 'machinery-3',
          machineryName: machinery[2]?.name || '雷沃施肥机',
          driverId: 'driver-2',
          driverName: '李四',
          fieldId: 'field-9',
          fieldName: '北九地块',
          operationType: '施肥',
          description: '底肥施用，每亩50kg有机肥',
          plannedStartTime: '2025-10-14T09:00:00',
          plannedEndTime: '2025-10-14T17:00:00',
          actualStartTime: '2025-10-14T09:05:00',
          actualEndTime: '2025-10-14T16:45:00',
          status: '已完成',
          issues: [],
          priority: 'low',
          assignedBy: '调度中心',
          assignedAt: '2025-10-13T16:00:00',
          createdAt: '2025-10-13T16:00:00',
          updatedAt: '2025-10-14T16:45:00',
        },
        {
          id: 'task-10',
          taskNumber: 'T202510130010',
          machineryId: machinery[0]?.id || 'machinery-1',
          machineryName: machinery[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-3',
          driverName: '王五',
          fieldId: 'field-10',
          fieldName: '西十地块',
          operationType: '耕地',
          description: '秋耕作业，深度25cm',
          plannedStartTime: '2025-10-13T08:00:00',
          plannedEndTime: '2025-10-13T17:00:00',
          actualStartTime: '2025-10-13T08:15:00',
          actualEndTime: '2025-10-13T17:10:00',
          status: '已完成',
          issues: [],
          priority: 'medium',
          assignedBy: '调度中心',
          assignedAt: '2025-10-12T17:00:00',
          createdAt: '2025-10-12T17:00:00',
          updatedAt: '2025-10-13T17:10:00',
        },
        
        // 已取消任务
        {
          id: 'task-11',
          taskNumber: 'T202510150011',
          machineryId: machinery[1]?.id || 'machinery-2',
          machineryName: machinery[1]?.name || '大疆植保无人机',
          driverId: 'driver-4',
          driverName: '赵六',
          fieldId: 'field-11',
          fieldName: '南十一地块',
          operationType: '喷药',
          description: '除草剂喷洒作业',
          plannedStartTime: '2025-10-15T14:00:00',
          plannedEndTime: '2025-10-15T17:00:00',
          status: '已取消',
          issues: [
            {
              id: 'issue-2',
              taskId: 'task-11',
              type: '天气影响',
              description: '突遇大风天气，不适宜喷药作业',
              photos: [],
              reportedAt: '2025-10-15T13:50:00',
              reportedBy: '赵六',
              status: 'resolved',
            },
          ],
          priority: 'low',
          assignedBy: '调度中心',
          assignedAt: '2025-10-15T10:00:00',
          createdAt: '2025-10-15T10:00:00',
          updatedAt: '2025-10-15T13:55:00',
        },
        {
          id: 'task-12',
          taskNumber: 'T202510140012',
          machineryId: machinery[2]?.id || 'machinery-3',
          machineryName: machinery[2]?.name || '洋马收割机',
          driverId: 'driver-5',
          driverName: '钱七',
          fieldId: 'field-12',
          fieldName: '东十二地块',
          operationType: '收获',
          description: '水稻收获作业',
          plannedStartTime: '2025-10-14T07:00:00',
          plannedEndTime: '2025-10-14T18:00:00',
          status: '已取消',
          issues: [
            {
              id: 'issue-3',
              taskId: 'task-12',
              type: '地块问题',
              description: '水稻尚未完全成熟，延后收获',
              photos: [],
              reportedAt: '2025-10-14T06:30:00',
              reportedBy: '钱七',
              status: 'resolved',
            },
          ],
          priority: 'high',
          assignedBy: '调度中心',
          assignedAt: '2025-10-13T18:00:00',
          createdAt: '2025-10-13T18:00:00',
          updatedAt: '2025-10-14T06:35:00',
        },
      ];
      localStorage.setItem('smart_agriculture_driver_tasks', JSON.stringify(mockTasks));
      setTasks(mockTasks);
    }
  };

  const { register, handleSubmit, setValue, reset } = useForm();
  const { register: registerIssue, handleSubmit: handleIssueSubmit, reset: resetIssue } = useForm();

  const onCreateTask = (data: any) => {
    const selectedMachinery = machinery.find(m => m.id === data.machineryId);
    const selectedDriver = drivers.find(d => d.id === data.driverId);
    const selectedField = fields.find(f => f.id === data.fieldId);

    const newTask: DriverTaskType = {
      id: `task-${Date.now()}`,
      taskNumber: `T${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(tasks.length + 1).padStart(4, '0')}`,
      machineryId: data.machineryId,
      machineryName: selectedMachinery?.name,
      driverId: data.driverId,
      driverName: selectedDriver?.name,
      fieldId: data.fieldId,
      fieldName: selectedField?.name,
      operationType: data.operationType,
      description: data.description,
      plannedStartTime: data.plannedStartTime,
      plannedEndTime: data.plannedEndTime,
      status: '待接收',
      issues: [],
      priority: data.priority,
      assignedBy: '系统管理员',
      assignedAt: new Date().toISOString(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    const newTasks = [...tasks, newTask];
    setTasks(newTasks);
    localStorage.setItem('smart_agriculture_driver_tasks', JSON.stringify(newTasks));
    toast.success('任务创建成功');
    setShowCreateDialog(false);
    reset();
  };

  const handleUpdateStatus = (taskId: string, newStatus: TaskStatus) => {
    const updatedTasks = tasks.map(task => {
      if (task.id === taskId) {
        const updated = { ...task, status: newStatus, updatedAt: new Date().toISOString() };
        
        // 如果是开始任务，记录实际开始时间
        if (newStatus === '进行中' && !task.actualStartTime) {
          updated.actualStartTime = new Date().toISOString();
        }
        
        // 如果是完成任务，记录实际结束时间并计算工时
        if (newStatus === '已完成' && !task.actualEndTime) {
          updated.actualEndTime = new Date().toISOString();
          if (updated.actualStartTime) {
            const start = new Date(updated.actualStartTime);
            const end = new Date(updated.actualEndTime);
            updated.workHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
          }
        }
        
        return updated;
      }
      return task;
    });

    setTasks(updatedTasks);
    localStorage.setItem('smart_agriculture_driver_tasks', JSON.stringify(updatedTasks));
    toast.success('任务状态更新成功');
  };

  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '待接收': return 'bg-muted text-muted-foreground';
      case '已接收': return 'bg-info-muted text-info';
      case '进行中': return 'bg-success-muted text-success';
      case '已完成': return 'bg-info-muted text-info';
      case '已取消': return 'bg-error-muted text-error';
      case '已终止': return 'bg-warning-muted text-warning';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  // 接收任务确认
  const handleAcceptTask = (taskId: string) => {
    setPendingTaskId(taskId);
    setShowAcceptConfirm(true);
  };

  const confirmAcceptTask = () => {
    if (pendingTaskId) {
      handleUpdateStatus(pendingTaskId, '已接收');
    }
    setShowAcceptConfirm(false);
    setPendingTaskId(null);
  };

  // 取消任务确认
  const handleCancelTask = (taskId: string) => {
    setPendingTaskId(taskId);
    setShowCancelConfirm(true);
  };

  const confirmCancelTask = () => {
    if (pendingTaskId) {
      handleUpdateStatus(pendingTaskId, '已取消');
    }
    setShowCancelConfirm(false);
    setPendingTaskId(null);
  };

  // 完成任务确认
  const handleCompleteTask = (taskId: string) => {
    setPendingTaskId(taskId);
    setShowCompleteConfirm(true);
  };

  const confirmCompleteTask = () => {
    if (pendingTaskId) {
      handleUpdateStatus(pendingTaskId, '已完成');
    }
    setShowCompleteConfirm(false);
    setPendingTaskId(null);
  };

  // 终止任务确认
  const handleTerminateTask = (taskId: string) => {
    setPendingTaskId(taskId);
    setShowTerminateConfirm(true);
  };

  const confirmTerminateTask = () => {
    if (pendingTaskId) {
      handleUpdateStatus(pendingTaskId, '已终止');
    }
    setShowTerminateConfirm(false);
    setPendingTaskId(null);
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'text-red-600';
      case 'medium': return 'text-orange-600';
      case 'low': return 'text-green-600';
      default: return 'text-gray-600';
    }
  };

  // 计算工时
  const calculateWorkHours = (task: DriverTaskType) => {
    if (task.workHours) {
      return task.workHours.toFixed(2);
    }
    if (task.actualStartTime && task.actualEndTime) {
      const start = new Date(task.actualStartTime);
      const end = new Date(task.actualEndTime);
      return ((end.getTime() - start.getTime()) / (1000 * 60 * 60)).toFixed(2);
    }
    return '-';
  };

  // 上报问题
  const handleReportIssue = (task: DriverTaskType) => {
    setSelectedTask(task);
    setIssuePhotos([]);
    setShowIssueDialog(true);
  };

  // 提交问题反馈
  const onSubmitIssue = (data: any) => {
    if (!selectedTask) return;

    const newIssue: TaskIssue = {
      id: `issue-${Date.now()}`,
      taskId: selectedTask.id,
      type: data.issueType,
      reportedAt: new Date().toISOString(),
      reportedBy: selectedTask.driverName || '驾驶员',
      description: data.description,
      photos: issuePhotos,
      status: 'pending',
    };

    const updatedTasks = tasks.map(task => {
      if (task.id === selectedTask.id) {
        return {
          ...task,
          issues: [...task.issues, newIssue],
          updatedAt: new Date().toISOString(),
        };
      }
      return task;
    });

    setTasks(updatedTasks);
    localStorage.setItem('smart_agriculture_driver_tasks', JSON.stringify(updatedTasks));
    toast.success('问题上报成功');
    setShowIssueDialog(false);
    resetIssue();
    setIssuePhotos([]);
  };

  // 模拟图片上传
  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      // 在实际应用中，这里应该上传到服务器并获取URL
      // 这里模拟生成URL
      const newPhotos = Array.from(files).map(file => URL.createObjectURL(file));
      setIssuePhotos([...issuePhotos, ...newPhotos]);
      toast.success(`已添加 ${files.length} 张图片`);
    }
  };

  // 删除图片
  const handleRemovePhoto = (index: number) => {
    setIssuePhotos(issuePhotos.filter((_, i) => i !== index));
  };

  // 查看任务详情
  const handleViewDetail = (task: DriverTaskType) => {
    setSelectedTask(task);
    setShowDetailDialog(true);
  };

  // 统计
  const stats = {
    total: tasks.length,
    pending: tasks.filter(t => t.status === '待接收').length,
    inProgress: tasks.filter(t => t.status === '进行中').length,
    completed: tasks.filter(t => t.status === '已完成').length,
    withIssues: tasks.filter(t => t.issues.length > 0).length,
  };

  // 重置示例数据
  const handleResetData = () => {
    localStorage.removeItem('smart_agriculture_driver_tasks');
    loadData();
    toast.success('示例数据已重置');
  };

  // 分页
  const pagination = usePagination(tasks, 10);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">驾驶员任务管理</h2>
          <p className="text-muted-foreground">创建、分配和跟踪驾驶员作业任务</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleResetData} size="sm">
            重置示例数据
          </Button>
          <Button onClick={() => setShowCreateDialog(true)}>
            <Plus className="w-4 h-4 mr-2" />
            创建任务
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总任务数</div>
          <div className="mt-1">{stats.total}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待接收</div>
          <div className="mt-1 text-gray-600">{stats.pending}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">进行中</div>
          <div className="mt-1 text-green-600">{stats.inProgress}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已完成</div>
          <div className="mt-1 text-purple-600">{stats.completed}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">有问题反馈</div>
          <div className="mt-1 text-orange-600">{stats.withIssues}</div>
        </Card>
      </div>

      {/* 任务列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>任务编号</TableHead>
              <TableHead>驾驶员</TableHead>
              <TableHead>农机</TableHead>
              <TableHead>地块</TableHead>
              <TableHead>作业类型</TableHead>
              <TableHead>计划时间</TableHead>
              <TableHead>工时</TableHead>
              <TableHead>优先级</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {pagination.paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={10} className="text-center text-muted-foreground py-8">
                  暂无任务
                </TableCell>
              </TableRow>
            ) : (
              pagination.paginatedData.map((task) => (
                <TableRow key={task.id}>
                  <TableCell>{task.taskNumber}</TableCell>
                  <TableCell>{task.driverName}</TableCell>
                  <TableCell>{task.machineryName}</TableCell>
                  <TableCell>{task.fieldName}</TableCell>
                  <TableCell>{task.operationType}</TableCell>
                  <TableCell>
                    <div className="text-sm">
                      {new Date(task.plannedStartTime).toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {calculateWorkHours(task)}h
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className={getPriorityColor(task.priority)}>
                      {task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低'}
                    </span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary" className={getStatusColor(task.status)}>
                      {task.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(task)}
                        title="查看详情"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      {task.status === '待接收' && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleAcceptTask(task.id)}
                            title="接收任务"
                          >
                            <CheckCircle className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleCancelTask(task.id)}
                            title="取消任务"
                            className="text-red-600 hover:text-red-700"
                          >
                            <XCircle className="w-4 h-4" />
                          </Button>
                        </>
                      )}
                      {task.status === '已接收' && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUpdateStatus(task.id, '进行中')}
                            title="开始任务"
                          >
                            开始
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleCancelTask(task.id)}
                            title="取消任务"
                            className="text-red-600 hover:text-red-700"
                          >
                            <XCircle className="w-4 h-4" />
                          </Button>
                        </>
                      )}
                      {task.status === '进行中' && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleCompleteTask(task.id)}
                            title="完成任务"
                          >
                            完成
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleTerminateTask(task.id)}
                            title="终止任务"
                            className="text-orange-600 hover:text-orange-700"
                          >
                            终止
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleReportIssue(task)}
                            title="上报问题"
                          >
                            <MessageSquare className="w-4 h-4 text-orange-600" />
                          </Button>
                        </>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {/* 分页 */}
        <DataPagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          pageSize={pagination.pageSize}
          totalItems={tasks.length}
          startIndex={pagination.startIndex}
          endIndex={pagination.endIndex}
          onPageChange={pagination.goToPage}
          onPageSizeChange={pagination.setPageSize}
          canPreviousPage={pagination.canPreviousPage}
          canNextPage={pagination.canNextPage}
        />
      </Card>

      {/* 任务详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>任务详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看任务的详细信息和问题反馈
            </DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <div className="space-y-4">
              <Card className="p-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="text-sm text-muted-foreground">任务编号</div>
                    <div className="mt-1">{selectedTask.taskNumber}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">状态</div>
                    <div className="mt-1">
                      <Badge variant="secondary" className={getStatusColor(selectedTask.status)}>
                        {selectedTask.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">驾驶员</div>
                    <div className="mt-1">{selectedTask.driverName}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">农机设备</div>
                    <div className="mt-1">{selectedTask.machineryName}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">作业地块</div>
                    <div className="mt-1">{selectedTask.fieldName || '-'}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">作业类型</div>
                    <div className="mt-1">{selectedTask.operationType}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">计划时间</div>
                    <div className="mt-1 text-sm">
                      {new Date(selectedTask.plannedStartTime).toLocaleString('zh-CN')}
                      <br />至<br />
                      {new Date(selectedTask.plannedEndTime).toLocaleString('zh-CN')}
                    </div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">实际工时</div>
                    <div className="mt-1 text-green-600">
                      <Clock className="w-4 h-4 inline mr-1" />
                      {calculateWorkHours(selectedTask)} 小时
                    </div>
                  </div>
                </div>
                {selectedTask.description && (
                  <div className="mt-4">
                    <div className="text-sm text-muted-foreground">任务描述</div>
                    <div className="mt-1">{selectedTask.description}</div>
                  </div>
                )}
              </Card>

              {/* 问题反馈列表 */}
              {selectedTask.issues.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-3">问题反馈 ({selectedTask.issues.length})</h4>
                  <div className="space-y-3">
                    {selectedTask.issues.map((issue) => (
                      <div key={issue.id} className="border rounded-lg p-3">
                        <div className="flex items-start justify-between mb-2">
                          <div>
                            <Badge variant="outline" className="text-xs">
                              {issue.type || issue.issueType}
                            </Badge>
                            <span className="text-sm text-muted-foreground ml-2">
                              {new Date(issue.reportedAt).toLocaleString('zh-CN')}
                            </span>
                          </div>
                          <Badge variant={
                            issue.status === '已解决' || issue.status === 'resolved' ? 'default' : 'secondary'
                          }>
                            {issue.status === 'pending' ? '待处理' : 
                             issue.status === 'processing' ? '处理中' :
                             issue.status === 'resolved' ? '已解决' : issue.status}
                          </Badge>
                        </div>
                        <div className="text-sm">{issue.description}</div>
                        {issue.photos && issue.photos.length > 0 && (
                          <div className="mt-2 flex gap-2">
                            {issue.photos.map((photo, idx) => (
                              <img
                                key={idx}
                                src={photo}
                                alt={`问题图片${idx + 1}`}
                                className="w-20 h-20 object-cover rounded border"
                              />
                            ))}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </Card>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 问题上报对话框 */}
      <Dialog open={showIssueDialog} onOpenChange={setShowIssueDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>上报问题</DialogTitle>
            <DialogDescription>
              请描述在执行任务过程中遇到的问题，可以上传相关图片
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleIssueSubmit(onSubmitIssue)}>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="issueType">问题类型 *</Label>
                <Select onValueChange={(value) => setValue('issueType', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择问题类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="设备故障">设备故障</SelectItem>
                    <SelectItem value="地块问题">地块问题</SelectItem>
                    <SelectItem value="天气影响">天气影响</SelectItem>
                    <SelectItem value="作业困难">作业困难</SelectItem>
                    <SelectItem value="其他问题">其他问题</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="issueDescription">问题描述 *</Label>
                <Textarea
                  id="issueDescription"
                  {...registerIssue('description', { required: true })}
                  placeholder="请详细描述遇到的问题..."
                  rows={4}
                />
              </div>

              <div className="space-y-2">
                <Label>上传图片（可选）</Label>
                <div className="border-2 border-dashed rounded-lg p-4">
                  <input
                    type="file"
                    accept="image/*"
                    multiple
                    onChange={handlePhotoUpload}
                    className="hidden"
                    id="photo-upload"
                  />
                  <label htmlFor="photo-upload" className="cursor-pointer">
                    <div className="flex flex-col items-center justify-center text-muted-foreground">
                      <Upload className="w-8 h-8 mb-2" />
                      <p className="text-sm">点击上传图片</p>
                      <p className="text-xs">支持多张图片</p>
                    </div>
                  </label>

                  {issuePhotos.length > 0 && (
                    <div className="mt-4 grid grid-cols-4 gap-2">
                      {issuePhotos.map((photo, index) => (
                        <div key={index} className="relative">
                          <img
                            src={photo}
                            alt={`上传图片${index + 1}`}
                            className="w-full h-24 object-cover rounded border"
                          />
                          <Button
                            type="button"
                            variant="destructive"
                            size="sm"
                            className="absolute top-1 right-1 h-6 w-6 p-0"
                            onClick={() => handleRemovePhoto(index)}
                          >
                            <X className="w-4 h-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="outline" onClick={() => setShowIssueDialog(false)}>
                取消
              </Button>
              <Button type="submit">
                提交问题
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 创建任务对话框 */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>创建新任务</DialogTitle>
            <DialogDescription className="sr-only">
              为驾驶员创建新的任务
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onCreateTask)}>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>选择农机 *</Label>
                  <Select onValueChange={(value) => setValue('machineryId', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择农机" />
                    </SelectTrigger>
                    <SelectContent>
                      {machinery.map(m => (
                        <SelectItem key={m.id} value={m.id}>
                          {m.name} - {m.model}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>选择驾驶员 *</Label>
                  <Select onValueChange={(value) => setValue('driverId', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择驾驶员" />
                    </SelectTrigger>
                    <SelectContent>
                      {drivers.filter(d => d.status === '在岗').map(d => (
                        <SelectItem key={d.id} value={d.id}>
                          {d.name} - {d.department}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>选择地块 *</Label>
                  <Select onValueChange={(value) => setValue('fieldId', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择地块" />
                    </SelectTrigger>
                    <SelectContent>
                      {fields.length === 0 ? (
                        <SelectItem value="no-fields" disabled>
                          暂无地块，请先在地块管理中添加
                        </SelectItem>
                      ) : (
                        fields.filter(f => f.status === 'active').map(f => (
                          <SelectItem key={f.id} value={f.id}>
                            {f.name} ({f.code}) - {f.area}亩
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>作业类型 *</Label>
                  <Select onValueChange={(value) => setValue('operationType', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择作业类型" />
                    </SelectTrigger>
                    <SelectContent>
                      {operationTypes.length === 0 ? (
                        <SelectItem value="no-types" disabled>
                          暂无作业类型，请在数据字典中配置
                        </SelectItem>
                      ) : (
                        operationTypes.map(type => (
                          <SelectItem key={type.id} value={type.label}>
                            {type.label}
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="plannedStartTime">计划开始时间 *</Label>
                  <Input id="plannedStartTime" type="datetime-local" {...register('plannedStartTime', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="plannedEndTime">计划结束时间 *</Label>
                  <Input id="plannedEndTime" type="datetime-local" {...register('plannedEndTime', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label>优先级 *</Label>
                  <Select onValueChange={(value) => setValue('priority', value)} defaultValue="medium">
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="high">高</SelectItem>
                      <SelectItem value="medium">中</SelectItem>
                      <SelectItem value="low">低</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">任务描述</Label>
                <Textarea id="description" {...register('description')} rows={3} />
              </div>
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="outline" onClick={() => setShowCreateDialog(false)}>
                取消
              </Button>
              <Button type="submit">
                创建任务
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 接收任务确认对话框 */}
      <AlertDialog open={showAcceptConfirm} onOpenChange={setShowAcceptConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认接收任务</AlertDialogTitle>
            <AlertDialogDescription>
              {pendingTaskId && tasks.find(t => t.id === pendingTaskId) && (
                <>
                  确定要接收任务 <span className="font-semibold text-green-700">{tasks.find(t => t.id === pendingTaskId)?.taskNumber}</span> 吗？
                  <br />
                  接收后将由您负责执行此任务。
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmAcceptTask} className="bg-green-600 hover:bg-green-700">
              确认接收
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 取消任务确认对话框 */}
      <AlertDialog open={showCancelConfirm} onOpenChange={setShowCancelConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认取消任务</AlertDialogTitle>
            <AlertDialogDescription>
              {pendingTaskId && tasks.find(t => t.id === pendingTaskId) && (
                <>
                  确定要取消任务 <span className="font-semibold text-red-700">{tasks.find(t => t.id === pendingTaskId)?.taskNumber}</span> 吗？
                  <br />
                  <span className="text-red-600 font-medium">取消后将无法恢复，请谨慎操作。</span>
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>我再想想</AlertDialogCancel>
            <AlertDialogAction onClick={confirmCancelTask} className="bg-red-600 hover:bg-red-700">
              确认取消
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 完成任务确认对话框 */}
      <AlertDialog open={showCompleteConfirm} onOpenChange={setShowCompleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认完成任务</AlertDialogTitle>
            <AlertDialogDescription>
              {pendingTaskId && tasks.find(t => t.id === pendingTaskId) && (
                <>
                  确定要将任务 <span className="font-semibold text-purple-700">{tasks.find(t => t.id === pendingTaskId)?.taskNumber}</span> 标记为已完成吗？
                  <br />
                  完成后将自动记录实际结束时间并计算工时。
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmCompleteTask} className="bg-purple-600 hover:bg-purple-700">
              确认完成
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 终止任务确认对话框 */}
      <AlertDialog open={showTerminateConfirm} onOpenChange={setShowTerminateConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认终止任务</AlertDialogTitle>
            <AlertDialogDescription>
              {pendingTaskId && tasks.find(t => t.id === pendingTaskId) && (
                <>
                  确定要终止任务 <span className="font-semibold text-orange-700">{tasks.find(t => t.id === pendingTaskId)?.taskNumber}</span> 吗？
                  <br />
                  <span className="text-orange-600 font-medium">终止后任务将停止执行，并记录为已终止状态。此操作不可恢复。</span>
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>我再想想</AlertDialogCancel>
            <AlertDialogAction onClick={confirmTerminateTask} className="bg-orange-600 hover:bg-orange-700">
              确认终止
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
