import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Checkbox } from '../ui/checkbox';
import { operationTypesData, OperationType, OperationTypeTemplate, OperationParameter } from '../../lib/operationTypes';
import {
  Plus,
  Edit,
  Trash2,
  FileText,
  MapPin,
  Clock,
  Download,
  Upload,
  Filter,
  Search,
  Scan,
  Camera,
  Navigation,
  User,
  Droplet,
  Sprout,
  Scissors,
  Package,
  Layers,
  ShoppingCart,
  Calculator,
  TrendingUp,
  BarChart3,
  CalendarDays,
  Eye,
  Save,
  Image as ImageIcon,
  QrCode,
  Leaf,
  Target,
  Gauge,
  Thermometer,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
} from 'recharts';

interface OperationExecutionProps {
  activePath?: string;
}

interface OperationRecord {
  id: string;
  operationType: OperationType;
  fieldId: string;
  fieldName: string;
  fieldArea: number;
  executor: string;
  teamName: string;
  executionDate: string;
  startTime: string;
  endTime: string;
  location: {
    latitude: number;
    longitude: number;
    address: string;
  };
  parameters: Record<string, any>;
  photos: string[];
  notes: string;
  status: '待验收' | '已验收';
  createdBy: string;
  createdAt: string;
  // 关联任务
  relatedTaskId?: string;
  relatedTaskName?: string;
  // 农资信息
  plannedMaterials?: { name: string; amount: number; unit: string }[]; // 计划农资
  actualMaterials?: { name: string; brand: string; amount: number; unit: string; batchNo: string }[]; // 实际使用农资
  // 验收信息
  acceptedBy?: string;
  acceptedAt?: string;
  acceptanceRating?: '优秀' | '良好' | '合格' | '不合格';
  acceptanceQualityScore?: number;
  acceptanceEfficiencyScore?: number;
  acceptanceComplianceScore?: number;
  acceptanceComment?: string;
  acceptanceIssues?: string;
}

// 任务接口（用于关联）
type TaskType = '播种' | '施肥' | '灌溉' | '除草' | '病虫害防治' | '采收';
type TaskStatus = '未开始' | '进行中' | '待验收' | '已完成';

interface Task {
  id: string;
  name: string;
  type: TaskType;
  fieldId: string;
  fieldName: string;
  crop: string;
  plannedStartDate: string;
  plannedEndDate: string;
  assignedTo: string;
  teamName: string;
  status: TaskStatus;
  description: string;
  materials: { name: string; amount: number; unit: string }[];
  estimatedHours: number;
  createdBy: string;
  createdAt: string;
}

export function OperationExecution({ activePath }: OperationExecutionProps) {
  const [activeTab, setActiveTab] = useState('type');
  const [showTypeDialog, setShowTypeDialog] = useState(false);
  const [showRecordDialog, setShowRecordDialog] = useState(false);
  const [showAcceptanceDialog, setShowAcceptanceDialog] = useState(false);
  const [selectedType, setSelectedType] = useState<OperationTypeTemplate | null>(null);
  const [selectedRecord, setSelectedRecord] = useState<OperationRecord | null>(null);
  const [filterType, setFilterType] = useState<string>('all');
  const [filterField, setFilterField] = useState<string>('all');
  const [filterExecutor, setFilterExecutor] = useState<string>('all');
  const [selectedField, setSelectedField] = useState<string>('');
  const [autoFilledData, setAutoFilledData] = useState<any>(null);
  const [selectedOperationType, setSelectedOperationType] = useState<OperationTypeTemplate | null>(null);
  const [uploadedPhotos, setUploadedPhotos] = useState<string[]>([]);
  const [acceptanceData, setAcceptanceData] = useState({
    rating: '优秀' as '优秀' | '良好' | '合格' | '不合格',
    qualityScore: 95,
    efficiencyScore: 90,
    complianceScore: 92,
    comment: '',
    inspector: '',
    issues: '',
  });
  
  // 关联任务相关状态
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [actualMaterials, setActualMaterials] = useState<{ name: string; brand: string; amount: number; unit: string; batchNo: string }[]>([]);
  const [recordForm, setRecordForm] = useState({
    operationType: '' as OperationType | '',
    fieldId: '',
    fieldName: '',
    fieldArea: 0,
    executor: '',
    teamName: '',
    executionDate: '',
    startTime: '',
    endTime: '',
    notes: '',
    relatedTaskId: '',
  });

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

  // 使用共享的农事类型库数据
  const [operationTypes, setOperationTypes] = useState<OperationTypeTemplate[]>(operationTypesData);

  // 模拟操作记录数据
  const [operationRecords, setOperationRecords] = useState<OperationRecord[]>([
    {
      id: 'record-1',
      operationType: '播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      fieldArea: 50.5,
      executor: '张三',
      teamName: '第一作业组',
      executionDate: '2024-03-01',
      startTime: '08:00',
      endTime: '12:00',
      location: {
        latitude: 30.25,
        longitude: 120.15,
        address: '浙江省杭州市余杭区东区1号地',
      },
      parameters: {
        '作物品种': '水稻',
        '种子品牌': '隆平高科',
        '种子批号': 'LP20240301',
        '播种量': 3.5,
        '播种方式': '条播',
        '行距': 30,
        '播种深度': 2.5,
      },
      photos: ['photo1.jpg', 'photo2.jpg'],
      notes: '天气晴朗，土壤墒情良好，适合播种',
      status: '已验收',
      createdBy: '张三',
      createdAt: '2024-03-01 12:30',
      acceptedBy: '农技主管',
      acceptedAt: '2024-03-01 14:00',
      acceptanceRating: '优秀',
      acceptanceQualityScore: 95,
      acceptanceEfficiencyScore: 92,
      acceptanceComplianceScore: 94,
      acceptanceComment: '播种作业规范，质量优良',
    },
    {
      id: 'record-2',
      operationType: '撒肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      fieldArea: 45.2,
      executor: '李四',
      teamName: '第二作业组',
      executionDate: '2024-03-10',
      startTime: '09:00',
      endTime: '11:30',
      location: {
        latitude: 30.28,
        longitude: 120.12,
        address: '浙江省杭州市余杭区西区2号地',
      },
      parameters: {
        '肥料类型': '复合肥',
        '肥料品牌': '金正大',
        '肥料批号': 'JZD20240305',
        '施肥量': 40,
        '总用量': 1808,
        '施肥方法': '基肥',
        '施肥位置': '全地块均匀撒施',
      },
      photos: ['photo3.jpg'],
      notes: '施肥后及时翻耕入土',
      status: '已验收',
      createdBy: '李四',
      createdAt: '2024-03-10 12:00',
      acceptedBy: '农技主管',
      acceptedAt: '2024-03-10 13:30',
      acceptanceRating: '良好',
      acceptanceQualityScore: 88,
      acceptanceEfficiencyScore: 85,
      acceptanceComplianceScore: 87,
      acceptanceComment: '施肥量准确，作业效率较好',
    },
    {
      id: 'record-3',
      operationType: '喷药',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      fieldArea: 60.3,
      executor: '王五',
      teamName: '第三作业组',
      executionDate: '2024-03-15',
      startTime: '06:00',
      endTime: '08:30',
      location: {
        latitude: 30.22,
        longitude: 120.18,
        address: '浙江省杭州市余杭区南区3号地',
      },
      parameters: {
        '农药类型': '杀虫剂',
        '农药品牌': '先正达',
        '农药批号': 'XZD20240310',
        '用药量': 40,
        '总用量': 2412,
        '稀释倍数': 1000,
        '喷洒方式': '无人机',
        '防治对象': '稻飞虱',
        '安全间隔期': 15,
      },
      photos: ['photo4.jpg', 'photo5.jpg'],
      notes: '选择无风天气喷洒，已穿戴防护装备',
      status: '待验收',
      createdBy: '王五',
      createdAt: '2024-03-15 09:00',
      relatedTaskId: 'task-3',
      relatedTaskName: '南区3号地病虫害防治',
    },
    {
      id: 'record-4',
      operationType: '灌溉',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      fieldArea: 50.5,
      executor: '赵六',
      teamName: '第一作业组',
      executionDate: '2024-03-20',
      startTime: '14:00',
      endTime: '18:00',
      location: {
        latitude: 30.25,
        longitude: 120.15,
        address: '浙江省杭州市余杭区东区1号地',
      },
      parameters: {
        '灌溉方式': '滴灌',
        '灌溉时长': 4,
        '水量': 100,
        '单位水量': 1.98,
        '水源': '水库',
      },
      photos: [],
      notes: '滴灌系统运行正常',
      status: '已验收',
      createdBy: '赵六',
      createdAt: '2024-03-20 18:30',
      acceptedBy: '农技主管',
      acceptedAt: '2024-03-20 19:00',
      acceptanceRating: '良好',
      acceptanceQualityScore: 85,
      acceptanceEfficiencyScore: 88,
      acceptanceComplianceScore: 90,
      acceptanceComment: '灌溉作业规范，系统运行正常',
    },
  ]);

  // 模拟地块数据
  const mockFields = [
    { id: 'field-1', name: '东区1号地', area: 50.5, crop: '水稻' },
    { id: 'field-2', name: '西区2号地', area: 45.2, crop: '水稻' },
    { id: 'field-3', name: '南区3号地', area: 60.3, crop: '玉米' },
    { id: 'field-4', name: '北区4号地', area: 44.0, crop: '蔬菜' },
  ];
  
  // 模拟任务数据
  const [availableTasks] = useState<Task[]>([
    {
      id: 'task-1',
      name: '东区1号地水稻播种',
      type: '播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '水稻',
      plannedStartDate: '2024-03-01',
      plannedEndDate: '2024-03-03',
      assignedTo: '张三',
      teamName: '第一作业组',
      status: '进行中',
      description: '进行水稻种子浸种催芽并播种',
      materials: [
        { name: '水稻种子', amount: 177, unit: 'kg' },
        { name: '浸种剂', amount: 0.5, unit: 'L' },
      ],
      estimatedHours: 25,
      createdBy: '系统',
      createdAt: '2024-02-25',
    },
    {
      id: 'task-2',
      name: '西区2号地施基肥',
      type: '施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '水稻',
      plannedStartDate: '2024-03-10',
      plannedEndDate: '2024-03-12',
      assignedTo: '李四',
      teamName: '第二作业组',
      status: '进行中',
      description: '施用有机肥和复合肥作为基肥',
      materials: [
        { name: '有机肥', amount: 18080, unit: 'kg' },
        { name: '复合肥', amount: 1808, unit: 'kg' },
      ],
      estimatedHours: 16,
      createdBy: '系统',
      createdAt: '2024-03-05',
    },
    {
      id: 'task-3',
      name: '南区3号地病虫害防治',
      type: '病虫害防治',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '玉米',
      plannedStartDate: '2024-03-15',
      plannedEndDate: '2024-03-16',
      assignedTo: '王五',
      teamName: '第三作业组',
      status: '未开始',
      description: '喷洒农药防治玉米常见病虫害',
      materials: [
        { name: '杀虫剂', amount: 2.4, unit: 'L' },
        { name: '杀菌剂', amount: 1.8, unit: 'L' },
      ],
      estimatedHours: 12,
      createdBy: '李四',
      createdAt: '2024-03-10',
    },
    {
      id: 'task-4',
      name: '北区4号地灌溉',
      type: '灌溉',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '蔬菜',
      plannedStartDate: '2024-03-20',
      plannedEndDate: '2024-03-20',
      assignedTo: '赵六',
      teamName: '第一作业组',
      status: '未开始',
      description: '进行滴灌系统灌溉',
      materials: [],
      estimatedHours: 6,
      createdBy: '张三',
      createdAt: '2024-03-15',
    },
  ]);

  // 模拟农资数据库
  const mockMaterials = [
    { code: 'LP20240301', name: '隆平高科优质稻1号', type: '种子', brand: '隆平高科', spec: '25kg/袋' },
    { code: 'JZD20240305', name: '金正大复合肥', type: '肥料', brand: '金正大', spec: 'N-P-K:15-15-15', unit: 'kg' },
    { code: 'XZD20240310', name: '先正达杀虫剂', type: '农药', brand: '先正达', spec: '200ml/瓶' },
  ];

  const handleCreateType = () => {
    setSelectedType(null);
    setShowTypeDialog(true);
  };

  const handleEditType = (type: OperationTypeTemplate) => {
    setSelectedType(type);
    setShowTypeDialog(true);
  };

  const handleDeleteType = (typeId: string) => {
    setOperationTypes(operationTypes.filter(t => t.id !== typeId));
    toast.success('农事类型已删除');
  };

  const handleCreateRecord = () => {
    setSelectedRecord(null);
    setSelectedTask(null);
    setSelectedField('');
    setAutoFilledData(null);
    setSelectedOperationType(null);
    setUploadedPhotos([]);
    setActualMaterials([]);
    setRecordForm({
      operationType: '',
      fieldId: '',
      fieldName: '',
      fieldArea: 0,
      executor: '',
      teamName: '',
      executionDate: '',
      startTime: '',
      endTime: '',
      notes: '',
      relatedTaskId: '',
    });
    setShowRecordDialog(true);
  };

  const handleEditRecord = (record: OperationRecord) => {
    setSelectedRecord(record);
    
    // 如果有关联任务，加载任务信息
    if (record.relatedTaskId) {
      const task = availableTasks.find(t => t.id === record.relatedTaskId);
      if (task) {
        setSelectedTask(task);
      }
    }
    
    // 加载表单数据
    setRecordForm({
      operationType: record.operationType,
      fieldId: record.fieldId,
      fieldName: record.fieldName,
      fieldArea: record.fieldArea,
      executor: record.executor,
      teamName: record.teamName,
      executionDate: record.executionDate,
      startTime: record.startTime,
      endTime: record.endTime,
      notes: record.notes,
      relatedTaskId: record.relatedTaskId || '',
    });
    
    // 加载实际农资
    setActualMaterials(record.actualMaterials || []);
    
    // 加载照片
    setUploadedPhotos(record.photos || []);
    
    setShowRecordDialog(true);
  };
  
  // 处理任务选择
  const handleTaskSelect = (taskId: string) => {
    if (taskId === 'none') {
      setSelectedTask(null);
      setRecordForm(prev => ({ ...prev, relatedTaskId: '' }));
      return;
    }
    
    const task = availableTasks.find(t => t.id === taskId);
    if (!task) return;
    
    setSelectedTask(task);
    
    // 自动填充任务信息
    setRecordForm(prev => ({
      ...prev,
      relatedTaskId: task.id,
      operationType: task.type as OperationType,
      fieldId: task.fieldId,
      fieldName: task.fieldName,
      executor: task.assignedTo,
      teamName: task.teamName,
      executionDate: task.plannedStartDate,
    }));
    
    // 获取地块面积
    const field = mockFields.find(f => f.id === task.fieldId);
    if (field) {
      setRecordForm(prev => ({ ...prev, fieldArea: field.area }));
    }
    
    // 初始化实际农资列表（基于计划农资）
    if (task.materials && task.materials.length > 0) {
      const initialActualMaterials = task.materials.map(m => ({
        name: m.name,
        brand: '',
        amount: m.amount,
        unit: m.unit,
        batchNo: '',
      }));
      setActualMaterials(initialActualMaterials);
    }
    
    toast.success(`已关联任务：${task.name}`);
  };
  
  // 添加实际农资
  const handleAddActualMaterial = () => {
    setActualMaterials([
      ...actualMaterials,
      { name: '', brand: '', amount: 0, unit: 'kg', batchNo: '' }
    ]);
  };
  
  // 更新实际农资
  const handleUpdateActualMaterial = (index: number, field: string, value: any) => {
    const updated = [...actualMaterials];
    updated[index] = { ...updated[index], [field]: value };
    setActualMaterials(updated);
  };
  
  // 删除实际农资
  const handleRemoveActualMaterial = (index: number) => {
    setActualMaterials(actualMaterials.filter((_, i) => i !== index));
  };

  const handleDeleteRecord = (recordId: string) => {
    setOperationRecords(operationRecords.filter(r => r.id !== recordId));
    toast.success('操作记录已删除');
  };

  // 扫描农资条码
  const handleScanMaterial = () => {
    // 模拟扫码结果
    const scannedCode = 'JZD20240305';
    const material = mockMaterials.find(m => m.code === scannedCode);
    if (material) {
      toast.success(`已识别：${material.name}`);
      setAutoFilledData(prev => ({
        ...prev,
        materialCode: material.code,
        materialName: material.name,
        materialBrand: material.brand,
        materialSpec: material.spec,
      }));
    }
  };

  // 选择地块后自动带出面积并计算推荐用量
  const handleFieldChange = (fieldId: string) => {
    setSelectedField(fieldId);
    const field = mockFields.find(f => f.id === fieldId);
    if (field) {
      // 模拟计算推荐用量（以施肥为例，每亩40kg）
      const recommendedAmount = field.area * 40;
      setAutoFilledData(prev => ({
        ...prev,
        fieldArea: field.area,
        fieldCrop: field.crop,
        recommendedAmount: recommendedAmount,
      }));
      toast.success(`已自动计算：地块面积 ${field.area} 亩，推荐用量 ${recommendedAmount} kg`);
    }
  };

  // 获取当前位置
  const handleGetLocation = () => {
    // 模拟GPS定位
    const mockLocation = {
      latitude: 30.25 + Math.random() * 0.1,
      longitude: 120.15 + Math.random() * 0.1,
      address: '浙江省杭州市余杭区',
    };
    setAutoFilledData(prev => ({
      ...prev,
      location: mockLocation,
    }));
    toast.success(`位置已获取：${mockLocation.address}`);
  };

  // 处理农事类型选择
  const handleOperationTypeChange = (typeName: string) => {
    const type = operationTypes.find(t => t.name === typeName);
    setSelectedOperationType(type || null);
  };

  // 处理图片上传
  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      const newPhotos = Array.from(files).map(file => URL.createObjectURL(file));
      setUploadedPhotos(prev => [...prev, ...newPhotos]);
      toast.success(`已上传 ${files.length} 张图片`);
    }
  };

  // 删除图片
  const handlePhotoRemove = (index: number) => {
    setUploadedPhotos(prev => prev.filter((_, i) => i !== index));
    toast.success('图片已删除');
  };

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

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

    // 更新记录状态和验收信息
    setOperationRecords(operationRecords.map(r => 
      r.id === selectedRecord.id 
        ? { 
            ...r, 
            status: '已验收',
            acceptedBy: acceptanceData.inspector,
            acceptedAt: new Date().toLocaleString('zh-CN', { 
              year: 'numeric', 
              month: '2-digit', 
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            }),
            acceptanceRating: acceptanceData.rating,
            acceptanceQualityScore: acceptanceData.qualityScore,
            acceptanceEfficiencyScore: acceptanceData.efficiencyScore,
            acceptanceComplianceScore: acceptanceData.complianceScore,
            acceptanceComment: acceptanceData.comment,
            acceptanceIssues: acceptanceData.issues,
          } 
        : r
    ));
    
    // 如果有关联任务，同步验收该任务
    if (selectedRecord.relatedTaskId) {
      const relatedTask = availableTasks.find(t => t.id === selectedRecord.relatedTaskId);
      if (relatedTask) {
        // 这里应该调用任务验收的逻辑，更新任务状态为"已完成"
        // 由于availableTasks是const，这里仅做提示
        console.log('同步验收关联任务:', relatedTask.name);
      }
    }
    
    // 提示验收完成并同步至关联任务
    const syncMessage = selectedRecord.relatedTaskId 
      ? `，已同步验收关联任务"${selectedRecord.relatedTaskName || ''}"`
      : '';
    toast.success(`操作记录验收完成（评价：${acceptanceData.rating}）${syncMessage}`);
    setShowAcceptanceDialog(false);
    setSelectedRecord(null);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '待验收': return 'bg-warning text-warning-foreground';
      case '已验收': return 'bg-success text-success-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getCategoryColor = (category: string) => {
    switch (category) {
      case '土地整理': return 'bg-muted text-muted-foreground';
      case '种植管理': return 'bg-success-muted text-success-muted-foreground';
      case '田间管理': return 'bg-info-muted text-info-muted-foreground';
      case '植保管理': return 'bg-error-muted text-error-muted-foreground';
      case '收获管理': return 'bg-warning-muted text-warning-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const filteredRecords = operationRecords.filter(r => {
    if (filterType !== 'all' && r.operationType !== filterType) return false;
    if (filterField !== 'all' && r.fieldId !== filterField) return false;
    if (filterExecutor !== 'all' && r.executor !== filterExecutor) return false;
    return true;
  });

  // 统计数据
  const recordsByType = operationTypes.map(type => ({
    name: type.name,
    数量: operationRecords.filter(r => r.operationType === type.name).length,
  }));

  const recordsTrend = [
    { date: '3/1', 操作次数: 5 },
    { date: '3/5', 操作次数: 8 },
    { date: '3/10', 操作次数: 12 },
    { date: '3/15', 操作次数: 10 },
    { date: '3/20', 操作次数: 7 },
  ];

  const exportToExcel = () => {
    toast.success('正在导出Excel文件...');
    // 实际项目中这里会调用导出功能
  };

  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">
          {activeTab === 'type' && (
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateType}>
              <Plus className="w-4 h-4 mr-2" />
              新增类型
            </Button>
          )}
          {activeTab === 'record' && (
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateRecord}>
              <Plus className="w-4 h-4 mr-2" />
              新增记录
            </Button>
          )}
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="type">农事类型</TabsTrigger>
          <TabsTrigger value="record">操作录入</TabsTrigger>
          <TabsTrigger value="log">日志多维查询</TabsTrigger>
        </TabsList>

        {/* 农事类型 */}
        <TabsContent value="type" className="space-y-4">
          {/* 类型库说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Layers 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>
                  <li>• 支持自定义新增农事类型，灵活适应不同农业生产需求</li>
                  <li>• 参数支持必填/选填、单位定义、选项配置等</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 按分类展示 */}
          {['土地整理', '种植管理', '田间管理', '植保管理', '收获管理'].map(category => {
            const categoryTypes = operationTypes.filter(t => t.category === category);
            if (categoryTypes.length === 0) return null;

            return (
              <Card key={category} className="p-6">
                <h3 className="mb-4 flex items-center gap-2">
                  <Badge className={getCategoryColor(category)}>
                    {category}
                  </Badge>
                  <span className="text-muted-foreground text-sm">
                    ({categoryTypes.length} 种操作类型)
                  </span>
                </h3>
                <div className="grid grid-cols-3 gap-4">
                  {categoryTypes.map(type => (
                    <Card key={type.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <span className="text-2xl">{type.icon}</span>
                          <div>
                            <h4>{type.name}</h4>
                            <p className="text-xs text-muted-foreground">
                              {type.parameters.length} 个参数
                            </p>
                          </div>
                        </div>
                        <div className="flex gap-1">
                          <Button size="sm" variant="outline" onClick={() => handleEditType(type)}>
                            <Edit className="w-3 h-3" />
                          </Button>
                          <Button size="sm" variant="outline" onClick={() => handleDeleteType(type.id)}>
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      </div>

                      <p className="text-sm text-muted-foreground mb-3">
                        {type.description}
                      </p>

                      <div className="space-y-2">
                        <p className="text-xs font-medium text-muted-foreground">关键参数：</p>
                        <div className="space-y-1">
                          {type.parameters.slice(0, 4).map((param, i) => (
                            <div key={i} className="flex items-center justify-between text-xs">
                              <span className="flex items-center gap-1">
                                {param.required && <span className="text-red-500">*</span>}
                                {param.name}
                              </span>
                              <Badge variant="outline" className="text-xs">
                                {param.type === 'number' && param.unit ? param.unit : param.type}
                              </Badge>
                            </div>
                          ))}
                          {type.parameters.length > 4 && (
                            <p className="text-xs text-muted-foreground">
                              ...还有 {type.parameters.length - 4} 个参数
                            </p>
                          )}
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </Card>
            );
          })}
        </TabsContent>

        {/* 操作录入 */}
        <TabsContent value="record" className="space-y-4">
          {/* 快捷操作入口 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={handleCreateRecord}>
              <div className="flex flex-col items-center text-center">
                <div className="p-3 bg-green-100 rounded-lg mb-2">
                  <Sprout className="w-6 h-6 text-green-600" />
                </div>
                <h4 className="mb-1">播种记录</h4>
                <p className="text-xs text-muted-foreground">记录播种作业</p>
              </div>
            </Card>

            <Card className="p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={handleCreateRecord}>
              <div className="flex flex-col items-center text-center">
                <div className="p-3 bg-orange-100 rounded-lg mb-2">
                  <Package className="w-6 h-6 text-orange-600" />
                </div>
                <h4 className="mb-1">施肥记录</h4>
                <p className="text-xs text-muted-foreground">记录施肥作业</p>
              </div>
            </Card>

            <Card className="p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={handleCreateRecord}>
              <div className="flex flex-col items-center text-center">
                <div className="p-3 bg-blue-100 rounded-lg mb-2">
                  <Droplet className="w-6 h-6 text-blue-600" />
                </div>
                <h4 className="mb-1">灌溉记录</h4>
                <p className="text-xs text-muted-foreground">记录灌溉作业</p>
              </div>
            </Card>

            <Card className="p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={handleCreateRecord}>
              <div className="flex flex-col items-center text-center">
                <div className="p-3 bg-red-100 rounded-lg mb-2">
                  <Target className="w-6 h-6 text-red-600" />
                </div>
                <h4 className="mb-1">喷药记录</h4>
                <p className="text-xs text-muted-foreground">记录植保作业</p>
              </div>
            </Card>
          </div>

          {/* 最近记录 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Clock className="w-5 h-5 text-purple-600" />
              最近操作记录
            </h3>
            <div className="space-y-4">
              {operationRecords.slice(0, 5).map(record => (
                <Card key={record.id} className="p-4 border-l-4 border-l-green-500">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className="p-2 bg-green-100 rounded-lg">
                        <FileText className="w-5 h-5 text-green-600" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{record.operationType} - {record.fieldName}</h4>
                          <Badge className={getStatusColor(record.status)}>
                            {record.status}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          记录ID: {record.id} | 执行人: {record.executor} | {record.executionDate}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      {record.status === '待验收' && (
                        <Button 
                          size="sm" 
                          className="bg-blue-600 hover:bg-blue-700"
                          onClick={() => handleOpenAcceptanceDialog(record)}
                        >
                          <Eye className="w-4 h-4 mr-1" />
                          验收
                        </Button>
                      )}
                      {record.status !== '已验收' && (
                        <>
                          <Button size="sm" variant="outline" onClick={() => handleEditRecord(record)}>
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button size="sm" variant="outline" onClick={() => handleDeleteRecord(record.id)}>
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </>
                      )}
                    </div>
                  </div>

                  <div className="grid grid-cols-4 gap-3 mb-3">
                    <div className="p-2 bg-gray-50 rounded">
                      <p className="text-xs text-muted-foreground">地块面积</p>
                      <p className="text-sm font-medium">{record.fieldArea} 亩</p>
                    </div>
                    <div className="p-2 bg-gray-50 rounded">
                      <p className="text-xs text-muted-foreground">作业时间</p>
                      <p className="text-sm font-medium">{record.startTime}-{record.endTime}</p>
                    </div>
                    <div className="p-2 bg-gray-50 rounded">
                      <p className="text-xs text-muted-foreground">班组</p>
                      <p className="text-sm font-medium">{record.teamName}</p>
                    </div>
                    <div className="p-2 bg-gray-50 rounded">
                      <p className="text-xs text-muted-foreground">现场照片</p>
                      <p className="text-sm font-medium">{record.photos.length} 张</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-2 bg-blue-50 rounded">
                      <p className="text-xs text-blue-900 mb-1">操作参数</p>
                      <div className="space-y-1">
                        {Object.entries(record.parameters).slice(0, 3).map(([key, value]) => (
                          <p key={key} className="text-xs text-blue-800">
                            {key}: {value}
                          </p>
                        ))}
                      </div>
                    </div>
                    <div className="p-2 bg-green-50 rounded">
                      <p className="text-xs text-green-900 mb-1">位置信息</p>
                      <p className="text-xs text-green-800 flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {record.location.address}
                      </p>
                      <p className="text-xs text-green-800 mt-1">
                        坐标: {record.location.latitude.toFixed(4)}, {record.location.longitude.toFixed(4)}
                      </p>
                    </div>
                  </div>

                  {/* 验收信息 */}
                  {record.status === '已验收' && record.acceptedBy && (
                    <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs font-medium text-green-900">验收评价</p>
                        <Badge className="bg-green-600">{record.acceptanceRating}</Badge>
                      </div>
                      <div className="grid grid-cols-3 gap-2 text-xs mb-2">
                        <div>
                          <span className="text-muted-foreground">质量: </span>
                          <span className="font-medium text-green-700">{record.acceptanceQualityScore}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">效率: </span>
                          <span className="font-medium text-blue-700">{record.acceptanceEfficiencyScore}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">规范: </span>
                          <span className="font-medium text-purple-700">{record.acceptanceComplianceScore}</span>
                        </div>
                      </div>
                      <p className="text-xs text-green-800">
                        验收人: {record.acceptedBy} | {record.acceptedAt}
                      </p>
                      {record.acceptanceComment && (
                        <p className="text-xs text-green-800 mt-1">
                          {record.acceptanceComment}
                        </p>
                      )}
                    </div>
                  )}
                </Card>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 日志多维查询 */}
        <TabsContent value="log" className="space-y-4">
          {/* 查询条件 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Filter className="w-5 h-5 text-blue-600" />
              查询条件
            </h3>
            <div className="grid grid-cols-5 gap-4 mb-4">
              <div>
                <label>地块</label>
                <Select value={filterField} onValueChange={setFilterField}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择地块" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部地块</SelectItem>
                    {mockFields.map(field => (
                      <SelectItem key={field.id} value={field.id}>
                        {field.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label>农事类型</label>
                <Select value={filterType} onValueChange={setFilterType}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    {operationTypes.map(type => (
                      <SelectItem key={type.id} value={type.name}>
                        {type.icon} {type.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label>执行人</label>
                <Select value={filterExecutor} onValueChange={setFilterExecutor}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择执行人" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部人员</SelectItem>
                    <SelectItem value="张三">张三</SelectItem>
                    <SelectItem value="李四">李四</SelectItem>
                    <SelectItem value="王五">王五</SelectItem>
                    <SelectItem value="赵六">赵六</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label>开始日期</label>
                <Input type="date" className="mt-2" />
              </div>

              <div>
                <label>结束日期</label>
                <Input type="date" className="mt-2" />
              </div>
            </div>

            <div className="flex gap-2">
              <Button className="bg-blue-600 hover:bg-blue-700">
                <Search className="w-4 h-4 mr-2" />
                查询
              </Button>
              <Button variant="outline">
                重置
              </Button>
              <Button variant="outline" className="ml-auto" onClick={exportToExcel}>
                <Download className="w-4 h-4 mr-2" />
                导出Excel
              </Button>
            </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-green-600">{operationRecords.length}</p>
                </div>
                <FileText 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-blue-600">
                    {new Set(operationRecords.map(r => r.fieldId)).size}
                  </p>
                </div>
                <MapPin className="w-12 h-12 text-blue-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">参与人员</p>
                  <p className="mt-2 text-3xl text-purple-600">
                    {new Set(operationRecords.map(r => r.executor)).size}
                  </p>
                </div>
                <User 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">
                    {operationRecords.filter(r => r.status === '待验收').length}
                  </p>
                </div>
                <Clock className="w-12 h-12 text-orange-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 统计图表 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-green-600" />
                操作类型统计
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={recordsByType}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="数量" fill="#22c55e" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-blue-600" />
                操作频次趋势
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={recordsTrend}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <Tooltip />
                    <Line type="monotone" dataKey="操作次数" stroke="#3b82f6" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </div>

          {/* 查询结果列表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Eye className="w-5 h-5 text-purple-600" />
              查询结果 ({filteredRecords.length} 条记录)
            </h3>
            <div className="space-y-3">
              {filteredRecords.map(record => (
                <Card key={record.id} className="p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant="outline">{record.operationType}</Badge>
                        <h4>{record.fieldName}</h4>
                        <Badge className={getStatusColor(record.status)}>
                          {record.status}
                        </Badge>
                        {record.status === '已验收' && record.acceptanceRating && (
                          <Badge className="bg-green-600">{record.acceptanceRating}</Badge>
                        )}
                      </div>
                      <div className="grid grid-cols-6 gap-4 text-sm">
                        <div>
                          <p className="text-xs text-muted-foreground">执行人</p>
                          <p className="font-medium">{record.executor}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">执行日期</p>
                          <p className="font-medium">{record.executionDate}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">作业时间</p>
                          <p className="font-medium">{record.startTime}-{record.endTime}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">地块面积</p>
                          <p className="font-medium">{record.fieldArea} 亩</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">位置</p>
                          <p className="font-medium text-xs">{record.location.latitude.toFixed(2)}, {record.location.longitude.toFixed(2)}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">照片</p>
                          <p className="font-medium">{record.photos.length} 张</p>
                        </div>
                      </div>
                      
                      {/* 验收信息 */}
                      {record.status === '已验收' && record.acceptedBy && (
                        <div className="mt-3 p-2 bg-green-50 border border-green-200 rounded text-xs">
                          <div className="grid grid-cols-4 gap-2">
                            <div>
                              <span className="text-muted-foreground">质量: </span>
                              <span className="font-medium text-green-700">{record.acceptanceQualityScore}</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">效率: </span>
                              <span className="font-medium text-blue-700">{record.acceptanceEfficiencyScore}</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">规范: </span>
                              <span className="font-medium text-purple-700">{record.acceptanceComplianceScore}</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">验收: </span>
                              <span className="font-medium">{record.acceptedBy}</span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                    <div className="flex flex-col gap-2">
                      {record.status === '待验收' && (
                        <Button 
                          size="sm" 
                          className="bg-blue-600 hover:bg-blue-700"
                          onClick={() => handleOpenAcceptanceDialog(record)}
                        >
                          <Eye className="w-4 h-4 mr-2" />
                          验收
                        </Button>
                      )}
                      <Button size="sm" variant="outline">
                        <Eye className="w-4 h-4 mr-2" />
                        详情
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 查询说明 */}
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Search className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">多维度查询功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• 支持按地块、农事类型、执行人、时间范围等多个维度组合查询</li>
                  <li>• 查询结果以列表形式展示，包含关键信息一目了然</li>
                  <li>• 支持导出为Excel文件，便于离线分析和存档</li>
                  <li>• 可用于成本核算、效率分析、质量追溯等多种场景</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 创建/编辑农事类型对话框 */}
      <Dialog open={showTypeDialog} onOpenChange={setShowTypeDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedType ? '编辑农事类型' : '新增农事类型'}</DialogTitle>
            <DialogDescription>
              定义农事操作类型的基本信息和参数模板
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-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="土地整理">土地整理</SelectItem>
                    <SelectItem value="种植管理">种植管理</SelectItem>
                    <SelectItem value="田间管理">田间管理</SelectItem>
                    <SelectItem value="植保管理">植保管理</SelectItem>
                    <SelectItem value="收获管理">收获管理</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <label>描述</label>
              <Textarea placeholder="请输入类型描述" className="mt-2" rows={2} />
            </div>

            <div>
              <label>参数配置</label>
              <div className="mt-2 space-y-3">
                <Card className="p-3 bg-gray-50">
                  <div className="grid grid-cols-4 gap-2">
                    <Input placeholder="参数名称" />
                    <Select>
                      <SelectTrigger>
                        <SelectValue placeholder="类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="text">文本</SelectItem>
                        <SelectItem value="number">数字</SelectItem>
                        <SelectItem value="select">选择</SelectItem>
                        <SelectItem value="date">日期</SelectItem>
                        <SelectItem value="image">图片</SelectItem>
                      </SelectContent>
                    </Select>
                    <Input placeholder="单位（可选）" />
                    <div className="flex items-center gap-2">
                      <Checkbox id="required" />
                      <label htmlFor="required" className="text-sm cursor-pointer">
                        必填
                      </label>
                      <Button size="sm" variant="outline">
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>
                </Card>
                <Button size="sm" variant="outline" className="w-full">
                  <Plus className="w-4 h-4 mr-2" />
                  添加参数
                </Button>
              </div>
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowTypeDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700">
                <Save className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 创建/编辑操作记录对话框 */}
      <Dialog open={showRecordDialog} onOpenChange={setShowRecordDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedRecord ? '编辑操作记录' : '新增操作记录'}</DialogTitle>
            <DialogDescription>
              记录农事操作的详细信息，支持关联任务并记录农资使用情况
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {/* 关联任务选择 */}
            <Card className="p-4 bg-green-50 border-green-200">
              <div className="flex items-start gap-2 mb-3">
                <CalendarDays className="w-5 h-5 text-green-600 mt-0.5" />
                <div className="flex-1">
                  <h4 className="text-green-900">关联农事任务（可选）</h4>
                  <p className="text-xs text-green-700 mt-1">
                    选择已创建的农事任务，系统将自动填充执行信息
                  </p>
                </div>
              </div>
              <Select 
                value={recordForm.relatedTaskId || "none"} 
                onValueChange={handleTaskSelect}
              >
                <SelectTrigger className="bg-white">
                  <SelectValue placeholder="不关联任务，手动填写" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">
                    <span className="text-muted-foreground">不关联任务，手动填写</span>
                  </SelectItem>
                  {availableTasks.filter(t => t.status !== '已完成').map(task => (
                    <SelectItem key={task.id} value={task.id}>
                      <div className="flex items-center gap-2">
                        <Badge variant="outline" className={
                          task.status === '进行中' ? 'bg-orange-500 text-white' : 
                          task.status === '未开始' ? 'bg-gray-500 text-white' : ''
                        }>
                          {task.status}
                        </Badge>
                        <span>{task.name}</span>
                        <span className="text-xs text-muted-foreground">
                          ({task.type} - {task.fieldName})
                        </span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {selectedTask && (
                <div className="mt-2 p-3 bg-white rounded border border-green-300">
                  <p className="text-xs text-green-800 font-medium mb-2">
                    ✓ 已关联任务：{selectedTask.name}
                  </p>
                  <div className="grid grid-cols-3 gap-2 text-xs text-green-700">
                    <div>任务类型：{selectedTask.type}</div>
                    <div>执行地块：{selectedTask.fieldName}</div>
                    <div>负责人：{selectedTask.assignedTo}</div>
                  </div>
                </div>
              )}
            </Card>

            {/* 基本信息 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <h4 className="mb-3">基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>农事类型 *</label>
                  <Select 
                    value={recordForm.operationType} 
                    onValueChange={(value: OperationType) => 
                      setRecordForm(prev => ({ ...prev, operationType: value }))
                    }
                    disabled={!!selectedTask}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue placeholder="选择农事类型" />
                    </SelectTrigger>
                    <SelectContent>
                      {operationTypes.map(type => (
                        <SelectItem key={type.id} value={type.name}>
                          {type.icon} {type.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {selectedTask && (
                    <p className="text-xs text-blue-600 mt-1">
                      ✓ 已从任务自动填充
                    </p>
                  )}
                </div>

                <div>
                  <label>执行地块 *</label>
                  <Select 
                    value={recordForm.fieldId} 
                    onValueChange={(value) => {
                      const field = mockFields.find(f => f.id === value);
                      setRecordForm(prev => ({
                        ...prev,
                        fieldId: value,
                        fieldName: field?.name || '',
                        fieldArea: field?.area || 0,
                      }));
                    }}
                    disabled={!!selectedTask}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue placeholder="选择地块" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockFields.map(field => (
                        <SelectItem key={field.id} value={field.id}>
                          {field.name} ({field.area}亩 - {field.crop})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {recordForm.fieldArea > 0 && (
                    <p className="text-xs text-green-600 mt-1">
                      ✓ 地块面积: {recordForm.fieldArea} 亩
                    </p>
                  )}
                </div>

                <div>
                  <label>执行人 *</label>
                  <Select 
                    value={recordForm.executor}
                    onValueChange={(value) => 
                      setRecordForm(prev => ({ ...prev, executor: value }))
                    }
                    disabled={!!selectedTask}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue placeholder="选择执行人" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="张三">张三</SelectItem>
                      <SelectItem value="李四">李四</SelectItem>
                      <SelectItem value="王五">王五</SelectItem>
                      <SelectItem value="赵六">赵六</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label>班组</label>
                  <Select 
                    value={recordForm.teamName}
                    onValueChange={(value) => 
                      setRecordForm(prev => ({ ...prev, teamName: value }))
                    }
                    disabled={!!selectedTask}
                  >
                    <SelectTrigger className="mt-2 bg-white">
                      <SelectValue placeholder="选择班组" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="第一作业组">第一作业组</SelectItem>
                      <SelectItem value="第二作业组">第二作业组</SelectItem>
                      <SelectItem value="第三作业组">第三作业组</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label>执行日期 *</label>
                  <Input 
                    type="date" 
                    className="mt-2 bg-white"
                    value={recordForm.executionDate}
                    onChange={(e) => 
                      setRecordForm(prev => ({ ...prev, executionDate: e.target.value }))
                    }
                  />
                </div>

                <div>
                  <label>作业时间</label>
                  <div className="flex gap-2 mt-2">
                    <Input 
                      type="time" 
                      placeholder="开始时间" 
                      className="bg-white"
                      value={recordForm.startTime}
                      onChange={(e) => 
                        setRecordForm(prev => ({ ...prev, startTime: e.target.value }))
                      }
                    />
                    <Input 
                      type="time" 
                      placeholder="结束时间" 
                      className="bg-white"
                      value={recordForm.endTime}
                      onChange={(e) => 
                        setRecordForm(prev => ({ ...prev, endTime: e.target.value }))
                      }
                    />
                  </div>
                </div>
              </div>
            </Card>

            {/* 操作参数（根据选择的农事类型动态显示） */}
            {selectedOperationType && (
              <Card className="p-4">
                <h4 className="mb-3">操作参数</h4>
                <div className="grid grid-cols-2 gap-4">
                  {selectedOperationType.parameters.map((param, index) => (
                    <div key={index}>
                      <label className="flex items-center gap-1">
                        {param.required && <span className="text-red-500">*</span>}
                        {param.name}
                      </label>
                      {param.type === 'text' && (
                        <Input 
                          placeholder={param.description || `请输入${param.name}`}
                          className="mt-2"
                        />
                      )}
                      {param.type === 'number' && (
                        <div className="flex gap-2 mt-2">
                          <Input 
                            type="number" 
                            placeholder={param.description || `请输入${param.name}`}
                          />
                          {param.unit && (
                            <span className="flex items-center px-3 bg-gray-100 rounded text-sm">
                              {param.unit}
                            </span>
                          )}
                        </div>
                      )}
                      {param.type === 'select' && (
                        <Select>
                          <SelectTrigger className="mt-2">
                            <SelectValue placeholder={param.description || `请选择${param.name}`} />
                          </SelectTrigger>
                          <SelectContent>
                            {param.options?.map((option, i) => (
                              <SelectItem key={i} value={option}>
                                {option}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                      {param.type === 'date' && (
                        <Input type="date" className="mt-2" />
                      )}
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {/* 现场图片上传 */}
            <Card className="p-4">
              <h4 className="mb-3 flex items-center gap-2">
                <Camera className="w-5 h-5 text-green-600" />
                现场图片
              </h4>
              <div className="space-y-3">
                {/* 上传按钮 */}
                <div>
                  <label htmlFor="photo-upload">
                    <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-green-500 hover:bg-green-50 transition-colors">
                      <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                      <p className="text-sm text-muted-foreground">
                        点击上传图片或拖拽图片到此处
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        支持 JPG、PNG 格式，最多上传10张
                      </p>
                    </div>
                  </label>
                  <input
                    id="photo-upload"
                    type="file"
                    accept="image/*"
                    multiple
                    className="hidden"
                    onChange={handlePhotoUpload}
                  />
                </div>

                {/* 已上传图片预览 */}
                {uploadedPhotos.length > 0 && (
                  <div className="grid grid-cols-4 gap-3">
                    {uploadedPhotos.map((photo, index) => (
                      <div key={index} className="relative group">
                        <img
                          src={photo}
                          alt={`现场图片 ${index + 1}`}
                          className="w-full h-24 object-cover rounded-lg border border-gray-200"
                        />
                        <button
                          onClick={() => handlePhotoRemove(index)}
                          className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          <Trash2 className="w-3 h-3" />
                        </button>
                        <div className="absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-xs px-2 py-0.5 rounded">
                          图{index + 1}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </Card>

            {/* 农资使用记录 */}
            <Card className="p-4 bg-yellow-50 border-yellow-200">
              <div className="flex items-center justify-between mb-3">
                <h4 className="flex items-center gap-2">
                  <Package className="w-5 h-5 text-yellow-600" />
                  农资使用记录
                </h4>
                <Button 
                  size="sm" 
                  variant="outline"
                  onClick={handleAddActualMaterial}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加农资
                </Button>
              </div>

              {/* 计划农资（如果有关联任务） */}
              {selectedTask && selectedTask.materials.length > 0 && (
                <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded">
                  <p className="text-sm text-blue-900 font-medium mb-2">
                    计划农资清单（来自任务）
                  </p>
                  <div className="grid grid-cols-3 gap-2">
                    {selectedTask.materials.map((mat, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-white rounded text-sm">
                        <span className="text-blue-800">{mat.name}</span>
                        <span className="text-blue-600 font-medium">{mat.amount} {mat.unit}</span>
                      </div>
                    ))}
                  </div>
                  <p className="text-xs text-blue-700 mt-2">
                    💡 下方可记录实际使用的农资，包括品牌、批号等详细信息
                  </p>
                </div>
              )}

              {/* 实际使用农资 */}
              <div className="space-y-3">
                {actualMaterials.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    <Package className="w-12 h-12 mx-auto mb-2 opacity-30" />
                    <p className="text-sm">暂无农资记录</p>
                    <p className="text-xs mt-1">点击"添加农资"按钮记录实际使用的农资</p>
                  </div>
                ) : (
                  actualMaterials.map((material, index) => (
                    <Card key={index} className="p-3 bg-white border border-yellow-300">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm font-medium text-yellow-900">
                          农资 #{index + 1}
                        </span>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleRemoveActualMaterial(index)}
                        >
                          <Trash2 className="w-3 h-3" />
                        </Button>
                      </div>
                      <div className="grid grid-cols-5 gap-3">
                        <div>
                          <label className="text-xs">农资名称 *</label>
                          <Input
                            className="mt-1"
                            placeholder="如：水稻种子"
                            value={material.name}
                            onChange={(e) => handleUpdateActualMaterial(index, 'name', e.target.value)}
                          />
                        </div>
                        <div>
                          <label className="text-xs">品牌</label>
                          <Input
                            className="mt-1"
                            placeholder="如：隆平高科"
                            value={material.brand}
                            onChange={(e) => handleUpdateActualMaterial(index, 'brand', e.target.value)}
                          />
                        </div>
                        <div>
                          <label className="text-xs">实际用量 *</label>
                          <div className="flex gap-1 mt-1">
                            <Input
                              type="number"
                              className="flex-1"
                              placeholder="数量"
                              value={material.amount || ''}
                              onChange={(e) => handleUpdateActualMaterial(index, 'amount', parseFloat(e.target.value) || 0)}
                            />
                          </div>
                        </div>
                        <div>
                          <label className="text-xs">单位 *</label>
                          <Select 
                            value={material.unit}
                            onValueChange={(value) => handleUpdateActualMaterial(index, 'unit', value)}
                          >
                            <SelectTrigger className="mt-1">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="kg">kg</SelectItem>
                              <SelectItem value="L">L</SelectItem>
                              <SelectItem value="袋">袋</SelectItem>
                              <SelectItem value="瓶">瓶</SelectItem>
                              <SelectItem value="g">g</SelectItem>
                              <SelectItem value="ml">ml</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <label className="text-xs">批次号</label>
                          <Input
                            className="mt-1"
                            placeholder="如：LP20240301"
                            value={material.batchNo}
                            onChange={(e) => handleUpdateActualMaterial(index, 'batchNo', e.target.value)}
                          />
                        </div>
                      </div>
                    </Card>
                  ))
                )}
              </div>

              <p className="text-xs text-yellow-800 mt-3 flex items-center gap-1">
                <Package className="w-3 h-3" />
                详细记录实际使用的农资信息，用于成本核算和生产追溯
              </p>
            </Card>

            {/* 备注 */}
            <div>
              <label>备注</label>
              <Textarea 
                placeholder="记录操作过程中的注意事项、天气情况等" 
                className="mt-2" 
                rows={3}
                value={recordForm.notes}
                onChange={(e) => setRecordForm(prev => ({ ...prev, notes: e.target.value }))}
              />
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowRecordDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700">
                <Save className="w-4 h-4 mr-2" />
                {selectedRecord ? '保存修改' : '保存记录'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 验收评价对话框 */}
      <Dialog open={showAcceptanceDialog} onOpenChange={setShowAcceptanceDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>操作记录验收</DialogTitle>
            <DialogDescription>
              对操作记录进行验收，填写验收评价
            </DialogDescription>
          </DialogHeader>
          {selectedRecord && (
            <div className="space-y-4">
              {/* 同步提示 - 醒目的提示区域 */}
              <div className={`p-4 rounded-lg border-2 ${selectedRecord.relatedTaskId ? 'bg-gradient-to-r from-orange-50 to-amber-50 border-orange-300' : 'bg-gradient-to-r from-cyan-50 to-blue-50 border-cyan-200'}`}>
                <div className="flex items-start gap-3">
                  <div className={`p-2 rounded-lg ${selectedRecord.relatedTaskId ? 'bg-orange-100' : 'bg-cyan-100'}`}>
                    <FileText className={`w-5 h-5 ${selectedRecord.relatedTaskId ? 'text-orange-600' : 'text-cyan-600'}`} />
                  </div>
                  <div className="flex-1">
                    <h4 className={`mb-1 font-semibold ${selectedRecord.relatedTaskId ? 'text-orange-900' : 'text-cyan-900'}`}>
                      {selectedRecord.relatedTaskId ? '⚠️ 验收同步提醒' : '验收说明'}
                    </h4>
                    <p className={`text-sm ${selectedRecord.relatedTaskId ? 'text-orange-800' : 'text-cyan-800'}`}>
                      {selectedRecord.relatedTaskId 
                        ? `提交验收后，系统将自动同步至关联的农事任务「${selectedRecord.relatedTaskName || ''}」，并将该任务状态更新为"已完成"` 
                        : '该操作记录将被标记为已验收'}
                    </p>
                    {selectedRecord.relatedTaskId && (
                      <p className="text-xs text-orange-700 mt-1 flex items-center gap-1">
                        <span className="inline-block w-1.5 h-1.5 bg-orange-600 rounded-full"></span>
                        操作记录验收 → 关联任务同步验收并标记为已完成
                      </p>
                    )}
                  </div>
                </div>
              </div>

              {/* 记录信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <FileText className="w-4 h-4 text-blue-600" />
                  记录信息
                </h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">操作类型：</span>
                    <span className="font-medium">{selectedRecord.operationType}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行地块：</span>
                    <span className="font-medium">{selectedRecord.fieldName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行人员：</span>
                    <span className="font-medium">{selectedRecord.executor}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">执行日期：</span>
                    <span className="font-medium">{selectedRecord.executionDate}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">作业时间：</span>
                    <span className="font-medium">{selectedRecord.startTime} - {selectedRecord.endTime}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">地块面积：</span>
                    <span className="font-medium">{selectedRecord.fieldArea} 亩</span>
                  </div>
                </div>
              </Card>

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

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

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

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

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

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

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

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

              <div className="flex gap-2 justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowAcceptanceDialog(false)}>
                  取消
                </Button>
                <Button 
                  className="bg-green-600 hover:bg-green-700"
                  onClick={handleSubmitAcceptance}
                >
                  <Eye className="w-4 h-4 mr-2" />
                  提交验收{selectedRecord.relatedTaskId ? '并同步至关联任务' : ''}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
