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, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { cn } from '../ui/utils';
import {
  FileText,
  Plus,
  Search,
  Filter,
  Download,
  CheckCircle,
  XCircle,
  Clock,
  User,
  Package,
  Calendar,
  MapPin,
  Tag,
  Eye,
  Edit,
  Send,
  Upload,
  Paperclip,
  AlertCircle,
  TrendingUp,
  Activity,
  BarChart3,
  Scan,
  CheckSquare,
  History,
  FileCheck,
  ArrowRight,
  ShoppingCart,
  UserCheck,
  Warehouse,
  PieChart as PieChartIcon,
  RefreshCw,
  Save,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AssetRequisitionProps {
  activePath?: string;
}

type RequisitionStatus = '草稿' | '待审批' | '已通过' | '已驳回' | '已出库' | '已核销';
type ApprovalAction = '同意' | '驳回' | '修改';
type Priority = '高' | '中' | '低';

interface RequisitionItem {
  id: string;
  materialId: string;
  materialName: string;
  materialType: string;
  materialCategory?: string; // 物品大类：农资/农具
  requestedQuantity: number;
  approvedQuantity?: number;
  actualQuantity?: number;
  unit: string;
  currentStock: number;
  estimatedPrice: number;
}

interface Requisition {
  id: string;
  code: string;
  applicant: string;
  applicantId: string;
  department: string;
  applyDate: string;
  purpose: string;
  relatedTask?: string;
  relatedField?: string;
  plannedUseDate: string;
  items: RequisitionItem[];
  totalAmount: number;
  status: RequisitionStatus;
  priority: Priority;
  approver?: string;
  approveDate?: string;
  approvalComments?: string;
  checkoutPerson?: string;
  checkoutDate?: string;
  attachments?: string[];
  notes?: string;
}

interface ApprovalRecord {
  id: string;
  requisitionCode: string;
  approver: string;
  action: ApprovalAction;
  comments: string;
  date: string;
  duration: string;
}

interface CheckoutRecord {
  id: string;
  requisitionCode: string;
  checkoutPerson: string;
  checkoutDate: string;
  items: {
    materialName: string;
    requestedQty: number;
    actualQty: number;
    batchNo: string;
  }[];
  scanMethod: '扫码' | '手动';
  notes?: string;
}

interface TraceabilityRecord {
  id: string;
  requisitionCode: string;
  materialName: string;
  materialType: string;
  batchNo: string;
  quantity: number;
  unit: string;
  applicant: string;
  approver: string;
  checkoutPerson: string;
  applyDate: string;
  approveDate: string;
  checkoutDate: string;
  purpose: string;
  relatedField?: string;
  relatedTask?: string;
  supplier: string;
  productionDate: string;
  expiryDate: string;
  qualityCert: string;
}

export function AssetRequisition({ activePath }: AssetRequisitionProps) {
  const [activeTab, setActiveTab] = useState('apply');
  const [showApplyDialog, setShowApplyDialog] = useState(false);
  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [showCheckoutDialog, setShowCheckoutDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedRequisition, setSelectedRequisition] = useState<Requisition | null>(null);
  const [selectedItems, setSelectedItems] = useState<RequisitionItem[]>([]);
  const [isEditingDraft, setIsEditingDraft] = useState(false);
  const [editingRequisitionId, setEditingRequisitionId] = useState<string | null>(null);
  
  // 申请表单状态
  const [formData, setFormData] = useState({
    department: 'team1',
    relatedTask: '',
    relatedField: '',
    plannedUseDate: '',
    priority: 'medium' as Priority,
    purpose: '',
    notes: '',
  });
  
  // 附件管理
  const [attachments, setAttachments] = useState<File[]>([]);
  const [isDragging, setIsDragging] = useState(false);
  
  // 审批状态
  const [approvalFormData, setApprovalFormData] = useState({
    action: '' as ApprovalAction | '',
    comments: '',
    modifiedItems: [] as RequisitionItem[],
  });
  
  // 消息通知状态
  const [notificationChannels, setNotificationChannels] = useState({
    systemMessage: true,
    sms: false,
    email: false,
  });
  
  // 出库状态
  const [checkoutFormData, setCheckoutFormData] = useState({
    scanMode: 'manual' as 'scan' | 'manual', // 普通出库
    checkoutItems: [] as Array<{
      itemId: string;
      materialName: string;
      approvedQuantity: number;
      actualQuantity: number;
      batchNo: string;
      warehouseLocation: string;
      unit: string;
      scanned: boolean;
    }>,
    notes: '',
  });
  
  // 扫码输入
  const [scanInput, setScanInput] = useState('');
  
  // 溯源详情对话框
  const [showTraceDetailDialog, setShowTraceDetailDialog] = useState(false);
  const [selectedTraceRecord, setSelectedTraceRecord] = useState<any>(null);
  
  // 溯源搜索筛选
  const [traceSearchTerm, setTraceSearchTerm] = useState('');
  const [traceMaterialType, setTraceMaterialType] = useState('all');
  const [traceDateRange, setTraceDateRange] = useState({ start: '', end: '' });
  const [traceField, setTraceField] = useState('all');
  const [traceDepartment, setTraceDepartment] = useState('all');

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

  // 模拟数据
  const [requisitions, setRequisitions] = useState<Requisition[]>([
    {
      id: 'req-0',
      code: 'LY202410220001',
      applicant: '当前用户',
      applicantId: 'emp-000',
      department: '种植一队',
      applyDate: '2024-10-22 10:15',
      purpose: '待完善用途说明',
      relatedTask: '',
      relatedField: '',
      plannedUseDate: '2024-10-25',
      items: [
        {
          id: 'item-0',
          materialId: 'mat-1',
          materialName: '复合肥',
          materialType: '肥料',
          requestedQuantity: 50,
          unit: '袋',
          currentStock: 500,
          estimatedPrice: 150,
        },
      ],
      totalAmount: 7500,
      status: '草稿',
      priority: '中',
    },
    {
      id: 'req-1',
      code: 'LY202410150001',
      applicant: '张三',
      applicantId: 'emp-001',
      department: '种植一队',
      applyDate: '2024-10-15 09:30',
      purpose: '水稻田施肥作业',
      relatedTask: '任务-2024001',
      relatedField: '1号田块',
      plannedUseDate: '2024-10-18',
      items: [
        {
          id: 'item-1',
          materialId: 'mat-1',
          materialName: '复合肥',
          materialType: '肥料',
          requestedQuantity: 100,
          approvedQuantity: 100,
          unit: '袋',
          currentStock: 500,
          estimatedPrice: 150,
        },
        {
          id: 'item-2',
          materialId: 'mat-2',
          materialName: '尿素',
          materialType: '肥料',
          requestedQuantity: 50,
          approvedQuantity: 50,
          unit: '袋',
          currentStock: 200,
          estimatedPrice: 100,
        },
      ],
      totalAmount: 20000,
      status: '已通过',
      priority: '高',
      approver: '李队长',
      approveDate: '2024-10-15 14:20',
      approvalComments: '同意领用',
      attachments: ['施肥方案.pdf'],
    },
    {
      id: 'req-2',
      code: 'LY202410150002',
      applicant: '王五',
      applicantId: 'emp-002',
      department: '种植二队',
      applyDate: '2024-10-15 10:45',
      purpose: '玉米田除草作业',
      relatedTask: '任务-2024002',
      relatedField: '2号田块',
      plannedUseDate: '2024-10-20',
      items: [
        {
          id: 'item-3',
          materialId: 'mat-3',
          materialName: '除草剂',
          materialType: '农药',
          requestedQuantity: 20,
          unit: '瓶',
          currentStock: 80,
          estimatedPrice: 50,
        },
      ],
      totalAmount: 1000,
      status: '待审批',
      priority: '中',
      attachments: ['除草方案.pdf', '现场照片.jpg'],
    },
    {
      id: 'req-3',
      code: 'LY202410140003',
      applicant: '赵六',
      applicantId: 'emp-003',
      department: '种植三队',
      applyDate: '2024-10-14 15:20',
      purpose: '蔬菜大棚灌溉',
      relatedField: '3号大棚',
      plannedUseDate: '2024-10-16',
      items: [
        {
          id: 'item-4',
          materialId: 'mat-4',
          materialName: '滴灌管',
          materialType: '农具',
          requestedQuantity: 200,
          approvedQuantity: 200,
          actualQuantity: 200,
          unit: '米',
          currentStock: 1000,
          estimatedPrice: 5,
        },
      ],
      totalAmount: 1000,
      status: '已出库',
      priority: '高',
      approver: '刘管理员',
      approveDate: '2024-10-14 16:30',
      approvalComments: '同意',
      checkoutPerson: '仓库-张',
      checkoutDate: '2024-10-15 08:00',
    },
  ]);

  const [approvalRecords] = useState<ApprovalRecord[]>([
    {
      id: 'appr-1',
      requisitionCode: 'LY202410150001',
      approver: '李队长',
      action: '同意',
      comments: '用量合理，同意领用',
      date: '2024-10-15 14:20',
      duration: '4小时50分',
    },
    {
      id: 'appr-2',
      requisitionCode: 'LY202410140003',
      approver: '刘管理员',
      action: '同意',
      comments: '库存充足，批准',
      date: '2024-10-14 16:30',
      duration: '1小时10分',
    },
  ]);

  const [checkoutRecords] = useState<CheckoutRecord[]>([
    {
      id: 'check-1',
      requisitionCode: 'LY202410140003',
      checkoutPerson: '仓库-张',
      checkoutDate: '2024-10-15 08:00',
      items: [
        {
          materialName: '滴灌管',
          requestedQty: 200,
          actualQty: 200,
          batchNo: 'BATCH-20241001-001',
        },
      ],
      scanMethod: '扫码',
    },
    {
      id: 'check-2',
      requisitionCode: 'LY202410150001',
      checkoutPerson: '仓库-李',
      checkoutDate: '2024-10-15 15:30',
      items: [
        {
          materialName: '复合肥',
          requestedQty: 100,
          actualQty: 100,
          batchNo: 'BATCH-20241005-002',
        },
        {
          materialName: '尿素',
          requestedQty: 50,
          actualQty: 50,
          batchNo: 'BATCH-20241008-003',
        },
      ],
      scanMethod: '扫码',
    },
  ]);

  const [traceRecords] = useState<TraceabilityRecord[]>([
    {
      id: 'trace-1',
      requisitionCode: 'LY202410150001',
      materialName: '复合肥',
      materialType: '肥料',
      batchNo: 'BATCH-20241005-002',
      quantity: 100,
      unit: '袋',
      applicant: '张三',
      approver: '李队长',
      checkoutPerson: '仓库-李',
      applyDate: '2024-10-15 09:30',
      approveDate: '2024-10-15 14:20',
      checkoutDate: '2024-10-15 15:30',
      purpose: '水稻田施肥作业',
      relatedField: '1号田块',
      relatedTask: '任务-2024001',
      supplier: '绿源农资公司',
      productionDate: '2024-09-15',
      expiryDate: '2025-09-15',
      qualityCert: 'CERT-2024-09-15-001',
    },
    {
      id: 'trace-2',
      requisitionCode: 'LY202410140003',
      materialName: '滴灌管',
      materialType: '农具',
      batchNo: 'BATCH-20241001-001',
      quantity: 200,
      unit: '米',
      applicant: '赵六',
      approver: '刘管理员',
      checkoutPerson: '仓库-张',
      applyDate: '2024-10-14 15:20',
      approveDate: '2024-10-14 16:30',
      checkoutDate: '2024-10-15 08:00',
      purpose: '蔬菜大棚灌溉',
      relatedField: '3号大棚',
      supplier: '农田设备厂',
      productionDate: '2024-08-20',
      expiryDate: '2029-08-20',
      qualityCert: 'CERT-2024-08-20-002',
    },
  ]);

  // 统计数据
  const totalRequisitions = requisitions.length;
  const pendingApproval = requisitions.filter(r => r.status === '待审批').length;
  const approved = requisitions.filter(r => r.status === '已通过').length;
  const checkedOut = requisitions.filter(r => r.status === '已出库').length;

  // 图表数据
  const statusChartData = [
    { name: '草稿', value: requisitions.filter(r => r.status === '草稿').length },
    { name: '待审批', value: pendingApproval },
    { name: '已通过', value: approved },
    { name: '已驳回', value: requisitions.filter(r => r.status === '已驳回').length },
    { name: '已出库', value: checkedOut },
  ];

  const trendChartData = [
    { month: '6月', count: 45 },
    { month: '7月', count: 52 },
    { month: '8月', count: 48 },
    { month: '9月', count: 60 },
    { month: '10月', count: 55 },
  ];

  const COLORS = ['#f59e0b', '#3b82f6', '#10b981', '#ef4444', '#8b5cf6'];

  const getStatusColor = (status: RequisitionStatus) => {
    switch (status) {
      case '草稿': return 'bg-gray-100 text-gray-700';
      case '待审批': return 'bg-yellow-100 text-yellow-700';
      case '已通过': return 'bg-green-100 text-green-700';
      case '已驳回': return 'bg-red-100 text-red-700';
      case '已出库': return 'bg-blue-100 text-blue-700';
      case '已核销': return 'bg-purple-100 text-purple-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getPriorityColor = (priority: Priority) => {
    switch (priority) {
      case '高': return 'bg-red-100 text-red-700';
      case '中': return 'bg-yellow-100 text-yellow-700';
      case '低': return 'bg-blue-100 text-blue-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  // 自动触发审批流程
  const triggerApprovalWorkflow = (totalAmount: number, items: RequisitionItem[]) => {
    // 根据金额和物资类型确定审批人
    let approvers: string[] = [];
    let approvalLevel = 1;
    
    // 审批规则1：根据金额
    if (totalAmount >= 50000) {
      approvalLevel = 3;
      approvers = ['总经理', '财务主管', '生产队长'];
    } else if (totalAmount >= 10000) {
      approvalLevel = 2;
      approvers = ['财务主管', '生产队长'];
    } else {
      approvalLevel = 1;
      approvers = ['生产队长'];
    }
    
    // 审批规则2：特殊物资需要额外审批
    const hasSpecialMaterial = items.some(item => 
      item.materialType === '农药' || item.materialType === '化肥'
    );
    
    if (hasSpecialMaterial && !approvers.includes('仓库管理员')) {
      approvers.push('仓库管理员');
    }
    
    // 审批规则3：紧急申请需要加快流程
    if (formData.priority === '高') {
      // 发送紧急通知
      sendNotification(approvers, '紧急审批', true);
    } else {
      sendNotification(approvers, '待审批', false);
    }
    
    return { approvers, approvalLevel };
  };
  
  // 发送通知
  const sendNotification = (approvers: string[], type: string, isUrgent: boolean) => {
    const channels: string[] = [];
    
    if (notificationChannels.systemMessage) channels.push('系统消息');
    if (notificationChannels.sms) channels.push('短信');
    if (notificationChannels.email) channels.push('邮件');
    if (notificationChannels.wechat) channels.push('微信');
    
    console.log('发送通知:', {
      approvers,
      type,
      isUrgent,
      channels,
      message: isUrgent ? '您有一个紧急审批待处理' : '您有新的审批申请'
    });
    
    // 实际项目中这里会调用后端API发送通知
  };
  
  // 保存草稿
  const handleSaveDraft = () => {
    // 草稿验证相对宽松，只需要有物品即可
    if (selectedItems.length === 0) {
      toast.error('请至少添加一项物品');
      return;
    }
    
    // 计算总金额
    const totalAmount = selectedItems.reduce((sum, item) => 
      sum + (item.requestedQuantity * item.estimatedPrice), 0
    );
    
    if (isEditingDraft && editingRequisitionId) {
      // 更新现有草稿
      setRequisitions(prev => 
        prev.map(req => 
          req.id === editingRequisitionId 
            ? {
                ...req,
                department: formData.department === 'team1' ? '种植一队' : '种植二队',
                relatedTask: formData.relatedTask,
                relatedField: formData.relatedField,
                plannedUseDate: formData.plannedUseDate,
                priority: formData.priority === 'high' ? '高' : formData.priority === 'medium' ? '中' : '低',
                purpose: formData.purpose,
                notes: formData.notes,
                items: selectedItems,
                totalAmount: totalAmount,
              }
            : req
        )
      );
      
      const requisition = requisitions.find(r => r.id === editingRequisitionId);
      toast.success('草稿已更新', {
        description: `申请单 ${requisition?.code} | 物品${selectedItems.length}项 | 附件${attachments.length}个`
      });
    } else {
      // 创建新草稿
      toast.success('领用申请已保存为草稿', {
        description: `物品${selectedItems.length}项 | 附件${attachments.length}个 | 可稍后继续编辑`
      });
    }
    
    // 重置表单
    setFormData({
      department: 'team1',
      relatedTask: '',
      relatedField: '',
      plannedUseDate: '',
      priority: 'medium',
      purpose: '',
      notes: '',
    });
    setSelectedItems([]);
    setAttachments([]);
    setIsEditingDraft(false);
    setEditingRequisitionId(null);
    setShowApplyDialog(false);
  };
  
  // 提交审批
  const handleSubmitRequisition = () => {
    // 验证表单
    if (!formData.purpose.trim()) {
      toast.error('请填写领用用途');
      return;
    }
    
    if (!formData.plannedUseDate) {
      toast.error('请选择计划领用时间');
      return;
    }
    
    if (selectedItems.length === 0) {
      toast.error('请至少添加一项物品');
      return;
    }
    
    // 验证每个物品是否填写完整
    const hasInvalidItem = selectedItems.some(
      item => !item.materialId || !item.materialName || item.requestedQuantity <= 0
    );
    
    if (hasInvalidItem) {
      toast.error('请完整填写所有物品信息');
      return;
    }
    
    // 检查库存
    const hasInsufficientStock = selectedItems.some(
      item => item.requestedQuantity > item.currentStock
    );
    
    if (hasInsufficientStock) {
      toast.error('部分物品申请数量超过当前库存');
      return;
    }
    
    // 计算总金额
    const totalAmount = selectedItems.reduce((sum, item) => 
      sum + (item.requestedQuantity * item.estimatedPrice), 0
    );
    
    // 自动触发审批流程
    const { approvers, approvalLevel } = triggerApprovalWorkflow(totalAmount, selectedItems);
    
    if (isEditingDraft && editingRequisitionId) {
      // 更新现有草稿并提交审批
      setRequisitions(prev => 
        prev.map(req => 
          req.id === editingRequisitionId 
            ? {
                ...req,
                department: formData.department === 'team1' ? '种植一队' : '种植二队',
                relatedTask: formData.relatedTask,
                relatedField: formData.relatedField,
                plannedUseDate: formData.plannedUseDate,
                priority: formData.priority === 'high' ? '高' : formData.priority === 'medium' ? '中' : '低',
                purpose: formData.purpose,
                notes: formData.notes,
                items: selectedItems,
                totalAmount: totalAmount,
                status: '待审批' as RequisitionStatus,
              }
            : req
        )
      );
      
      const requisition = requisitions.find(r => r.id === editingRequisitionId);
      toast.success('草稿已更新并提交，已自动触发审批流程', {
        description: `申请单 ${requisition?.code} | 审批等级：${approvalLevel}级 | 审批人：${approvers.join('、')}`
      });
    } else {
      // 创建新申请
      toast.success('领用申请已提交，已自动触发审批流程', {
        description: `审批等级：${approvalLevel}级 | 审批人：${approvers.join('、')} | 物品${selectedItems.length}项 | 附件${attachments.length}个`
      });
    }
    
    // 重置表单
    setFormData({
      department: 'team1',
      relatedTask: '',
      relatedField: '',
      plannedUseDate: '',
      priority: 'medium',
      purpose: '',
      notes: '',
    });
    setSelectedItems([]);
    setAttachments([]);
    setIsEditingDraft(false);
    setEditingRequisitionId(null);
    setShowApplyDialog(false);
  };
  
  // 编辑草稿
  const handleEditDraft = (requisition: Requisition) => {
    // 填充表单数据
    setFormData({
      department: requisition.department === '种植一队' ? 'team1' : 'team2',
      relatedTask: requisition.relatedTask || '',
      relatedField: requisition.relatedField || '',
      plannedUseDate: requisition.plannedUseDate,
      priority: requisition.priority === '高' ? 'high' : requisition.priority === '中' ? 'medium' : 'low',
      purpose: requisition.purpose,
      notes: requisition.notes || '',
    });
    
    // 填充物品清单
    setSelectedItems(requisition.items);
    
    // 标记为编辑模式
    setIsEditingDraft(true);
    setEditingRequisitionId(requisition.id);
    
    // 打开对话框
    setShowApplyDialog(true);
    
    toast.info('正在编辑草稿', {
      description: `申请单号: ${requisition.code}`
    });
  };
  
  // 撤回申请（将待审批状态改为草稿）
  const handleWithdrawRequisition = (requisitionId: string) => {
    setRequisitions(prev => 
      prev.map(req => 
        req.id === requisitionId 
          ? { ...req, status: '草稿' as RequisitionStatus }
          : req
      )
    );
    
    const requisition = requisitions.find(r => r.id === requisitionId);
    toast.success('申请已撤回，状态已变更为草稿', {
      description: `申请单 ${requisition?.code} 可以重新编辑后再次提交审批`
    });
  };
  
  // 从草稿提交审批
  const handleSubmitFromDraft = (requisitionId: string) => {
    const requisition = requisitions.find(r => r.id === requisitionId);
    
    if (!requisition) {
      toast.error('未找到申请单');
      return;
    }
    
    // 验证草稿数据
    if (!requisition.purpose.trim()) {
      toast.error('请先编辑草稿并填写领用用途');
      return;
    }
    
    if (requisition.items.length === 0) {
      toast.error('请先编辑草稿并添加物品');
      return;
    }
    
    // 更新状态为待审批
    setRequisitions(prev => 
      prev.map(req => 
        req.id === requisitionId 
          ? { ...req, status: '待审批' as RequisitionStatus }
          : req
      )
    );
    
    // 触发审批流程
    const { approvers, approvalLevel } = triggerApprovalWorkflow(requisition.totalAmount, requisition.items);
    
    toast.success('草稿已提交审批，已自动触发审批流程', {
      description: `申请单 ${requisition.code} | 审批等级：${approvalLevel}级 | 审批人：${approvers.join('、')}`
    });
  };

  const handleApprove = (action: ApprovalAction) => {
    if (!approvalFormData.comments.trim()) {
      toast.error('请填写审批意见');
      return;
    }
    
    const actionText = action === '同意' ? '通过' : action === '驳回' ? '驳回' : '修改';
    
    // 记录审批操作
    const approvalRecord = {
      requisitionCode: selectedRequisition?.code,
      approver: '当前审批人',
      action,
      comments: approvalFormData.comments,
      date: new Date().toLocaleString('zh-CN'),
      duration: '15分钟',
      modifiedItems: action === '修改' ? approvalFormData.modifiedItems : undefined,
    };
    
    console.log('审批记录:', approvalRecord);
    
    // 发送通知给申请人
    const notificationMsg = action === '同意' 
      ? '您的领用申请已通过审批，请等待出库'
      : action === '驳回'
      ? '您的领用申请已被驳回，请查看驳回原因'
      : '您的领用申请需要修改，请查看修改意见';
    
    console.log('发送通知给申请人:', {
      applicant: selectedRequisition?.applicant,
      message: notificationMsg,
      details: approvalFormData.comments
    });
    
    toast.success(`已${actionText}该申请`, {
      description: `审批意见已记录，已通知申请人`
    });
    
    // 重置审批表单
    setApprovalFormData({
      action: '',
      comments: '',
      modifiedItems: [],
    });
    
    setShowApprovalDialog(false);
  };
  
  // 初始化出库清单
  const initializeCheckoutItems = (requisition: Requisition) => {
    const checkoutItems = requisition.items.map(item => ({
      itemId: item.id,
      materialName: item.materialName,
      approvedQuantity: item.approvedQuantity || item.requestedQuantity,
      actualQuantity: item.approvedQuantity || item.requestedQuantity,
      batchNo: '',
      warehouseLocation: '',
      unit: item.unit,
      scanned: false,
    }));
    
    setCheckoutFormData({
      ...checkoutFormData,
      checkoutItems,
    });
  };
  
  // 扫码匹配物品
  const handleScanMatch = () => {
    if (!scanInput.trim()) {
      toast.error('请输入批次号');
      return;
    }
    
    // 模拟扫码匹配逻辑
    const batchNo = scanInput.trim();
    
    // 查找匹配的物品（这里使用模拟逻辑）
    const matchedIndex = checkoutFormData.checkoutItems.findIndex(item => !item.scanned);
    
    if (matchedIndex === -1) {
      toast.error('所有物品已扫码完成');
      setScanInput('');
      return;
    }
    
    // 模拟从系统中获取批次信息
    const warehouseLocation = `A区-${Math.floor(Math.random() * 10) + 1}号货架`;
    
    // 更新出库清单
    const updatedItems = [...checkoutFormData.checkoutItems];
    updatedItems[matchedIndex] = {
      ...updatedItems[matchedIndex],
      batchNo,
      warehouseLocation,
      scanned: true,
    };
    
    setCheckoutFormData({
      ...checkoutFormData,
      checkoutItems: updatedItems,
    });
    
    toast.success(`已匹配物品：${updatedItems[matchedIndex].materialName}`, {
      description: `批次号：${batchNo} | 库位：${warehouseLocation}`
    });
    
    setScanInput('');
  };
  
  // 更新出库数量
  const handleUpdateCheckoutQuantity = (itemId: string, quantity: number) => {
    const updatedItems = checkoutFormData.checkoutItems.map(item =>
      item.itemId === itemId ? { ...item, actualQuantity: quantity } : item
    );
    
    setCheckoutFormData({
      ...checkoutFormData,
      checkoutItems: updatedItems,
    });
  };
  
  // 手动输入批次号
  const handleManualBatchInput = (itemId: string, batchNo: string) => {
    const updatedItems = checkoutFormData.checkoutItems.map(item =>
      item.itemId === itemId ? { ...item, batchNo } : item
    );
    
    setCheckoutFormData({
      ...checkoutFormData,
      checkoutItems: updatedItems,
    });
  };
  
  // 确认出库
  const handleConfirmCheckout = () => {
    // 验证：所有物品必须填写仓库和批次号
    const hasEmptyBatch = checkoutFormData.checkoutItems.some(item => !item.batchNo || !item.batchNo.includes('-'));
    if (hasEmptyBatch) {
      toast.error('请为所有物品选择仓库并输入批次号');
      return;
    }
    
    // 验证：所有物品必须有实际出库数量
    const hasInvalidQuantity = checkoutFormData.checkoutItems.some(
      item => !item.actualQuantity || item.actualQuantity <= 0
    );
    if (hasInvalidQuantity) {
      toast.error('请填写所有物品的实际出库数量');
      return;
    }
    
    // 验证：实际出库数量不能超过批准数量
    const hasExceededQuantity = checkoutFormData.checkoutItems.some(
      item => item.actualQuantity > item.approvedQuantity
    );
    if (hasExceededQuantity) {
      toast.error('实际出库数量不能超过批准数量');
      return;
    }
    
    // 1. 自动核减库存
    const inventoryDeductions = checkoutFormData.checkoutItems.map(item => ({
      materialName: item.materialName,
      batchNo: item.batchNo,
      quantity: item.actualQuantity,
      unit: item.unit,
      beforeStock: 500, // 模拟数据
      afterStock: 500 - item.actualQuantity,
      warehouseLocation: item.warehouseLocation,
    }));
    
    console.log('库存核减记录:', inventoryDeductions);
    
    // 2. 记录出库信息
    const checkoutRecord = {
      requisitionCode: selectedRequisition?.code,
      applicant: selectedRequisition?.applicant,
      checkoutPerson: '当前仓库管理员',
      checkoutDate: new Date().toLocaleString('zh-CN'),
      scanMethod: '手动',
      items: checkoutFormData.checkoutItems,
      notes: checkoutFormData.notes,
      inventoryDeductions,
    };
    
    console.log('出库记录:', checkoutRecord);
    
    // 3. 反馈给申请人
    const applicantNotification = {
      recipient: selectedRequisition?.applicant,
      type: '出库完成通知',
      message: `您的领用申请（${selectedRequisition?.code}）已完成出库`,
      details: {
        items: checkoutFormData.checkoutItems.map(item => ({
          name: item.materialName,
          quantity: item.actualQuantity,
          unit: item.unit,
          batchNo: item.batchNo,
        })),
        checkoutTime: new Date().toLocaleString('zh-CN'),
      },
      channels: ['系统消息', '短信'],
    };
    
    console.log('通知申请人:', applicantNotification);
    
    // 4. 反馈给财务系统
    const financeNotification = {
      recipient: '财务系统',
      type: '物资出库财务数据',
      requisitionCode: selectedRequisition?.code,
      applicant: selectedRequisition?.applicant,
      department: selectedRequisition?.department,
      items: checkoutFormData.checkoutItems.map(item => ({
        materialName: item.materialName,
        quantity: item.actualQuantity,
        unit: item.unit,
        estimatedPrice: selectedRequisition?.items.find(i => i.id === item.itemId)?.estimatedPrice || 0,
        totalAmount: item.actualQuantity * (selectedRequisition?.items.find(i => i.id === item.itemId)?.estimatedPrice || 0),
        batchNo: item.batchNo,
      })),
      totalAmount: checkoutFormData.checkoutItems.reduce((sum, item) => {
        const price = selectedRequisition?.items.find(i => i.id === item.itemId)?.estimatedPrice || 0;
        return sum + (item.actualQuantity * price);
      }, 0),
      checkoutDate: new Date().toLocaleString('zh-CN'),
      purpose: selectedRequisition?.purpose,
      relatedField: selectedRequisition?.relatedField,
      relatedTask: selectedRequisition?.relatedTask,
    };
    
    console.log('同步财务系统:', financeNotification);
    
    // 成功提示
    toast.success('出库完成！', {
      description: `已出库${checkoutFormData.checkoutItems.length}项物品，库存已自动核减，已通知申请人和财务系统`
    });
    
    // 重置表单
    setCheckoutFormData({
      scanMode: 'scan',
      checkoutItems: [],
      notes: '',
    });
    setScanInput('');
    setShowCheckoutDialog(false);
  };

  const handleCheckout = () => {
    toast.success('出库成功，库存已自动核减');
    setShowCheckoutDialog(false);
  };
  
  // 查看溯源详情
  const handleViewTraceDetail = (record: any) => {
    setSelectedTraceRecord(record);
    setShowTraceDetailDialog(true);
  };
  
  // 导出溯源记录
  const handleExportTraceRecords = () => {
    // 构建导出数据
    const exportData = filteredTraceRecords.map(record => ({
      申请单号: record.requisitionCode,
      物资名称: record.materialName,
      物资类型: record.materialType,
      批次号: record.batchNo,
      数量: `${record.quantity}${record.unit}`,
      领用人: record.applicant,
      部门: record.department,
      审批人: record.approver,
      出库人: record.checkoutPerson,
      用途: record.purpose,
      关联地块: record.relatedField || '-',
      关联任务: record.relatedTask || '-',
      申请时间: record.applyDate,
      审批时间: record.approveDate,
      出库时间: record.checkoutDate,
      供应商: record.supplier,
      生产日期: record.productionDate,
      有效期至: record.expiryDate,
      质检证书: record.qualityCert,
    }));
    
    console.log('导出溯源记录:', exportData);
    
    toast.success('导出成功', {
      description: `已导出${exportData.length}条溯源记录`
    });
  };
  
  // 重置筛选条件
  const handleResetFilters = () => {
    setTraceSearchTerm('');
    setTraceMaterialType('all');
    setTraceDateRange({ start: '', end: '' });
    setTraceField('all');
    setTraceDepartment('all');
    
    toast.success('已重置筛选条件');
  };
  
  // 筛选后的溯源记录
  const filteredTraceRecords = traceRecords.filter(record => {
    // 搜索词筛选
    if (traceSearchTerm) {
      const searchLower = traceSearchTerm.toLowerCase();
      const matchSearch = 
        record.requisitionCode.toLowerCase().includes(searchLower) ||
        record.materialName.toLowerCase().includes(searchLower) ||
        record.batchNo.toLowerCase().includes(searchLower) ||
        record.applicant.toLowerCase().includes(searchLower);
      if (!matchSearch) return false;
    }
    
    // 物资类型筛选
    if (traceMaterialType !== 'all' && record.materialType !== traceMaterialType) {
      return false;
    }
    
    // 地块筛选
    if (traceField !== 'all' && record.relatedField !== traceField) {
      return false;
    }
    
    // 部门筛选
    if (traceDepartment !== 'all' && record.department !== traceDepartment) {
      return false;
    }
    
    // 日期范围筛选
    if (traceDateRange.start && record.checkoutDate < traceDateRange.start) {
      return false;
    }
    if (traceDateRange.end && record.checkoutDate > traceDateRange.end) {
      return false;
    }
    
    return true;
  });

  const handleAddItem = () => {
    const newItem: RequisitionItem = {
      id: `item-${Date.now()}`,
      materialId: '',
      materialName: '',
      materialType: '',
      materialCategory: '', // 先选择农资或农具
      requestedQuantity: 0,
      unit: '',
      currentStock: 0,
      estimatedPrice: 0,
    };
    setSelectedItems([...selectedItems, newItem]);
  };

  const handleRemoveItem = (itemId: string) => {
    setSelectedItems(selectedItems.filter(item => item.id !== itemId));
  };
  
  const handleUpdateItem = (itemId: string, field: string, value: any) => {
    setSelectedItems(selectedItems.map(item => {
      if (item.id === itemId) {
        // 如果选择了物品类别，清空已选的物品
        if (field === 'materialCategory') {
          return {
            ...item,
            materialCategory: value,
            materialId: '',
            materialName: '',
            materialType: '',
            currentStock: 0,
            estimatedPrice: 0,
            unit: '',
          };
        }
        
        // 如果选择了新的物资，更新相关信息
        if (field === 'materialId') {
          const materials = [
            { id: 'mat1', name: '复合肥', type: '肥料', category: '农资', stock: 500, price: 150, unit: '袋' },
            { id: 'mat2', name: '尿素', type: '肥料', category: '农资', stock: 200, price: 100, unit: '袋' },
            { id: 'mat3', name: '除草剂', type: '农药', category: '农资', stock: 80, price: 50, unit: '瓶' },
            { id: 'mat4', name: '滴灌管', type: '农具', category: '农具', stock: 1000, price: 5, unit: '米' },
            { id: 'mat5', name: '杀虫剂', type: '农药', category: '农资', stock: 120, price: 80, unit: '瓶' },
            { id: 'mat6', name: '地膜', type: '农具', category: '农具', stock: 300, price: 20, unit: '卷' },
            { id: 'mat7', name: '喷雾器', type: '农具', category: '农具', stock: 50, price: 300, unit: '台' },
            { id: 'mat8', name: '钾肥', type: '肥料', category: '农资', stock: 150, price: 120, unit: '袋' },
          ];
          const material = materials.find(m => m.id === value);
          if (material) {
            return {
              ...item,
              materialId: value,
              materialName: material.name,
              materialType: material.type,
              currentStock: material.stock,
              estimatedPrice: material.price,
              unit: material.unit,
            };
          }
        }
        return { ...item, [field]: value };
      }
      return item;
    }));
  };
  
  // 附件处理函数
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      handleFiles(Array.from(files));
    }
  };
  
  const handleFiles = (files: File[]) => {
    const validFiles = files.filter(file => {
      // 限制文件大小为10MB
      if (file.size > 10 * 1024 * 1024) {
        toast.error(`文件 ${file.name} 超过10MB限制`);
        return false;
      }
      
      // 允许的文件类型
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'text/plain',
      ];
      
      if (!allowedTypes.includes(file.type)) {
        toast.error(`文件 ${file.name} 格式不支持`);
        return false;
      }
      
      return true;
    });
    
    setAttachments([...attachments, ...validFiles]);
    
    if (validFiles.length > 0) {
      toast.success(`成功添加 ${validFiles.length} 个文件`);
    }
  };
  
  const handleRemoveAttachment = (index: number) => {
    setAttachments(attachments.filter((_, i) => i !== index));
    toast.success('已移除附件');
  };
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };
  
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = Array.from(e.dataTransfer.files);
    handleFiles(files);
  };
  
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>物资领用管理</h2>
          <p className="text-sm text-muted-foreground mt-1">
            完整的物资领用申请、审批、出库与溯源流程管理
          </p>
        </div>
        <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
          setSelectedItems([]);
          setIsEditingDraft(false);
          setEditingRequisitionId(null);
          setFormData({
            department: 'team1',
            relatedTask: '',
            relatedField: '',
            plannedUseDate: '',
            priority: 'medium',
            purpose: '',
            notes: '',
          });
          setShowApplyDialog(true);
        }}>
          <Plus className="w-4 h-4 mr-2" />
          新建领用申请
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md: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">{totalRequisitions}</p>
              <p className="text-xs text-green-600 mt-1">本月新增 12 项</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-yellow-600">{pendingApproval}</p>
              <p className="text-xs text-orange-600 mt-1">需及时处理</p>
            </div>
            <Clock className="w-12 h-12 text-yellow-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">{approved}</p>
              <p className="text-xs text-blue-600 mt-1">待出库处理</p>
            </div>
            <CheckCircle 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">{checkedOut}</p>
              <p className="text-xs text-green-600 mt-1">完成率 92%</p>
            </div>
            <Package className="w-12 h-12 text-purple-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="apply">领用申请</TabsTrigger>
          <TabsTrigger value="approval">领用审批</TabsTrigger>
          <TabsTrigger value="checkout">出库与核销</TabsTrigger>
          <TabsTrigger value="record">领用记录与溯源</TabsTrigger>
        </TabsList>

        {/* 领用申请 */}
        <TabsContent value="apply" className="space-y-4">
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <ShoppingCart className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">领用申请功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>在线填写</strong>: APP或Web端填写电子申请单</li>
                  <li>• <strong>关联作业</strong>: 选择物品、预估数量、关联任务或地块</li>
                  <li>• <strong>计划时间</strong>: 设置计划领用时间</li>
                  <li>• <strong>附件上传</strong>: 支持上传说明文件、图片等</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 搜索和筛选 */}
          <Card className="p-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <Input placeholder="搜索申请单号、申请人..." prefix={<Search className="w-4 h-4" />} />
              </div>
              <Select defaultValue="all">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="状态筛选" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="pending">待提交</SelectItem>
                  <SelectItem value="submitted">已提交</SelectItem>
                  <SelectItem value="approved">已通过</SelectItem>
                  <SelectItem value="rejected">已驳回</SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline">
                <Filter className="w-4 h-4 mr-2" />
                高级筛选
              </Button>
            </div>
          </Card>

          {/* 申请列表 */}
          <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>
                {requisitions.map((req) => (
                  <TableRow key={req.id}>
                    <TableCell className="font-medium">{req.code}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-muted-foreground" />
                        {req.applicant}
                      </div>
                    </TableCell>
                    <TableCell>{req.department}</TableCell>
                    <TableCell>{req.applyDate}</TableCell>
                    <TableCell className="max-w-xs truncate">{req.purpose}</TableCell>
                    <TableCell>{req.items.length} 项</TableCell>
                    <TableCell>¥{req.totalAmount.toLocaleString()}</TableCell>
                    <TableCell>
                      <Badge className={getPriorityColor(req.priority)}>{req.priority}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(req.status)}>{req.status}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setSelectedRequisition(req);
                            setShowDetailDialog(true);
                          }}
                        >
                          <Eye className="w-3 h-3" />
                        </Button>
                        {req.status === '草稿' && (
                          <>
                            <Button 
                              size="sm" 
                              variant="outline"
                              className="border-blue-500 text-blue-600 hover:bg-blue-50"
                              onClick={() => handleEditDraft(req)}
                            >
                              <Edit className="w-3 h-3" />
                            </Button>
                            <Button 
                              size="sm" 
                              className="bg-green-600 hover:bg-green-700 text-white"
                              onClick={() => handleSubmitFromDraft(req.id)}
                            >
                              <Send className="w-3 h-3 mr-1" />
                              提交审批
                            </Button>
                          </>
                        )}
                        {req.status === '待审批' && (
                          <Button 
                            size="sm" 
                            variant="outline"
                            className="border-orange-500 text-orange-600 hover:bg-orange-50"
                            onClick={() => handleWithdrawRequisition(req.id)}
                          >
                            <RefreshCw className="w-3 h-3 mr-1" />
                            撤回
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 领用审批 */}
        <TabsContent value="approval" className="space-y-4">
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <UserCheck className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">领用审批功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动流程</strong>: 根据物资价值或类型自动触发审批流程</li>
                  <li>• <strong>消息通知</strong>: 通过系统消息、短信通知审批人</li>
                  <li>• <strong>在线审批</strong>: 可在线查看详情并同意、驳回或修改</li>
                  <li>• <strong>全程留痕</strong>: 审批过程完整记录，可追溯</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 待审批列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Clock className="w-5 h-5 text-yellow-600" />
                待我审批 ({pendingApproval})
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>申请单号</TableHead>
                  <TableHead>申请人</TableHead>
                  <TableHead>部门</TableHead>
                  <TableHead>申请时间</TableHead>
                  <TableHead>用途</TableHead>
                  <TableHead>物品清单</TableHead>
                  <TableHead>预估金额</TableHead>
                  <TableHead>优先级</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {requisitions.filter(r => r.status === '待审批').map((req) => (
                  <TableRow key={req.id}>
                    <TableCell className="font-medium">{req.code}</TableCell>
                    <TableCell>{req.applicant}</TableCell>
                    <TableCell>{req.department}</TableCell>
                    <TableCell>{req.applyDate}</TableCell>
                    <TableCell className="max-w-xs truncate">{req.purpose}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {req.items.map(item => (
                          <div key={item.id} className="text-xs">
                            {item.materialName} × {item.requestedQuantity}{item.unit}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>¥{req.totalAmount.toLocaleString()}</TableCell>
                    <TableCell>
                      <Badge className={getPriorityColor(req.priority)}>{req.priority}</Badge>
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        className="bg-blue-600 hover:bg-blue-700"
                        onClick={() => {
                          setSelectedRequisition(req);
                          setShowApprovalDialog(true);
                        }}
                      >
                        <Send className="w-3 h-3 mr-1" />
                        审批
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 审批历史 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <History className="w-5 h-5 text-gray-600" />
                审批历史
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>申请单号</TableHead>
                  <TableHead>审批人</TableHead>
                  <TableHead>审批结果</TableHead>
                  <TableHead>审批意见</TableHead>
                  <TableHead>审批时间</TableHead>
                  <TableHead>处理时长</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {approvalRecords.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.requisitionCode}</TableCell>
                    <TableCell>{record.approver}</TableCell>
                    <TableCell>
                      <Badge className={record.action === '同意' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}>
                        {record.action}
                      </Badge>
                    </TableCell>
                    <TableCell>{record.comments}</TableCell>
                    <TableCell>{record.date}</TableCell>
                    <TableCell>{record.duration}</TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          // 根据申请单号查找对应的申请记录
                          const req = requisitions.find(r => r.code === record.requisitionCode);
                          if (req) {
                            setSelectedRequisition(req);
                            setShowDetailDialog(true);
                          }
                        }}
                      >
                        <Eye className="w-3 h-3 mr-1" />
                        查看
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 出库与核销 */}
        <TabsContent value="checkout" className="space-y-4">
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Warehouse className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">出库与核销功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>凭单作业</strong>: 审批通过后仓库管理员凭单出库</li>
                  <li>• <strong>手动录入</strong>: 填写批次号和出库数量完成出库登记</li>
                  <li>• <strong>自动核减</strong>: 确认出库后系统自动核减库存</li>
                  <li>• <strong>信息反馈</strong>: 出库信息自动反馈给申请人和财务系统</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 待出库列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Package className="w-5 h-5 text-blue-600" />
                待出库申请 ({approved})
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>申请单号</TableHead>
                  <TableHead>申请人</TableHead>
                  <TableHead>审批人</TableHead>
                  <TableHead>审批时间</TableHead>
                  <TableHead>物品清单</TableHead>
                  <TableHead>计划领用时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {requisitions.filter(r => r.status === '已通过').map((req) => (
                  <TableRow key={req.id}>
                    <TableCell className="font-medium">{req.code}</TableCell>
                    <TableCell>{req.applicant}</TableCell>
                    <TableCell>{req.approver}</TableCell>
                    <TableCell>{req.approveDate}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {req.items.map(item => (
                          <div key={item.id} className="text-xs">
                            {item.materialName} × {item.approvedQuantity || item.requestedQuantity}{item.unit}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>{req.plannedUseDate}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          className="bg-green-600 hover:bg-green-700"
                          onClick={() => {
                            setSelectedRequisition(req);
                            initializeCheckoutItems(req);
                            setShowCheckoutDialog(true);
                          }}
                        >
                          <Package className="w-3 h-3 mr-1" />
                          出库
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 出库记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <FileCheck className="w-5 h-5 text-green-600" />
                出库记录
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>申请单号</TableHead>
                  <TableHead>出库人</TableHead>
                  <TableHead>出库时间</TableHead>
                  <TableHead>出库物品</TableHead>
                  <TableHead>出库方式</TableHead>
                  <TableHead>备注</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {checkoutRecords.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.requisitionCode}</TableCell>
                    <TableCell>{record.checkoutPerson}</TableCell>
                    <TableCell>{record.checkoutDate}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {record.items.map((item, idx) => (
                          <div key={idx} className="text-xs">
                            {item.materialName} × {item.actualQty} (批次: {item.batchNo})
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className="bg-green-100 text-green-700">
                        手动出库
                      </Badge>
                    </TableCell>
                    <TableCell>{record.notes || '-'}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 领用记录与溯源 */}
        <TabsContent value="record" className="space-y-4">
          <Card className="p-4 bg-orange-50 border-orange-200">
            <div className="flex items-start gap-2">
              <Activity className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-orange-900">
                <p className="mb-2">领用记录与溯源功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>电子台账</strong>: 每笔领用记录形成完整电子台账</li>
                  <li>• <strong>全程记录</strong>: 记录领用人、审批人、出库时间、物资批次</li>
                  <li>• <strong>用途追踪</strong>: 完整记录用途（地块/任务）信息</li>
                  <li>• <strong>质量溯源</strong>: 构成农产品质量安全溯源核心链条</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 统计图表 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <PieChartIcon className="w-4 h-4" />
                领用状态分布
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={statusChartData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, value }) => `${name}: ${value}`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {statusChartData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-4 h-4" />
                领用趋势分析
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={trendChartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line type="monotone" dataKey="count" stroke="#10b981" name="领用次数" />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>

          {/* 溯源记录查询 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <History className="w-5 h-5 text-green-600" />
                溯源记录查询
              </h3>
            </div>

            {/* 高级搜索和筛选 */}
            <div className="p-4 border-b space-y-4">
              {/* 第一行：搜索框和快捷筛选 */}
              <div className="flex gap-4">
                <div className="flex-1">
                  <Input 
                    placeholder="搜索申请单号、物资名称、领用人..." 
                    value={traceSearchTerm}
                    onChange={(e) => setTraceSearchTerm(e.target.value)}
                    className="w-full"
                  />
                </div>
                <Select value={traceMaterialType} onValueChange={setTraceMaterialType}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="物资类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    <SelectItem value="肥料">肥料</SelectItem>
                    <SelectItem value="农药">农药</SelectItem>
                    <SelectItem value="农具">农具</SelectItem>
                    <SelectItem value="种子">种子</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={traceDepartment} onValueChange={setTraceDepartment}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="部门" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部部门</SelectItem>
                    <SelectItem value="种植一队">种植一队</SelectItem>
                    <SelectItem value="种植二队">种植二队</SelectItem>
                    <SelectItem value="种植三队">种植三队</SelectItem>
                    <SelectItem value="养殖队">养殖队</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={traceField} onValueChange={setTraceField}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="地块" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部地块</SelectItem>
                    <SelectItem value="1号田块">1号田块</SelectItem>
                    <SelectItem value="2号田块">2号田块</SelectItem>
                    <SelectItem value="3号大棚">3号大棚</SelectItem>
                    <SelectItem value="4号果园">4号果园</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              {/* 第二行：日期范围和重置按钮 */}
              <div className="flex items-center gap-4">
                <Label className="text-sm whitespace-nowrap">出库日期：</Label>
                <Input 
                  type="date" 
                  value={traceDateRange.start}
                  onChange={(e) => setTraceDateRange({...traceDateRange, start: e.target.value})}
                  className="w-48"
                />
                <span className="text-muted-foreground">至</span>
                <Input 
                  type="date" 
                  value={traceDateRange.end}
                  onChange={(e) => setTraceDateRange({...traceDateRange, end: e.target.value})}
                  className="w-48"
                />
                <Button variant="outline" size="sm" onClick={handleResetFilters}>
                  <RefreshCw className="w-3 h-3 mr-1" />
                  重置筛选
                </Button>
                <div className="text-sm text-muted-foreground">
                  共 <span className="font-medium text-green-600">{filteredTraceRecords.length}</span> 条记录
                </div>
              </div>
            </div>

            {/* 溯源记录列表 */}
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>申请单号</TableHead>
                    <TableHead>物品数量</TableHead>
                    <TableHead>领用人</TableHead>
                    <TableHead>审批人</TableHead>
                    <TableHead>出库人</TableHead>
                    <TableHead>用途</TableHead>
                    <TableHead>时间链</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredTraceRecords.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                        <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
                        <p>暂无溯源记录</p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredTraceRecords.map((record) => {
                      const requisition = requisitions.find(r => r.code === record.requisitionCode);
                      const itemCount = requisition?.items.length || 1;
                      return (
                      <TableRow key={record.id}>
                      <TableCell className="font-medium">{record.requisitionCode}</TableCell>
                      <TableCell>{itemCount}项</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <User className="w-3 h-3 text-muted-foreground" />
                          {record.applicant}
                        </div>
                      </TableCell>
                      <TableCell>{record.approver}</TableCell>
                      <TableCell>{record.checkoutPerson}</TableCell>
                      <TableCell>
                        <div className="space-y-1 text-xs">
                          <div className="flex items-center gap-1">
                            <Tag className="w-3 h-3" />
                            {record.purpose}
                          </div>
                          {record.relatedField && (
                            <div className="flex items-center gap-1 text-muted-foreground">
                              <MapPin className="w-3 h-3" />
                              {record.relatedField}
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1 text-xs">
                          <div className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            申请: {record.applyDate}
                          </div>
                          <div className="flex items-center gap-1">
                            <CheckCircle className="w-3 h-3" />
                            审批: {record.approveDate}
                          </div>
                          <div className="flex items-center gap-1">
                            <Package className="w-3 h-3" />
                            出库: {record.checkoutDate}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Button 
                          size="sm" 
                          variant="outline"
                          onClick={() => handleViewTraceDetail(record)}
                        >
                          <Eye className="w-3 h-3 mr-1" />
                          查看详情
                        </Button>
                      </TableCell>
                      </TableRow>
                    );
                    })
                  )}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 新建申请对话框 */}
      <Dialog open={showApplyDialog} onOpenChange={(open) => {
        setShowApplyDialog(open);
        if (!open) {
          // 关闭时重置表单
          setFormData({
            department: 'team1',
            relatedTask: '',
            relatedField: '',
            plannedUseDate: '',
            priority: 'medium',
            purpose: '',
            notes: '',
          });
          setSelectedItems([]);
          setAttachments([]);
        }
      }}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isEditingDraft ? '编辑草稿' : '新建领用申请'}</DialogTitle>
            <DialogDescription>
              {isEditingDraft ? '修改草稿信息后可保存或直接提交审批' : '填写物资领用申请信息，提交后将进入审批流程'}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            {/* 基本信息提示 */}
            <Card className="p-3 bg-blue-50 border-blue-200">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                <div className="text-xs text-blue-900">
                  <p className="mb-1">填写说明：</p>
                  <ul className="space-y-0.5">
                    <li>• 请准确填写领用用途和关联的任务或地块，便于后期溯源</li>
                    <li>• 选择物品时注意查看当前库存，避免申请数量超出</li>
                    <li>• 可上传相关说明文件（如作业方案、施肥计划等）作为附件</li>
                  </ul>
                </div>
              </div>
            </Card>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>申请人 <span className="text-red-500">*</span></Label>
                <Input defaultValue="当前用户" disabled />
              </div>
              <div>
                <Label>所属部门 <span className="text-red-500">*</span></Label>
                <Select 
                  value={formData.department}
                  onValueChange={(value) => setFormData({...formData, department: value})}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="team1">种植一队</SelectItem>
                    <SelectItem value="team2">种植二队</SelectItem>
                    <SelectItem value="team3">种植三队</SelectItem>
                    <SelectItem value="team4">畜牧队</SelectItem>
                    <SelectItem value="team5">综合队</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>关联任务（可选）</Label>
                <Select 
                  value={formData.relatedTask}
                  onValueChange={(value) => setFormData({...formData, relatedTask: value})}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择关联任务" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不关联任务</SelectItem>
                    <SelectItem value="task1">任务-2024001 - 水稻田施肥</SelectItem>
                    <SelectItem value="task2">任务-2024002 - 玉米田除草</SelectItem>
                    <SelectItem value="task3">任务-2024003 - 蔬菜大棚灌溉</SelectItem>
                    <SelectItem value="task4">任务-2024004 - 果树修剪</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>关联地块（可选）</Label>
                <Select 
                  value={formData.relatedField}
                  onValueChange={(value) => setFormData({...formData, relatedField: value})}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择关联地块" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不关联地块</SelectItem>
                    <SelectItem value="field1">1号田块 (水稻)</SelectItem>
                    <SelectItem value="field2">2号田块 (玉米)</SelectItem>
                    <SelectItem value="field3">3号大棚 (蔬菜)</SelectItem>
                    <SelectItem value="field4">4号果园 (苹果)</SelectItem>
                    <SelectItem value="field5">5号大棚 (草莓)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>计划领用时间 <span className="text-red-500">*</span></Label>
                <Input 
                  type="date" 
                  value={formData.plannedUseDate}
                  onChange={(e) => setFormData({...formData, plannedUseDate: e.target.value})}
                  min={new Date().toISOString().split('T')[0]}
                />
              </div>
              <div>
                <Label>优先级 <span className="text-red-500">*</span></Label>
                <Select 
                  value={formData.priority}
                  onValueChange={(value: Priority) => setFormData({...formData, priority: value})}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="high">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-red-500"></div>
                        高 - 紧急需要
                      </div>
                    </SelectItem>
                    <SelectItem value="medium">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-yellow-500"></div>
                        中 - 正常需求
                      </div>
                    </SelectItem>
                    <SelectItem value="low">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-blue-500"></div>
                        低 - 不紧急
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>领用用途 <span className="text-red-500">*</span></Label>
              <Textarea 
                placeholder="详细说明物资的用途，例如：用于1号田块水稻施肥作业，预计施肥面积50亩..."
                rows={3}
                value={formData.purpose}
                onChange={(e) => setFormData({...formData, purpose: e.target.value})}
              />
            </div>

            {/* 物品清单 */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label>物品清单 <span className="text-red-500">*</span></Label>
                <Button size="sm" variant="outline" onClick={handleAddItem}>
                  <Plus className="w-3 h-3 mr-1" />
                  添加物品
                </Button>
              </div>
              <div className="space-y-2 max-h-80 overflow-y-auto">
                {selectedItems.map((item, index) => (
                  <Card key={item.id} className="p-3">
                    <div className="space-y-3">
                      <div className="grid grid-cols-6 gap-2 items-end">
                        <div>
                          <Label className="text-xs">物品类型 <span className="text-red-500">*</span></Label>
                          <Select
                            value={item.materialCategory || ''}
                            onValueChange={(value) => handleUpdateItem(item.id, 'materialCategory', value)}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="选择类型" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="农资">农资</SelectItem>
                              <SelectItem value="农具">农具</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="col-span-2">
                          <Label className="text-xs">物资名称 <span className="text-red-500">*</span></Label>
                          <Select
                            value={item.materialId}
                            onValueChange={(value) => handleUpdateItem(item.id, 'materialId', value)}
                            disabled={!item.materialCategory}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={item.materialCategory ? "选择物资" : "请先选择类型"} />
                            </SelectTrigger>
                            <SelectContent>
                              {item.materialCategory === '农资' && (
                                <>
                                  <SelectItem value="mat1">复合肥 (肥料)</SelectItem>
                                  <SelectItem value="mat2">尿素 (肥料)</SelectItem>
                                  <SelectItem value="mat8">钾肥 (肥料)</SelectItem>
                                  <SelectItem value="mat3">除草剂 (农药)</SelectItem>
                                  <SelectItem value="mat5">杀虫剂 (农药)</SelectItem>
                                </>
                              )}
                              {item.materialCategory === '农具' && (
                                <>
                                  <SelectItem value="mat4">滴灌管 (农具)</SelectItem>
                                  <SelectItem value="mat6">地膜 (农具)</SelectItem>
                                  <SelectItem value="mat7">喷雾器 (农具)</SelectItem>
                                </>
                              )}
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Label className="text-xs">申请数量 <span className="text-red-500">*</span></Label>
                          <Input 
                            type="number" 
                            placeholder="0"
                            min="0"
                            value={item.requestedQuantity || ''}
                            onChange={(e) => handleUpdateItem(item.id, 'requestedQuantity', Number(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label className="text-xs">单位</Label>
                          <Input value={item.unit || '-'} disabled className="bg-gray-50" />
                        </div>
                        <div>
                          <Label className="text-xs">当前库存</Label>
                          <Input 
                            value={item.currentStock || '-'} 
                            disabled 
                            className={cn(
                              "bg-gray-50",
                              item.requestedQuantity > 0 && item.requestedQuantity > item.currentStock && "border-red-500"
                            )}
                          />
                        </div>
                        <div>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleRemoveItem(item.id)}
                            className="w-full text-red-600 hover:text-red-700 hover:bg-red-50"
                          >
                            <XCircle className="w-3 h-3 mr-1" />
                            删除
                          </Button>
                        </div>
                      </div>
                      
                      {/* 库存警告 */}
                      {item.requestedQuantity > 0 && item.requestedQuantity > item.currentStock && (
                        <div className="flex items-start gap-2 p-2 bg-red-50 border border-red-200 rounded text-xs text-red-700">
                          <AlertCircle className="w-3 h-3 flex-shrink-0 mt-0.5" />
                          <span>申请数量超过当前库存！当前库存仅有 {item.currentStock} {item.unit}</span>
                        </div>
                      )}
                      
                      {/* 预估金额 */}
                      {item.materialId && item.requestedQuantity > 0 && (
                        <div className="text-xs text-muted-foreground">
                          预估单价: ¥{item.estimatedPrice} / {item.unit} ，小计: 
                          <span className="font-medium text-green-600 ml-1">
                            ¥{(item.requestedQuantity * item.estimatedPrice).toFixed(2)}
                          </span>
                        </div>
                      )}
                    </div>
                  </Card>
                ))}
                {selectedItems.length === 0 && (
                  <div className="text-center py-12 border-2 border-dashed rounded-lg text-muted-foreground">
                    <Package className="w-12 h-12 mx-auto mb-2 opacity-50" />
                    <p>暂无物品，请点击"添加物品"按钮</p>
                  </div>
                )}
              </div>
              
              {/* 总计 */}
              {selectedItems.length > 0 && (
                <div className="mt-2 p-3 bg-gray-50 rounded-lg flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">
                    共 {selectedItems.length} 项物品
                  </span>
                  <div className="text-sm">
                    <span className="text-muted-foreground">预估总金额: </span>
                    <span className="text-lg text-green-600">
                      ¥{selectedItems.reduce((sum, item) => 
                        sum + (item.requestedQuantity * item.estimatedPrice), 0
                      ).toFixed(2)}
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* 附件上传 */}
            <div>
              <Label>附件上传（可选）</Label>
              <div 
                className={cn(
                  "mt-2 border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer",
                  isDragging ? "border-green-500 bg-green-50" : "border-gray-300 hover:border-green-400"
                )}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => document.getElementById('file-upload')?.click()}
              >
                <input
                  id="file-upload"
                  type="file"
                  multiple
                  className="hidden"
                  onChange={handleFileSelect}
                  accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.gif,.txt"
                />
                <Upload className={cn(
                  "w-8 h-8 mx-auto mb-2",
                  isDragging ? "text-green-600" : "text-muted-foreground"
                )} />
                <p className="text-sm text-muted-foreground mb-1">
                  {isDragging ? '释放以上传文件' : '点击上传或拖拽文件到此区域'}
                </p>
                <p className="text-xs text-muted-foreground">
                  支持 PDF、Word、图片、文本等格式，单个文件不超过10MB
                </p>
              </div>
              
              {/* 已上传文件列表 */}
              {attachments.length > 0 && (
                <div className="mt-3 space-y-2">
                  <p className="text-xs text-muted-foreground">已上传 {attachments.length} 个文件:</p>
                  {attachments.map((file, index) => (
                    <div key={index} className="flex items-center gap-2 p-2 border rounded hover:bg-gray-50">
                      <Paperclip className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm truncate">{file.name}</p>
                        <p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
                      </div>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleRemoveAttachment(index);
                        }}
                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                      >
                        <XCircle className="w-4 h-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div>
              <Label>备注</Label>
              <Textarea 
                placeholder="其他需要说明的信息..."
                rows={2}
                value={formData.notes}
                onChange={(e) => setFormData({...formData, notes: e.target.value})}
              />
            </div>
          </div>

          <DialogFooter className="flex gap-2">
            <Button variant="outline" onClick={() => setShowApplyDialog(false)}>
              取消
            </Button>
            <Button variant="outline" onClick={handleSaveDraft} className="border-blue-500 text-blue-600 hover:bg-blue-50">
              <Save className="w-4 h-4 mr-2" />
              保存草稿
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSubmitRequisition}>
              <Send className="w-4 h-4 mr-2" />
              提交审批
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 审批对话框 */}
      <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle>审批领用申请</DialogTitle>
            <DialogDescription>
              请仔细审核申请信息，并作出审批决定
            </DialogDescription>
          </DialogHeader>

          {selectedRequisition && (
            <div className="space-y-4 overflow-y-auto pr-2">
              <Card className="p-4 bg-gray-50">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">申请单号：</span>
                    <span className="font-medium">{selectedRequisition.code}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">申请人：</span>
                    <span className="font-medium">{selectedRequisition.applicant}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">部门：</span>
                    <span>{selectedRequisition.department}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">申请时间：</span>
                    <span>{selectedRequisition.applyDate}</span>
                  </div>
                  <div className="col-span-2">
                    <span className="text-muted-foreground">用途：</span>
                    <span>{selectedRequisition.purpose}</span>
                  </div>
                </div>
              </Card>

              <div>
                <Label>物品清单</Label>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>物资名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>申请数量</TableHead>
                      <TableHead>当前库存</TableHead>
                      <TableHead>预估单价</TableHead>
                      <TableHead>小计</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedRequisition.items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>{item.materialName}</TableCell>
                        <TableCell>{item.materialType}</TableCell>
                        <TableCell>{item.requestedQuantity}{item.unit}</TableCell>
                        <TableCell>{item.currentStock}{item.unit}</TableCell>
                        <TableCell>¥{item.estimatedPrice}</TableCell>
                        <TableCell>¥{(item.requestedQuantity * item.estimatedPrice).toLocaleString()}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
                <div className="mt-2 text-right">
                  <span className="text-sm text-muted-foreground">预估总金额：</span>
                  <span className="text-lg font-medium text-green-600 ml-2">
                    ¥{selectedRequisition.totalAmount.toLocaleString()}
                  </span>
                </div>
              </div>

              {selectedRequisition.attachments && selectedRequisition.attachments.length > 0 && (
                <div>
                  <Label>附件</Label>
                  <div className="mt-2 space-y-2">
                    {selectedRequisition.attachments.map((file, idx) => (
                      <div key={idx} className="flex items-center gap-2 p-2 border rounded">
                        <Paperclip className="w-4 h-4 text-muted-foreground" />
                        <span className="text-sm">{file}</span>
                        <Button size="sm" variant="ghost" className="ml-auto">
                          <Download className="w-3 h-3" />
                        </Button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 审批决定选择 */}
              <div>
                <Label>审批决定 <span className="text-red-500">*</span></Label>
                <div className="grid grid-cols-3 gap-3 mt-2">
                  <Card 
                    className={cn(
                      "p-4 cursor-pointer transition-all border-2",
                      approvalFormData.action === '同意' 
                        ? "border-green-500 bg-green-50" 
                        : "border-gray-200 hover:border-green-300"
                    )}
                    onClick={() => setApprovalFormData({...approvalFormData, action: '同意'})}
                  >
                    <div className="flex flex-col items-center gap-2">
                      <CheckCircle className={cn(
                        "w-8 h-8",
                        approvalFormData.action === '同意' ? "text-green-600" : "text-gray-400"
                      )} />
                      <span className={cn(
                        approvalFormData.action === '同意' ? "text-green-700" : "text-gray-600"
                      )}>同意</span>
                    </div>
                  </Card>
                  
                  <Card 
                    className={cn(
                      "p-4 cursor-pointer transition-all border-2",
                      approvalFormData.action === '修改' 
                        ? "border-blue-500 bg-blue-50" 
                        : "border-gray-200 hover:border-blue-300"
                    )}
                    onClick={() => setApprovalFormData({...approvalFormData, action: '修改'})}
                  >
                    <div className="flex flex-col items-center gap-2">
                      <Edit className={cn(
                        "w-8 h-8",
                        approvalFormData.action === '修改' ? "text-blue-600" : "text-gray-400"
                      )} />
                      <span className={cn(
                        approvalFormData.action === '修改' ? "text-blue-700" : "text-gray-600"
                      )}>修改</span>
                    </div>
                  </Card>
                  
                  <Card 
                    className={cn(
                      "p-4 cursor-pointer transition-all border-2",
                      approvalFormData.action === '驳回' 
                        ? "border-red-500 bg-red-50" 
                        : "border-gray-200 hover:border-red-300"
                    )}
                    onClick={() => setApprovalFormData({...approvalFormData, action: '驳回'})}
                  >
                    <div className="flex flex-col items-center gap-2">
                      <XCircle className={cn(
                        "w-8 h-8",
                        approvalFormData.action === '驳回' ? "text-red-600" : "text-gray-400"
                      )} />
                      <span className={cn(
                        approvalFormData.action === '驳回' ? "text-red-700" : "text-gray-600"
                      )}>驳回</span>
                    </div>
                  </Card>
                </div>
              </div>
              
              {/* 修改数量（仅当选择"修改"时显示） */}
              {approvalFormData.action === '修改' && (
                <div>
                  <Label>调整申请数量</Label>
                  <Card className="p-3 mt-2">
                    <div className="space-y-2">
                      {selectedRequisition.items.map((item, index) => (
                        <div key={item.id} className="flex items-center gap-3">
                          <span className="text-sm flex-1">{item.materialName}</span>
                          <span className="text-xs text-muted-foreground">
                            申请：{item.requestedQuantity}{item.unit}
                          </span>
                          <ArrowRight className="w-4 h-4 text-muted-foreground" />
                          <Input
                            type="number"
                            placeholder="调整后数量"
                            className="w-32"
                            defaultValue={item.requestedQuantity}
                            onChange={(e) => {
                              const modifiedItems = [...approvalFormData.modifiedItems];
                              modifiedItems[index] = {
                                ...item,
                                approvedQuantity: Number(e.target.value)
                              };
                              setApprovalFormData({...approvalFormData, modifiedItems});
                            }}
                          />
                          <span className="text-xs text-muted-foreground w-12">{item.unit}</span>
                        </div>
                      ))}
                    </div>
                  </Card>
                  <p className="text-xs text-muted-foreground mt-2">
                    修改后的数量将作为最终批准数量
                  </p>
                </div>
              )}

              <div>
                <Label>审批意见 <span className="text-red-500">*</span></Label>
                <Textarea 
                  placeholder={
                    approvalFormData.action === '同意' 
                      ? '填写同意理由...' 
                      : approvalFormData.action === '驳回'
                      ? '填写驳回原因...'
                      : '填写修改说明...'
                  }
                  rows={3}
                  value={approvalFormData.comments}
                  onChange={(e) => setApprovalFormData({...approvalFormData, comments: e.target.value})}
                />
              </div>
              
              {/* 通知渠道选择 */}
              <div>
                <Label>通知申请人方式</Label>
                <div className="grid grid-cols-3 gap-3 mt-2">
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="system-msg"
                      checked={notificationChannels.systemMessage}
                      onChange={(e) => setNotificationChannels({
                        ...notificationChannels,
                        systemMessage: e.target.checked
                      })}
                      className="rounded"
                    />
                    <label htmlFor="system-msg" className="text-sm cursor-pointer">
                      系统消息
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="sms"
                      checked={notificationChannels.sms}
                      onChange={(e) => setNotificationChannels({
                        ...notificationChannels,
                        sms: e.target.checked
                      })}
                      className="rounded"
                    />
                    <label htmlFor="sms" className="text-sm cursor-pointer">
                      短信通知
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="email"
                      checked={notificationChannels.email}
                      onChange={(e) => setNotificationChannels({
                        ...notificationChannels,
                        email: e.target.checked
                      })}
                      className="rounded"
                    />
                    <label htmlFor="email" className="text-sm cursor-pointer">
                      邮件通知
                    </label>
                  </div>
                </div>
              </div>
              
              {/* 审批提示 */}
              <Card className="p-3 bg-orange-50 border-orange-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-orange-600 flex-shrink-0 mt-0.5" />
                  <div className="text-xs text-orange-900">
                    <p>温馨提示：</p>
                    <ul className="mt-1 space-y-0.5">
                      <li>• 审批意见将永久保存，作为审批依据</li>
                      <li>• 审批后将通过所选渠道通知申请人</li>
                      <li>• 同意后申请将进入出库环节</li>
                      <li>• 驳回后申请人可修改后重新提交</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowApprovalDialog(false);
              setApprovalFormData({ action: '', comments: '', modifiedItems: [] });
            }}>
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={() => handleApprove(approvalFormData.action as ApprovalAction)}
              disabled={!approvalFormData.action}
            >
              {approvalFormData.action === '同意' && <CheckCircle className="w-4 h-4 mr-2" />}
              {approvalFormData.action === '修改' && <Edit className="w-4 h-4 mr-2" />}
              {approvalFormData.action === '驳回' && <XCircle className="w-4 h-4 mr-2" />}
              确认审批
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 出库对话框 */}
      <Dialog open={showCheckoutDialog} onOpenChange={(open) => {
        if (!open) {
          // 关闭时重置表单
          setCheckoutFormData({
            scanMode: 'manual',
            checkoutItems: [],
            notes: '',
          });
          setScanInput('');
        }
        setShowCheckoutDialog(open);
      }}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Package className="w-5 h-5 text-green-600" />
              物资出库操作
            </DialogTitle>
            <DialogDescription>
              凭单作业，填写批次号和出库数量，系统将自动核减库存并通知相关人员
            </DialogDescription>
          </DialogHeader>

          {selectedRequisition && (
            <div className="space-y-4">
              {/* 申请单信息 */}
              <Card className="p-4 bg-gray-50">
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">申请单号：</span>
                    <span className="font-medium">{selectedRequisition.code}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">领用人：</span>
                    <span className="font-medium">{selectedRequisition.applicant}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">部门：</span>
                    <span>{selectedRequisition.department}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">用途：</span>
                    <span className="truncate">{selectedRequisition.purpose}</span>
                  </div>
                </div>
              </Card>
              
              {/* 操作提示 */}
              <Card className="p-3 bg-blue-50 border-blue-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div className="text-xs text-blue-900">
                    <p className="mb-1">出库操作说明：</p>
                    <ul className="space-y-0.5">
                      <li>• <strong>填写信息</strong>：在表格中输入批次号和实际出库数量</li>
                      <li>• <strong>先进先出</strong>：建议优先选择最早批次的物资</li>
                      <li>• <strong>实时核减</strong>：确认出库后立即核减库存，并通知申请人和财务系统</li>
                    </ul>
                  </div>
                </div>
              </Card>

              {/* 出库清单 */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>出库清单</Label>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => initializeCheckoutItems(selectedRequisition)}
                  >
                    <RefreshCw className="w-3 h-3 mr-1" />
                    初始化清单
                  </Button>
                </div>
                <Card>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>物资名称</TableHead>
                        <TableHead>批准数量</TableHead>
                        <TableHead>实际出库</TableHead>
                        <TableHead>仓库-批次号</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {checkoutFormData.checkoutItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={4} className="text-center text-muted-foreground py-8">
                            <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
                            <p>点击"初始化清单"开始出库操作</p>
                          </TableCell>
                        </TableRow>
                      ) : (
                        checkoutFormData.checkoutItems.map((item) => (
                          <TableRow key={item.itemId}>
                            <TableCell className="font-medium">{item.materialName}</TableCell>
                            <TableCell>{item.approvedQuantity}{item.unit}</TableCell>
                            <TableCell>
                              <Input
                                type="number"
                                placeholder="输入数量"
                                value={item.actualQuantity}
                                onChange={(e) => handleUpdateCheckoutQuantity(item.itemId, Number(e.target.value))}
                                className="w-28"
                              />
                            </TableCell>
                            <TableCell>
                              <div className="flex gap-2 items-center">
                                <Select
                                  value={item.batchNo?.split('-')[0] || ''}
                                  onValueChange={(value) => {
                                    const currentBatchNo = item.batchNo?.split('-')[1] || '';
                                    const newBatchNo = currentBatchNo ? `${value}-${currentBatchNo}` : value;
                                    handleManualBatchInput(item.itemId, newBatchNo);
                                  }}
                                >
                                  <SelectTrigger className="w-32">
                                    <SelectValue placeholder="选择仓库" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="1号仓库">1号仓库</SelectItem>
                                    <SelectItem value="2号仓库">2号仓库</SelectItem>
                                    <SelectItem value="3号仓库">3号仓库</SelectItem>
                                    <SelectItem value="4号仓库">4号仓库</SelectItem>
                                  </SelectContent>
                                </Select>
                                <span className="text-muted-foreground">-</span>
                                <Input 
                                  placeholder="批次号" 
                                  className="w-32"
                                  value={item.batchNo?.includes('-') ? item.batchNo.split('-')[1] : item.batchNo || ''}
                                  onChange={(e) => {
                                    const warehouse = item.batchNo?.split('-')[0] || '';
                                    const newBatchNo = warehouse ? `${warehouse}-${e.target.value}` : e.target.value;
                                    handleManualBatchInput(item.itemId, newBatchNo);
                                  }}
                                />
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </Card>
              </div>

              {/* 备注 */}
              <div>
                <Label>出库备注</Label>
                <Textarea 
                  placeholder="备注信息（如特殊说明、注意事项等）..."
                  rows={2}
                  value={checkoutFormData.notes}
                  onChange={(e) => setCheckoutFormData({...checkoutFormData, notes: e.target.value})}
                />
              </div>
              
              {/* 确认提示 */}
              <Card className="p-3 bg-orange-50 border-orange-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-orange-600 flex-shrink-0 mt-0.5" />
                  <div className="text-xs text-orange-900">
                    <p className="mb-1">确认出库后将执行以下操作：</p>
                    <ul className="space-y-0.5">
                      <li>• <strong>自动核减库存</strong>：根据实际出库数量立即核减对应批次的库存</li>
                      <li>• <strong>通知申请人</strong>：通过系统消息和短信通知领用人出库完成</li>
                      <li>• <strong>同步财务系统</strong>：将出库数据推送给财务系统进行成本核算</li>
                      <li>• <strong>记录溯源信息</strong>：完整记录出库人、时间、批次等溯源数据</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCheckoutDialog(false)}>
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700"
              onClick={handleConfirmCheckout}
              disabled={checkoutFormData.checkoutItems.length === 0}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              确认出库
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>领用申请详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看物资领用申请的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedRequisition && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4">
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">申请单号</p>
                    <p className="font-medium">{selectedRequisition.code}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">申请人</p>
                    <p>{selectedRequisition.applicant}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">所属部门</p>
                    <p>{selectedRequisition.department}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">申请时间</p>
                    <p>{selectedRequisition.applyDate}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">计划领用时间</p>
                    <p>{selectedRequisition.plannedUseDate}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">当前状态</p>
                    <Badge className={getStatusColor(selectedRequisition.status)}>
                      {selectedRequisition.status}
                    </Badge>
                  </div>
                  <div className="col-span-3">
                    <p className="text-muted-foreground mb-1">用途</p>
                    <p>{selectedRequisition.purpose}</p>
                  </div>
                  {selectedRequisition.relatedTask && (
                    <div>
                      <p className="text-muted-foreground mb-1">关联任务</p>
                      <p>{selectedRequisition.relatedTask}</p>
                    </div>
                  )}
                  {selectedRequisition.relatedField && (
                    <div>
                      <p className="text-muted-foreground mb-1">关联地块</p>
                      <p>{selectedRequisition.relatedField}</p>
                    </div>
                  )}
                </div>
              </Card>

              {/* 物品清单 */}
              <Card className="p-4">
                <h4 className="mb-3">物品清单</h4>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>物资名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>申请数量</TableHead>
                      <TableHead>批准数量</TableHead>
                      <TableHead>实际出库</TableHead>
                      <TableHead>预估单价</TableHead>
                      <TableHead>小计</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedRequisition.items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>{item.materialName}</TableCell>
                        <TableCell>{item.materialType}</TableCell>
                        <TableCell>{item.requestedQuantity}{item.unit}</TableCell>
                        <TableCell>{item.approvedQuantity ? `${item.approvedQuantity}${item.unit}` : '-'}</TableCell>
                        <TableCell>{item.actualQuantity ? `${item.actualQuantity}${item.unit}` : '-'}</TableCell>
                        <TableCell>¥{item.estimatedPrice}</TableCell>
                        <TableCell>¥{(item.requestedQuantity * item.estimatedPrice).toLocaleString()}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </Card>

              {/* 审批信息 */}
              {selectedRequisition.approver && (
                <Card className="p-4">
                  <h4 className="mb-3">审批信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <p className="text-muted-foreground mb-1">审批人</p>
                      <p>{selectedRequisition.approver}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">审批时间</p>
                      <p>{selectedRequisition.approveDate}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">审批结果</p>
                      <Badge className="bg-green-100 text-green-700">已通过</Badge>
                    </div>
                    {selectedRequisition.approvalComments && (
                      <div className="col-span-3">
                        <p className="text-muted-foreground mb-1">审批意见</p>
                        <p>{selectedRequisition.approvalComments}</p>
                      </div>
                    )}
                  </div>
                </Card>
              )}

              {/* 出库信息 */}
              {selectedRequisition.checkoutPerson && (
                <Card className="p-4">
                  <h4 className="mb-3">出库信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <p className="text-muted-foreground mb-1">出库人</p>
                      <p>{selectedRequisition.checkoutPerson}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">出库时间</p>
                      <p>{selectedRequisition.checkoutDate}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">出库状态</p>
                      <Badge className="bg-green-100 text-green-700">已完成</Badge>
                    </div>
                  </div>
                </Card>
              )}
            </div>
          )}

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

      {/* 溯源详情对话框 */}
      <Dialog open={showTraceDetailDialog} onOpenChange={setShowTraceDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="w-5 h-5 text-green-600" />
              物资领用溯源详情
            </DialogTitle>
            <DialogDescription>
              完整的物资领用全生命周期追溯信息
            </DialogDescription>
          </DialogHeader>

          {selectedTraceRecord && (
            <div className="space-y-4">
              {/* 溯源链条可视化 */}
              <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
                <h4 className="mb-4 flex items-center gap-2">
                  <ArrowRight className="w-4 h-4 text-green-600" />
                  溯源链条
                </h4>
                <div className="flex items-center justify-around max-w-3xl mx-auto">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-12 h-12 rounded-full bg-purple-500 text-white flex items-center justify-center">
                        <FileText className="w-6 h-6" />
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">领用申请</p>
                        <p className="font-medium text-sm">{selectedTraceRecord.applicant}</p>
                        <p className="text-xs text-muted-foreground">
                          {selectedTraceRecord.applyDate}
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  <ArrowRight className="w-6 h-6 text-gray-400 mx-4" />
                  
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-12 h-12 rounded-full bg-orange-500 text-white flex items-center justify-center">
                        <UserCheck className="w-6 h-6" />
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">审批通过</p>
                        <p className="font-medium text-sm">{selectedTraceRecord.approver}</p>
                        <p className="text-xs text-muted-foreground">
                          {selectedTraceRecord.approveDate}
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  <ArrowRight className="w-6 h-6 text-gray-400 mx-4" />
                  
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-12 h-12 rounded-full bg-green-500 text-white flex items-center justify-center">
                        <Warehouse className="w-6 h-6" />
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">出库完成</p>
                        <p className="font-medium text-sm">{selectedTraceRecord.checkoutPerson}</p>
                        <p className="text-xs text-muted-foreground">
                          {selectedTraceRecord.checkoutDate}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 物资清单 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Package className="w-4 h-4 text-blue-600" />
                  物资清单
                </h4>
                <div className="space-y-3">
                  {(() => {
                    // 查找对应的申请单以获取完整的物资列表
                    const requisition = requisitions.find(r => r.code === selectedTraceRecord.requisitionCode);
                    const items = requisition?.items || [];
                    
                    // 如果找到了申请单的物资列表，显示所有物资
                    if (items.length > 0) {
                      return (
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>物资名称</TableHead>
                              <TableHead>类型</TableHead>
                              <TableHead>批次号</TableHead>
                              <TableHead>数量</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {items.map((item, index) => (
                              <TableRow key={index}>
                                <TableCell className="font-medium">{item.materialName}</TableCell>
                                <TableCell>
                                  <Badge variant="outline">{item.materialType}</Badge>
                                </TableCell>
                                <TableCell>
                                  <Badge className="font-mono bg-green-100 text-green-700 text-xs">
                                    {selectedTraceRecord.batchNo}
                                  </Badge>
                                </TableCell>
                                <TableCell>{item.actualQuantity || item.requestedQuantity}{item.unit}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      );
                    } else {
                      // 如果没有找到申请单，显示单个物资信息
                      return (
                        <div className="space-y-3 text-sm">
                          <div>
                            <p className="text-muted-foreground mb-1">物资名称</p>
                            <p className="font-medium">{selectedTraceRecord.materialName}</p>
                          </div>
                          <div>
                            <p className="text-muted-foreground mb-1">物资类型</p>
                            <Badge variant="outline">{selectedTraceRecord.materialType}</Badge>
                          </div>
                          <div>
                            <p className="text-muted-foreground mb-1">批次号</p>
                            <Badge className="font-mono bg-green-100 text-green-700">
                              {selectedTraceRecord.batchNo}
                            </Badge>
                          </div>
                          <div>
                            <p className="text-muted-foreground mb-1">数量</p>
                            <p className="font-medium">{selectedTraceRecord.quantity}{selectedTraceRecord.unit}</p>
                          </div>
                        </div>
                      );
                    }
                  })()}
                </div>
              </Card>

              {/* 人员信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <User className="w-4 h-4 text-orange-600" />
                  人员信息
                </h4>
                <div className="space-y-3 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">领用人</p>
                    <p className="font-medium">{selectedTraceRecord.applicant}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">所属部门</p>
                    <p>{selectedTraceRecord.department}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">审批人</p>
                    <p>{selectedTraceRecord.approver}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">出库人</p>
                    <p>{selectedTraceRecord.checkoutPerson}</p>
                  </div>
                </div>
              </Card>

              {/* 用途和关联信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Tag className="w-4 h-4 text-green-600" />
                  用途与关联信息
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">申请单号</p>
                    <p className="font-medium font-mono">{selectedTraceRecord.requisitionCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">用途说明</p>
                    <p>{selectedTraceRecord.purpose}</p>
                  </div>
                  {selectedTraceRecord.relatedField && (
                    <div>
                      <p className="text-muted-foreground mb-1">关联地块</p>
                      <div className="flex items-center gap-1">
                        <MapPin className="w-3 h-3 text-green-600" />
                        <p className="font-medium">{selectedTraceRecord.relatedField}</p>
                      </div>
                    </div>
                  )}
                  {selectedTraceRecord.relatedTask && (
                    <div>
                      <p className="text-muted-foreground mb-1">关联任务</p>
                      <p>{selectedTraceRecord.relatedTask}</p>
                    </div>
                  )}
                </div>
              </Card>

              {/* 时间线 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-purple-600" />
                  完整时间线
                </h4>
                <div className="space-y-3">
                  <div className="flex items-start gap-3 text-sm">
                    <div className="w-20 text-muted-foreground shrink-0">申请时间</div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-blue-500"></div>
                      <span className="font-medium">{selectedTraceRecord.applyDate}</span>
                    </div>
                  </div>
                  <div className="flex items-start gap-3 text-sm">
                    <div className="w-20 text-muted-foreground shrink-0">审批时间</div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-orange-500"></div>
                      <span className="font-medium">{selectedTraceRecord.approveDate}</span>
                    </div>
                  </div>
                  <div className="flex items-start gap-3 text-sm">
                    <div className="w-20 text-muted-foreground shrink-0">出库时间</div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-green-500"></div>
                      <span className="font-medium">{selectedTraceRecord.checkoutDate}</span>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 溯源说明 */}
              <Card className="p-4 bg-amber-50 border-amber-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-amber-900">
                    <p className="mb-2 font-medium">溯源说明</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>使用追踪</strong>：记录了物资的具体用途、使用地块和关联任务</li>
                      <li>• <strong>责任追溯</strong>：完整记录领用人、审批人、出库人，责任明确</li>
                      <li>• <strong>流程管理</strong>：本记录是物资领用全流程管理的核心链条</li>
                      <li>• <strong>投入品管理</strong>：确保所有农业投入品去向可追、责任可究</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setShowTraceDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
