import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle 
} from '../ui/alert-dialog';
import { Progress } from '../ui/progress';
import { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { Checkbox } from '../ui/checkbox';
import {
  Package,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  ArrowDownCircle,
  ArrowUpCircle,
  Warehouse,
  MapPin,
  Calendar,
  User,
  FileText,
  Barcode,
  TrendingUp,
  TrendingDown,
  Activity,
  Bell,
  BarChart3,
  PieChart as PieChartIcon,
  Clock,
  Save,
  Send,
  Printer,
  Smartphone,
  Target,
  Zap,
  Box,
  Layers,
  ListChecks,
  ClipboardList,
  ShoppingCart,
  AlertCircle,
  FileSearch,
  RefreshCw,
  Settings,
  Mail,
  X,
  QrCode,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';
import { LocationQRCodeDialog } from './LocationQRCodeDialog';

/**
 * AssetInventory Component
 * Last Updated: 2025-10-21 15:30:00
 * Fixed: Removed duplicate function declarations (getWarehouseLocations, getLocationStatusColor)
 */

interface AssetInventoryProps {
  activePath?: string;
}

type TransactionType = '入库' | '出库' | '调拨' | '盘盈' | '盘亏';
type WarehouseZone = 'A区' | 'B区' | 'C区' | 'D区';

interface InboundRecord {
  id: string;
  recordNo: string;
  orderNo?: string;
  type: '采购入库' | '退货入库' | '调拨入库' | '其他入库';
  warehouseId: string;
  warehouseName: string;
  supplierId?: string;
  supplierName?: string;
  items: InboundItem[];
  totalAmount: number;
  operator: string;
  inboundDate: string;
  batchNo: string;
  status: '待审核' | '已审核' | '已驳回';
  notes?: string;
  rejectReason?: string;
  createdAt: string;
}

interface InboundItem {
  id: string;
  materialId: string;
  materialName: string;
  spec: string;
  quantity: number;
  unit: string;
  unitPrice: number;
  amount: number;
  batchNo: string;
  productionDate: string;
  expiryDate: string;
  locationId?: string;
  locationCode?: string;
}

interface OutboundRecord {
  id: string;
  recordNo: string;
  type: '生产领用' | '销售出库' | '调拨出库' | '其他出库';
  warehouseId: string;
  warehouseName: string;
  // 调拨出库时的目标仓库
  targetWarehouseId?: string;
  targetWarehouseName?: string;
  recipient: string;
  recipientType: '员工' | '客户' | '其他';
  purpose: string;
  fieldId?: string;
  fieldName?: string;
  taskId?: string;
  taskName?: string;
  items: OutboundItem[];
  totalAmount: number;
  operator: string;
  outboundDate: string;
  status: '待审核' | '已审核' | '已驳回';
  notes?: string;
  rejectReason?: string;
  createdAt: string;
}

interface OutboundItem {
  id: string;
  materialId: string;
  materialName: string;
  spec: string;
  quantity: number;
  unit: string;
  batchNo: string;
  unitPrice: number;
  amount: number;
  locationId?: string;
  locationCode?: string;
}

interface StockCheckTask {
  id: string;
  taskNo: string;
  taskName: string;
  warehouseId: string;
  warehouseName: string;
  status: '待盘点' | '待审批' | '已完成' | '已取消';
  checkType: '全盘' | '抽盘';
  planDate: string;
  actualDate?: string;
  items: StockCheckItem[];
  profit: number;
  loss: number;
  checker: string;
  approver?: string;
  notes?: string;
  createdAt: string;
}

interface StockCheckItem {
  id: string;
  materialId: string;
  materialName: string;
  spec: string;
  unit: string;
  locationCode: string;
  batchNo: string;
  bookQuantity: number;
  actualQuantity?: number; // 可选，盘点时才填写
  difference: number;
  status: '待盘点' | '盘盈' | '盘亏' | '正常';
  selected?: boolean;
  notes?: string;
}

interface InventoryWarning {
  id: string;
  materialId: string;
  materialName: string;
  materialType: string;
  currentStock: number;
  safeStock: number;
  unit: string;
  warehouseName: string;
  warningType: '库存不足' | '临期预警' | '过期预警';
  warningLevel: '低' | '中' | '高';
  expiryDate?: string;
  daysLeft?: number;
  createdAt: string;
  handled: boolean;
}

interface StockTransaction {
  id: string;
  transactionNo: string;
  type: TransactionType;
  materialId: string;
  materialName: string;
  quantity: number;
  unit: string;
  batchNo: string;
  warehouseName: string;
  locationCode?: string;
  operator: string;
  relatedNo?: string;
  beforeStock: number;
  afterStock: number;
  createdAt: string;
  notes?: string;
}

interface Warehouse {
  id: string;
  name: string;
  code: string;
  type: string;
  address?: string;
  area?: number;
  manager?: string;
  contact?: string;
  status: '正常' | '维护中' | '禁用';
  locationCount: number;
  usedLocationCount: number;
  notes?: string;
  createdAt: string;
}

interface WarehouseLocation {
  id: string;
  code: string;
  name: string; // 位置名称
  warehouseId: string;
  warehouseName: string;
  status: '空闲' | '使用中' | '维护中' | '禁用';
  materials: LocationMaterial[];
  notes?: string;
  level?: string; // 层级
  capacity?: number; // 总容量
  usedCapacity?: number; // 已用容量
  zone?: string; // 区域
  row?: string; // 排
  shelf?: string; // 架
}

interface LocationMaterial {
  materialId: string;
  materialName: string;
  quantity: number;
  unit: string;
}

interface PurchaseSuggestion {
  id: string;
  materialId: string;
  materialName: string;
  materialType: string;
  currentStock: number;
  safeStock: number;
  avgDailyConsumption: number;
  forecastDays: number;
  forecastConsumption: number;
  suggestedQuantity: number;
  unit: string;
  lastPurchasePrice: number;
  estimatedAmount: number;
  priority: '高' | '中' | '低';
  reason: string;
}

// 采购订单接口 - 用于入库关联
interface PurchaseOrder {
  id: string;
  orderNo: string;
  supplierId: string;
  supplierName: string;
  totalAmount: number;
  items: PurchaseOrderItem[];
  expectedDeliveryDate: string;
  createdAt: string;
  status: '待审批' | '待复审' | '已下单' | '部分到货' | '已完成' | '已取消';
  approvalStatus: '待初审' | '待复审' | '已通过' | '已驳回';
}

interface PurchaseOrderItem {
  id: string;
  materialId: string;
  materialName: string;
  spec: string;
  quantity: number;
  receivedQuantity: number;
  unit: string;
  unitPrice: number;
  amount: number;
}

// 入库物料项（用于表单）
interface InboundFormItem {
  orderItemId: string;
  materialId: string;
  materialName: string;
  spec: string;
  unit: string;
  unitPrice: number;
  orderQuantity: number;
  receivedQuantity: number;
  remainingQuantity: number;
  inboundQuantity: number;
  batchNo: string;
  productionDate: string;
  expiryDate: string;
  locationId: string;
  locationCode: string;
}

// 可选农资材料
interface AvailableMaterial {
  id: string;
  name: string;
  type: string;
  spec: string;
  unit: string;
  lastPrice: number;
}

export function AssetInventory({ activePath }: AssetInventoryProps) {
  const [activeTab, setActiveTab] = useState('in');
  const [showInboundDialog, setShowInboundDialog] = useState(false);
  const [showOutboundDialog, setShowOutboundDialog] = useState(false);
  const [showCheckDialog, setShowCheckDialog] = useState(false);
  const [showLocationDialog, setShowLocationDialog] = useState(false);
  const [showLocationDeleteConfirm, setShowLocationDeleteConfirm] = useState(false);
  const [showWarehouseDeleteConfirm, setShowWarehouseDeleteConfirm] = useState(false);
  const [warehouseToDelete, setWarehouseToDelete] = useState<Warehouse | null>(null);
  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<any>(null);
  const [approvalAction, setApprovalAction] = useState<'approve' | 'reject'>('approve');
  const [approvalNotes, setApprovalNotes] = useState('');
  
  // 入库表单相关状态
  const [inboundType, setInboundType] = useState<'manual' | 'order'>('order');
  const [selectedOrderId, setSelectedOrderId] = useState<string>('');
  const [inboundFormData, setInboundFormData] = useState({
    warehouseId: 'wh-1',
    warehouseName: '1号仓库',
    supplierId: '',
    supplierName: '',
    inboundDate: new Date().toISOString().split('T')[0],
    notes: '',
  });
  const [inboundItems, setInboundItems] = useState<InboundFormItem[]>([]);

  // 出库表单相关状态
  const [outboundFormData, setOutboundFormData] = useState({
    type: '生产领用' as '生产领用' | '销售出库' | '调拨出库' | '其他出库',
    warehouseId: 'wh-1',
    warehouseName: '1号仓库',
    targetWarehouseId: '',
    targetWarehouseName: '',
    recipient: '',
    recipientType: '员工' as '员工' | '客户' | '其他',
    purpose: '',
    fieldId: '',
    fieldName: '',
    taskId: '',
    taskName: '',
    outboundDate: new Date().toISOString().split('T')[0],
    notes: '',
  });
  const [outboundItems, setOutboundItems] = useState<any[]>([]);
  const [selectedMaterialId, setSelectedMaterialId] = useState('');

  // 盘点表单相关状态
  const [checkFormData, setCheckFormData] = useState({
    taskName: '',
    warehouseId: 'wh-1',
    warehouseName: '1号仓库',
    checkType: '全盘' as '全盘' | '抽盘',
    planDate: new Date().toISOString().split('T')[0],
    checker: '当前用户',
    notes: '',
  });
  const [checkItems, setCheckItems] = useState<any[]>([]);
  const [showCheckItemDialog, setShowCheckItemDialog] = useState(false);
  const [showCheckInputDialog, setShowCheckInputDialog] = useState(false);
  const [selectedCheckTask, setSelectedCheckTask] = useState<StockCheckTask | null>(null);
  const [inputCheckItems, setInputCheckItems] = useState<StockCheckItem[]>([]);
  const [printTask, setPrintTask] = useState<StockCheckTask | null>(null);
  const [showCheckApprovalConfirm, setShowCheckApprovalConfirm] = useState(false);
  const [showCheckRejectConfirm, setShowCheckRejectConfirm] = useState(false);

  // 库存预警相关状态
  const [showWarningRuleDialog, setShowWarningRuleDialog] = useState(false);
  const [showWarningDetailDialog, setShowWarningDetailDialog] = useState(false);
  const [selectedWarning, setSelectedWarning] = useState<any>(null);
  const [warningFilter, setWarningFilter] = useState({
    level: 'all',
    type: 'all',
    handled: 'all',
  });

  // 预警通知设置状态
  const [warningNotificationSettings, setWarningNotificationSettings] = useState({
    systemMessage: true,
    sms: false,
    email: false,
  });

  // 预警通知对象列表和选中状态
  const [notificationTargets] = useState([
    { id: 'staff-1', name: '张三', role: '库管主管', type: 'warehouse', selected: true },
    { id: 'staff-2', name: '李四', role: '仓库管理员', type: 'warehouse', selected: true },
    { id: 'staff-3', name: '王五', role: '采购主管', type: 'purchase', selected: true },
    { id: 'staff-4', name: '赵六', role: '采购专员', type: 'purchase', selected: false },
  ]);
  const [selectedNotificationTargets, setSelectedNotificationTargets] = useState<string[]>([
    'staff-1', 'staff-2', 'staff-3'
  ]);

  // 库存明细相关状态
  const [detailSearchText, setDetailSearchText] = useState('');
  const [detailTypeFilter, setDetailTypeFilter] = useState('all');
  const [detailWarehouseFilter, setDetailWarehouseFilter] = useState('all');
  const [detailDateRange, setDetailDateRange] = useState({
    start: '',
    end: '',
  });
  const [selectedTransaction, setSelectedTransaction] = useState<any>(null);
  const [showTraceChainDialog, setShowTraceChainDialog] = useState(false);
  const [traceChainData, setTraceChainData] = useState<any[]>([]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/inventory/in')) {
        setActiveTab('in');
      } else if (activePath.includes('/inventory/out')) {
        setActiveTab('out');
      } else if (activePath.includes('/inventory/check')) {
        setActiveTab('check');
      } else if (activePath.includes('/inventory/warning')) {
        setActiveTab('warning');
      } else if (activePath.includes('/inventory/detail')) {
        setActiveTab('detail');
      } else if (activePath.includes('/inventory/location')) {
        setActiveTab('location');
      } else if (activePath.includes('/inventory/suggest')) {
        setActiveTab('suggest');
      }
    }
  }, [activePath]);

  // 模拟入库记录
  const [inboundRecords, setInboundRecords] = useState<InboundRecord[]>([
    {
      id: 'in-1',
      recordNo: 'IN-2024-001',
      orderNo: 'PO-2024-001',
      type: '采购入库',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      supplierId: 'sup-1',
      supplierName: '北方农资有限公司',
      items: [
        {
          id: 'item-1',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          quantity: 50,
          unit: '袋',
          unitPrice: 280,
          amount: 14000,
          batchNo: 'BATCH-2024-001',
          productionDate: '2023-10-01',
          expiryDate: '2024-12-31',
          locationId: 'loc-1',
          locationCode: 'A区-01-02',
        },
      ],
      totalAmount: 14000,
      operator: '王五',
      inboundDate: '2024-03-15',
      batchNo: 'BATCH-2024-001',
      status: '已审核',
      notes: '第一批到货',
      rejectReason: undefined,
      createdAt: '2024-03-15 10:30',
    },
    {
      id: 'in-2',
      recordNo: 'IN-2024-002',
      orderNo: 'PO-2024-003',
      type: '采购入库',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      supplierId: 'sup-2',
      supplierName: '南方农药供应商',
      items: [
        {
          id: 'item-2',
          materialId: 'mat-2',
          materialName: '高效复合肥',
          spec: '50kg/袋',
          quantity: 100,
          unit: '袋',
          unitPrice: 180,
          amount: 18000,
          batchNo: 'BATCH-2024-002',
          productionDate: '2024-03-01',
          expiryDate: '2026-03-01',
          locationId: 'loc-2',
          locationCode: 'A区-02-03',
        },
        {
          id: 'item-3',
          materialId: 'mat-3',
          materialName: '有机农药',
          spec: '1L/瓶',
          quantity: 50,
          unit: '瓶',
          unitPrice: 85,
          amount: 4250,
          batchNo: 'BATCH-2024-003',
          productionDate: '2024-02-15',
          expiryDate: '2025-02-15',
          locationId: 'loc-3',
          locationCode: 'B区-01-01',
        },
      ],
      totalAmount: 22250,
      operator: '张三',
      inboundDate: '2024-03-20',
      batchNo: 'BATCH-2024-002',
      status: '待审核',
      notes: '春季肥料和农药采购',
      rejectReason: undefined,
      createdAt: '2024-03-20 14:25',
    },
    {
      id: 'in-3',
      recordNo: 'IN-2024-003',
      type: '其他入库',
      warehouseId: 'wh-2',
      warehouseName: '2号仓库',
      supplierId: 'sup-3',
      supplierName: '东部农机配件',
      items: [
        {
          id: 'item-4',
          materialId: 'mat-4',
          materialName: '滴灌管',
          spec: '100m/卷',
          quantity: 30,
          unit: '卷',
          unitPrice: 120,
          amount: 3600,
          batchNo: 'BATCH-2024-004',
          productionDate: '2024-03-10',
          expiryDate: '2029-03-10',
          locationId: 'loc-4',
          locationCode: 'C区-03-02',
        },
      ],
      totalAmount: 3600,
      operator: '李四',
      inboundDate: '2024-03-22',
      batchNo: 'BATCH-2024-004',
      status: '待审核',
      notes: '灌溉设备补充',
      rejectReason: undefined,
      createdAt: '2024-03-22 09:15',
    },
  ]);

  // 模拟出库记录
  const [outboundRecords, setOutboundRecords] = useState<OutboundRecord[]>([
    {
      id: 'out-1',
      recordNo: 'OUT-2024-001',
      type: '生产领用',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      recipient: '张三',
      recipientType: '员工',
      purpose: '春季播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      taskId: 'task-1',
      taskName: '水稻播种任务',
      items: [
        {
          id: 'item-1',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          quantity: 10,
          unit: '袋',
          batchNo: 'BATCH-2024-001',
          unitPrice: 280,
          amount: 2800,
          locationId: 'loc-1',
          locationCode: 'A区-01-02',
        },
      ],
      totalAmount: 2800,
      operator: '李四',
      outboundDate: '2024-03-18',
      status: '已审核',
      notes: '播种用种',
      rejectReason: undefined,
      createdAt: '2024-03-18 09:00',
    },
    {
      id: 'out-2',
      recordNo: 'OUT-2024-002',
      type: '生产领用',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      recipient: '王五',
      recipientType: '员工',
      purpose: '春季施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      taskId: 'task-2',
      taskName: '小麦追肥任务',
      items: [
        {
          id: 'item-2',
          materialId: 'mat-2',
          materialName: '高效复合肥',
          spec: '50kg/袋',
          quantity: 20,
          unit: '袋',
          batchNo: 'BATCH-2024-002',
          unitPrice: 180,
          amount: 3600,
          locationId: 'loc-2',
          locationCode: 'A区-02-03',
        },
      ],
      totalAmount: 3600,
      operator: '张三',
      outboundDate: '2024-03-25',
      status: '待审核',
      notes: '追肥用肥',
      rejectReason: undefined,
      createdAt: '2024-03-25 14:30',
    },
  ]);

  // 模拟盘点任务
  const [checkTasks, setCheckTasks] = useState<StockCheckTask[]>([
    {
      id: 'check-1',
      taskNo: 'CHECK-2024-001',
      taskName: '2024年3月月度盘点',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      status: '待审批',
      checkType: '全盘',
      planDate: '2024-03-31',
      actualDate: '2024-03-31',
      items: [
        {
          id: 'item-1',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          unit: '袋',
          locationCode: 'A区-01-02',
          batchNo: 'BATCH-2024-001',
          bookQuantity: 40,
          actualQuantity: 38,
          difference: -2,
          status: '盘亏',
          notes: '发现2袋破损',
        },
        {
          id: 'item-2',
          materialId: 'mat-2',
          materialName: '复合肥',
          spec: '50kg/袋',
          unit: '袋',
          locationCode: 'B区-02-01',
          batchNo: 'BATCH-2024-002',
          bookQuantity: 450,
          actualQuantity: 452,
          difference: 2,
          status: '盘盈',
        },
      ],
      profit: 2,
      loss: 2,
      checker: '王五',
      createdAt: '2024-03-31',
    },
  ]);

  // 模拟库存预警
  const [warnings, setWarnings] = useState<InventoryWarning[]>([
    {
      id: 'warn-1',
      materialId: 'mat-1',
      materialName: '优质水稻种子',
      materialType: '种子',
      currentStock: 85,
      safeStock: 100,
      unit: '袋',
      warehouseName: '1号仓库',
      warningType: '库存不足',
      warningLevel: '中',
      createdAt: '2024-03-20',
      handled: false,
    },
    {
      id: 'warn-2',
      materialId: 'mat-3',
      materialName: '吡虫啉可湿性粉剂',
      materialType: '农药',
      currentStock: 120,
      safeStock: 50,
      unit: '瓶',
      warehouseName: '1号仓库',
      warningType: '临期预警',
      warningLevel: '高',
      expiryDate: '2024-05-31',
      daysLeft: 45,
      createdAt: '2024-03-18',
      handled: false,
    },
  ]);

  // 模拟库存明细
  const [transactions, setTransactions] = useState<StockTransaction[]>([
    {
      id: 'trans-1',
      transactionNo: 'TRANS-2024-001',
      type: '入库',
      materialId: 'mat-1',
      materialName: '优质水稻种子',
      quantity: 50,
      unit: '袋',
      batchNo: 'BATCH-2024-001',
      warehouseName: '1号仓库',
      locationCode: 'A区-01-02',
      operator: '王五',
      relatedNo: 'IN-2024-001',
      beforeStock: 85,
      afterStock: 135,
      createdAt: '2024-03-15 10:30',
      notes: '采购入库',
    },
    {
      id: 'trans-2',
      transactionNo: 'TRANS-2024-002',
      type: '出库',
      materialId: 'mat-1',
      materialName: '优质水稻种子',
      quantity: 10,
      unit: '袋',
      batchNo: 'BATCH-2024-001',
      warehouseName: '1号仓库',
      locationCode: 'A区-01-02',
      operator: '李四',
      relatedNo: 'OUT-2024-001',
      beforeStock: 135,
      afterStock: 125,
      createdAt: '2024-03-18 09:00',
      notes: '生产领用 - 东区1号地播种',
    },
  ]);

  // 模拟库位
  const [locations, setLocations] = useState<WarehouseLocation[]>([
    {
      id: 'loc-1',
      code: 'LOC-001',
      name: 'A区种子存储位',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      status: '使用中',
      materials: [
        {
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          quantity: 40,
          unit: '袋',
        },
      ],
    },
    {
      id: 'loc-2',
      code: 'LOC-002',
      name: 'A区肥料存储位',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      status: '使用中',
      materials: [
        {
          materialId: 'mat-2',
          materialName: '复合肥',
          quantity: 80,
          unit: '袋',
        },
      ],
    },
    {
      id: 'loc-3',
      code: 'LOC-003',
      name: 'B区农药存储位',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      status: '使用中',
      materials: [
        {
          materialId: 'mat-3',
          materialName: '有机农药',
          quantity: 50,
          unit: '瓶',
        },
      ],
    },
    {
      id: 'loc-4',
      code: 'LOC-004',
      name: 'B区预留库位',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      status: '空闲',
      materials: [],
      notes: '新建库位',
    },
    {
      id: 'loc-5',
      code: 'LOC-005',
      name: '机油存储位',
      warehouseId: 'wh-2',
      warehouseName: '2号仓库',
      status: '使用中',
      materials: [
        {
          materialId: 'mat-4',
          materialName: '机油',
          quantity: 20,
          unit: '桶',
        },
        {
          materialId: 'mat-5',
          materialName: '尿素',
          quantity: 100,
          unit: '袋',
        },
      ],
    },
    {
      id: 'loc-6',
      code: 'C区-03-02',
      warehouseId: 'wh-2',
      warehouseName: '2号仓库',
      zone: 'C区',
      row: '03',
      shelf: '02',
      level: '高层',
      capacity: 100,
      usedCapacity: 0,
      status: '维护中',
      materials: [],
      notes: '货架维修中',
    },
  ]);

  // 仓库管理相关状态
  const [selectedWarehouse, setSelectedWarehouse] = useState<string | null>('wh-1');
  const [showWarehouseDialog, setShowWarehouseDialog] = useState(false);
  const [editingWarehouse, setEditingWarehouse] = useState<Warehouse | null>(null);
  const [warehouseFormData, setWarehouseFormData] = useState({
    name: '',
    code: '',
    type: '综合仓库',
    address: '',
    area: 0,
    manager: '',
    contact: '',
    notes: '',
  });
  const [expandedWarehouses, setExpandedWarehouses] = useState<Set<string>>(new Set(['wh-1']));

  // 库位管理相关状态
  const [locationSearchText, setLocationSearchText] = useState('');
  const [locationStatusFilter, setLocationStatusFilter] = useState('all');
  const [showLocationDetailDialog, setShowLocationDetailDialog] = useState(false);
  const [showLocationQRCodeDialog, setShowLocationQRCodeDialog] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState<WarehouseLocation | null>(null);
  const [qrCodeLocation, setQrCodeLocation] = useState<WarehouseLocation | null>(null);
  const [locationToDelete, setLocationToDelete] = useState<WarehouseLocation | null>(null);
  const [locationFormData, setLocationFormData] = useState({
    warehouseId: 'wh-1',
    warehouseName: '1号仓库',
    name: '', // 位置名称
    notes: '',
  });

  // 采购建议相关状态
  const [forecastDays, setForecastDays] = useState(30);
  const [showSuggestionDetailDialog, setShowSuggestionDetailDialog] = useState(false);
  const [selectedSuggestion, setSelectedSuggestion] = useState<PurchaseSuggestion | null>(null);
  const [isCalculating, setIsCalculating] = useState(false);
  const [showAddPlanDialog, setShowAddPlanDialog] = useState(false);
  const [selectedSuggestions, setSelectedSuggestions] = useState<PurchaseSuggestion[]>([]);
  const [planFormData, setPlanFormData] = useState({
    planNo: '',
    supplierId: '',
    expectedDate: new Date().toISOString().split('T')[0],
    notes: '',
  });

  // 模拟农资档案（用于库存预警判断）
  const materials = [
    { id: 'mat-1', name: '优质水稻种子', type: '种子', safeStock: 100 },
    { id: 'mat-2', name: '复合肥', type: '化肥', safeStock: 200 },
    { id: 'mat-3', name: '吡虫啉可湿性粉剂', type: '农药', safeStock: 50 },
    { id: 'mat-4', name: '机油', type: '维护用品', safeStock: 30 },
    { id: 'mat-5', name: '尿素', type: '化肥', safeStock: 150 },
    { id: 'mat-6', name: '草甘膦除草剂', type: '农药', safeStock: 80 },
    { id: 'mat-7', name: '有机肥', type: '化肥', safeStock: 120 },
    { id: 'mat-8', name: '磷酸二铵', type: '化肥', safeStock: 180 },
  ];

  // 模拟可用于入库的采购订单（已审批通过且未完成）
  const [availablePurchaseOrders, setAvailablePurchaseOrders] = useState<PurchaseOrder[]>([
    {
      id: 'order-1',
      orderNo: 'PO-2024-001',
      supplierId: 'sup-1',
      supplierName: '北方农资有限公司',
      status: '部分到货',
      approvalStatus: '已通过',
      totalAmount: 32200,
      items: [
        {
          id: 'oi-1',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          quantity: 115,
          receivedQuantity: 50,
          unit: '袋',
          unitPrice: 280,
          amount: 32200,
        },
      ],
      expectedDeliveryDate: '2024-03-20',
      createdAt: '2024-03-05',
    },
    {
      id: 'order-2',
      orderNo: 'PO-2024-002',
      supplierId: 'sup-2',
      supplierName: '绿野化肥集团',
      status: '已下单',
      approvalStatus: '已通过',
      totalAmount: 45000,
      items: [
        {
          id: 'oi-2',
          materialId: 'mat-2',
          materialName: '复合肥',
          spec: '50kg/袋',
          quantity: 250,
          receivedQuantity: 0,
          unit: '袋',
          unitPrice: 180,
          amount: 45000,
        },
      ],
      expectedDeliveryDate: '2024-03-25',
      createdAt: '2024-03-12',
    },
    {
      id: 'order-4',
      orderNo: 'PO-2024-004',
      supplierId: 'sup-3',
      supplierName: '现代农药科技',
      status: '已下单',
      approvalStatus: '已通过',
      totalAmount: 10800,
      items: [
        {
          id: 'oi-4',
          materialId: 'mat-3',
          materialName: '吡虫啉可湿性粉剂',
          spec: '500ml/瓶',
          quantity: 240,
          receivedQuantity: 0,
          unit: '瓶',
          unitPrice: 45,
          amount: 10800,
        },
      ],
      expectedDeliveryDate: '2024-03-28',
      createdAt: '2024-03-15',
    },
  ]);

  // 模拟仓库列表
  const [warehouses, setWarehouses] = useState<Warehouse[]>([
    { 
      id: 'wh-1', 
      name: '1号仓库', 
      code: 'WH-001',
      type: '综合仓库',
      address: '农场东区',
      area: 500,
      manager: '张三',
      contact: '13800001111',
      status: '正常',
      locationCount: 12,
      usedLocationCount: 8,
      createdAt: '2024-01-01',
    },
    { 
      id: 'wh-2', 
      name: '2号仓库', 
      code: 'WH-002',
      type: '农药专用仓库',
      address: '农场西区',
      area: 300,
      manager: '李四',
      contact: '13800002222',
      status: '正常',
      locationCount: 8,
      usedLocationCount: 3,
      createdAt: '2024-01-15',
    },
    { 
      id: 'wh-3', 
      name: '3号仓库', 
      code: 'WH-003',
      type: '机具仓库',
      address: '农场南区',
      area: 800,
      manager: '王五',
      contact: '13800003333',
      status: '正常',
      locationCount: 6,
      usedLocationCount: 2,
      createdAt: '2024-02-01',
    },
  ]);

  // 模拟可用库存批次（用于出库先进先出）
  const [availableStockBatches] = useState([
    {
      materialId: 'mat-1',
      materialName: '优质水稻种子',
      spec: '25kg/袋',
      unit: '袋',
      batchNo: 'BATCH-2024-001',
      quantity: 40,
      unitPrice: 280,
      productionDate: '2023-10-01',
      expiryDate: '2024-12-31',
      locationId: 'loc-1',
      locationCode: 'A区-01-02',
      warehouseId: 'wh-1',
    },
    {
      materialId: 'mat-2',
      materialName: '高效复合肥',
      spec: '50kg/袋',
      unit: '袋',
      batchNo: 'BATCH-2024-002',
      quantity: 80,
      unitPrice: 180,
      productionDate: '2024-03-01',
      expiryDate: '2026-03-01',
      locationId: 'loc-2',
      locationCode: 'A区-02-03',
      warehouseId: 'wh-1',
    },
    {
      materialId: 'mat-2',
      materialName: '高效复合肥',
      spec: '50kg/袋',
      unit: '袋',
      batchNo: 'BATCH-2023-015',
      quantity: 30,
      unitPrice: 175,
      productionDate: '2023-12-15',
      expiryDate: '2025-12-15',
      locationId: 'loc-3',
      locationCode: 'B区-01-01',
      warehouseId: 'wh-1',
    },
    {
      materialId: 'mat-3',
      materialName: '有机农药',
      spec: '1L/瓶',
      unit: '瓶',
      batchNo: 'BATCH-2024-003',
      quantity: 50,
      unitPrice: 85,
      productionDate: '2024-02-15',
      expiryDate: '2025-02-15',
      locationId: 'loc-3',
      locationCode: 'B区-01-01',
      warehouseId: 'wh-1',
    },
  ]);

  // 模拟地块列表
  const fieldList = [
    { id: 'field-1', name: '东区1号地', area: 50, crop: '水稻' },
    { id: 'field-2', name: '西区2号地', area: 45, crop: '小麦' },
    { id: 'field-3', name: '南区3号地', area: 60, crop: '玉米' },
    { id: 'field-4', name: '北区4号地', area: 38, crop: '大豆' },
  ];

  // 模拟任务列表
  const taskList = [
    { id: 'task-1', name: '水稻播种任务', fieldName: '东区1号地', status: '进行中' },
    { id: 'task-2', name: '小麦追肥任务', fieldName: '西区2号地', status: '进行中' },
    { id: 'task-3', name: '玉米病虫害防治', fieldName: '南区3号地', status: '计划中' },
    { id: 'task-4', name: '大豆中耕除草', fieldName: '北区4号地', status: '计划中' },
  ];

  // 模拟员工列表
  const employeeList = [
    { id: 'emp-1', name: '张三', department: '种植部', position: '技术员' },
    { id: 'emp-2', name: '李四', department: '种植部', position: '主管' },
    { id: 'emp-3', name: '王五', department: '农机部', position: '机手' },
    { id: 'emp-4', name: '赵六', department: '仓储部', position: '库管' },
  ];

  // 模拟客户列表
  const customerList = [
    { id: 'cust-1', name: '绿色农产品公司', type: '批发商', contact: '13800001111' },
    { id: 'cust-2', name: '有机蔬菜基地', type: '种植户', contact: '13800002222' },
    { id: 'cust-3', name: '农贸市场', type: '零售商', contact: '13800003333' },
  ];

  // 模拟库位列表
  const availableLocations = [
    { id: 'loc-1', code: 'A区-01-02', warehouse: 'wh-1', zone: 'A区' },
    { id: 'loc-2', code: 'A区-01-03', warehouse: 'wh-1', zone: 'A区' },
    { id: 'loc-3', code: 'B区-02-01', warehouse: 'wh-1', zone: 'B区' },
    { id: 'loc-4', code: 'B区-02-02', warehouse: 'wh-1', zone: 'B区' },
    { id: 'loc-5', code: 'C区-03-01', warehouse: 'wh-2', zone: 'C区' },
  ];

  // 模拟可用农资列表（用于手动创建）
  const availableMaterials: AvailableMaterial[] = [
    { id: 'mat-1', name: '优质水稻种子', type: '种子', spec: '25kg/袋', unit: '袋', lastPrice: 280 },
    { id: 'mat-2', name: '复合肥', type: '化肥', spec: '50kg/袋', unit: '袋', lastPrice: 180 },
    { id: 'mat-3', name: '吡虫啉可湿性粉剂', type: '农药', spec: '500ml/瓶', unit: '瓶', lastPrice: 45 },
    { id: 'mat-4', name: '机油', type: '维护用品', spec: '4L/桶', unit: '桶', lastPrice: 350 },
    { id: 'mat-5', name: '尿素', type: '化肥', spec: '50kg/袋', unit: '袋', lastPrice: 120 },
    { id: 'mat-6', name: '草甘膦除草剂', type: '农药', spec: '1L/瓶', unit: '瓶', lastPrice: 35 },
    { id: 'mat-7', name: '有机肥', type: '化肥', spec: '40kg/袋', unit: '袋', lastPrice: 80 },
    { id: 'mat-8', name: '磷酸二铵', type: '化肥', spec: '50kg/袋', unit: '袋', lastPrice: 200 },
  ];

  // 模拟供应商列表（用于手动创建）
  const suppliers = [
    { id: 'sup-1', name: '北方农资有限公司' },
    { id: 'sup-2', name: '绿野化肥集团' },
    { id: 'sup-3', name: '现代农药科技' },
    { id: 'sup-4', name: '金田机械设备' },
    { id: 'sup-5', name: '丰收农资批发' },
  ];

  // 模拟采购建议
  const [suggestions, setSuggestions] = useState<PurchaseSuggestion[]>([
    {
      id: 'sug-1',
      materialId: 'mat-1',
      materialName: '优质水稻种子',
      materialType: '种子',
      currentStock: 85,
      safeStock: 100,
      avgDailyConsumption: 5,
      forecastDays: 30,
      forecastConsumption: 150,
      suggestedQuantity: 165,
      unit: '袋',
      lastPurchasePrice: 280,
      estimatedAmount: 46200,
      priority: '高',
      reason: '当前库存低于安全库存，且未来30天预计消耗150袋',
    },
    {
      id: 'sug-2',
      materialId: 'mat-4',
      materialName: '机油',
      materialType: '维护用品',
      currentStock: 20,
      safeStock: 30,
      avgDailyConsumption: 2,
      forecastDays: 30,
      forecastConsumption: 60,
      suggestedQuantity: 70,
      unit: '桶',
      lastPurchasePrice: 350,
      estimatedAmount: 24500,
      priority: '中',
      reason: '库存不足且农机保养季节需求增加',
    },
  ]);

  // 选择采购订单时，自动填充信息
  const handleSelectOrder = (orderId: string) => {
    setSelectedOrderId(orderId);
    
    if (!orderId) {
      setInboundFormData({
        ...inboundFormData,
        supplierId: '',
        supplierName: '',
      });
      setInboundItems([]);
      return;
    }
    
    const order = availablePurchaseOrders.find(o => o.id === orderId);
    if (!order) return;
    
    // 填充供应商信息
    setInboundFormData({
      ...inboundFormData,
      supplierId: order.supplierId,
      supplierName: order.supplierName,
    });
    
    // 填充物料明细
    const items: InboundFormItem[] = order.items.map(item => ({
      orderItemId: item.id,
      materialId: item.materialId,
      materialName: item.materialName,
      spec: item.spec,
      unit: item.unit,
      unitPrice: item.unitPrice,
      orderQuantity: item.quantity,
      receivedQuantity: item.receivedQuantity,
      remainingQuantity: item.quantity - item.receivedQuantity,
      inboundQuantity: item.quantity - item.receivedQuantity, // 默认全部入库
      batchNo: `BATCH-${new Date().getFullYear()}-${String(inboundRecords.length + 1).padStart(3, '0')}`,
      productionDate: new Date().toISOString().split('T')[0],
      expiryDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      locationId: '',
      locationCode: '',
    }));
    
    setInboundItems(items);
  };

  // 手动添加物料
  const handleAddManualMaterial = (materialId: string) => {
    const material = availableMaterials.find(m => m.id === materialId);
    if (!material) return;
    
    // 检查是否已添加
    if (inboundItems.some(item => item.materialId === materialId)) {
      toast.error('该物料已添加');
      return;
    }
    
    const newItem: InboundFormItem = {
      orderItemId: '',
      materialId: material.id,
      materialName: material.name,
      spec: material.spec,
      unit: material.unit,
      unitPrice: material.lastPrice,
      orderQuantity: 0,
      receivedQuantity: 0,
      remainingQuantity: 999999, // 手动创建没有限制
      inboundQuantity: 1,
      batchNo: `BATCH-${new Date().getFullYear()}-${String(inboundRecords.length + 1).padStart(3, '0')}`,
      productionDate: new Date().toISOString().split('T')[0],
      expiryDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      locationId: '',
      locationCode: '',
    };
    
    setInboundItems([...inboundItems, newItem]);
  };

  // 删除物料项
  const handleRemoveMaterialItem = (index: number) => {
    const newItems = inboundItems.filter((_, i) => i !== index);
    setInboundItems(newItems);
  };

  // 更新入库物料项
  const handleUpdateInboundItem = (index: number, field: keyof InboundFormItem, value: any) => {
    const newItems = [...inboundItems];
    newItems[index] = { ...newItems[index], [field]: value };
    
    // 如果修改了库位ID，同步更新库位代码
    if (field === 'locationId') {
      const location = availableLocations.find(l => l.id === value);
      newItems[index].locationCode = location?.code || '';
    }
    
    setInboundItems(newItems);
  };

  // 提交入库
  const handleSubmitInbound = () => {
    // 验证
    if (inboundType === 'order' && !selectedOrderId) {
      toast.error('请选择采购订单');
      return;
    }
    
    if (inboundItems.length === 0) {
      toast.error('请添加入库物料');
      return;
    }
    
    // 验证每个物料
    for (const item of inboundItems) {
      if (!item.inboundQuantity || item.inboundQuantity <= 0) {
        toast.error(`${item.materialName} 入库数量必须大于0`);
        return;
      }
      
      // 仅在基于订单模式下检查剩余数量
      if (inboundType === 'order' && item.inboundQuantity > item.remainingQuantity) {
        toast.error(`${item.materialName} 入库数量不能超过剩余数量 ${item.remainingQuantity}`);
        return;
      }
      
      if (!item.batchNo) {
        toast.error(`${item.materialName} 请填写批次号`);
        return;
      }
      
      if (!item.productionDate) {
        toast.error(`${item.materialName} 请填写生产日期`);
        return;
      }
      
      if (!item.locationId) {
        toast.error(`${item.materialName} 请选择库位`);
        return;
      }
      
      if (!item.unitPrice || item.unitPrice <= 0) {
        toast.error(`${item.materialName} 单价必须大于0`);
        return;
      }
    }
    
    // 生成入库记录
    const newRecord: InboundRecord = {
      id: `in-${inboundRecords.length + 1}`,
      recordNo: `IN-2024-${String(inboundRecords.length + 1).padStart(3, '0')}`,
      orderNo: inboundType === 'order' ? availablePurchaseOrders.find(o => o.id === selectedOrderId)?.orderNo : undefined,
      type: inboundType === 'order' ? '采购入库' : '其他入库',
      warehouseId: inboundFormData.warehouseId,
      warehouseName: inboundFormData.warehouseName,
      supplierId: inboundFormData.supplierId,
      supplierName: inboundFormData.supplierName || '未指定',
      items: inboundItems.map(item => ({
        id: `item-${Date.now()}-${Math.random()}`,
        materialId: item.materialId,
        materialName: item.materialName,
        spec: item.spec,
        quantity: item.inboundQuantity,
        unit: item.unit,
        unitPrice: item.unitPrice,
        amount: item.inboundQuantity * item.unitPrice,
        batchNo: item.batchNo,
        productionDate: item.productionDate,
        expiryDate: item.expiryDate,
        locationId: item.locationId,
        locationCode: item.locationCode,
      })),
      totalAmount: inboundItems.reduce((sum, item) => sum + (item.inboundQuantity * item.unitPrice), 0),
      operator: '当前用户',
      inboundDate: inboundFormData.inboundDate,
      batchNo: inboundItems[0]?.batchNo || '',
      status: '已审核',
      notes: inboundFormData.notes,
      createdAt: new Date().toLocaleString('zh-CN'),
    };
    
    setInboundRecords([newRecord, ...inboundRecords]);
    
    // 如果是基于采购订单，更新订单的到货数量
    if (inboundType === 'order' && selectedOrderId) {
      setAvailablePurchaseOrders(prev => prev.map(order => {
        if (order.id === selectedOrderId) {
          const updatedItems = order.items.map(orderItem => {
            const inboundItem = inboundItems.find(i => i.orderItemId === orderItem.id);
            if (inboundItem) {
              const newReceivedQty = orderItem.receivedQuantity + inboundItem.inboundQuantity;
              return {
                ...orderItem,
                receivedQuantity: newReceivedQty,
              };
            }
            return orderItem;
          });
          
          // 判断订单状态
          const allReceived = updatedItems.every(item => item.receivedQuantity >= item.quantity);
          const partialReceived = updatedItems.some(item => item.receivedQuantity > 0);
          
          return {
            ...order,
            items: updatedItems,
            status: allReceived ? '已完成' : (partialReceived ? '部分到货' : '已下单'),
          };
        }
        return order;
      }));
    }
    
    toast.success('入库成功', {
      description: `入库单号: ${newRecord.recordNo}，共 ${newRecord.items.length} 项物料`,
    });
    
    // 重置并关闭对话框
    setShowInboundDialog(false);
    setInboundType('order');
    setSelectedOrderId('');
    setInboundFormData({
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      supplierId: '',
      supplierName: '',
      inboundDate: new Date().toISOString().split('T')[0],
      notes: '',
    });
    setInboundItems([]);
  };

  // 打开审批对话框
  const handleOpenApproval = (record: InboundRecord, action: 'approve' | 'reject') => {
    setSelectedRecord(record);
    setApprovalAction(action);
    setApprovalNotes('');
    setShowApprovalDialog(true);
  };

  // 打开详情对话框
  const handleOpenDetail = (record: InboundRecord) => {
    setSelectedRecord(record);
    setShowDetailDialog(true);
  };

  // 提交审批（同时处理入库、出库和盘点）
  const handleSubmitApproval = () => {
    // 盘点审批
    if (selectedCheckTask) {
      handleSubmitCheckApproval();
      return;
    }

    if (!selectedRecord) return;

    // 判断是入库还是出库记录
    if (selectedRecord.recordNo?.startsWith('IN-')) {
      // 入库审批
      const updatedRecords = inboundRecords.map(record => {
        if (record.id === selectedRecord.id) {
          return {
            ...record,
            status: approvalAction === 'approve' ? '已审核' : '已驳回',
            rejectReason: approvalAction === 'reject' ? approvalNotes : undefined,
          };
        }
        return record;
      });

      setInboundRecords(updatedRecords);

      toast.success(
        approvalAction === 'approve' ? '审批通过' : '已驳回',
        {
          description: `入库单 ${selectedRecord.recordNo} ${approvalAction === 'approve' ? '已审核通过' : '已被驳回'}`,
        }
      );
    } else if (selectedRecord.recordNo?.startsWith('OUT-')) {
      // 出库审批
      handleSubmitOutboundApproval();
      return;
    }

    setShowApprovalDialog(false);
    setSelectedRecord(null);
    setApprovalNotes('');
  };

  // 出库相关函数
  // 添加出库物料
  const handleAddOutboundItem = () => {
    if (!selectedMaterialId) {
      toast.error('请选择物料');
      return;
    }

    // 查找该物料的可用批次（按生产日期排序，实现先进先出）
    const materialBatches = availableStockBatches
      .filter(batch => batch.materialId === selectedMaterialId && batch.quantity > 0)
      .sort((a, b) => new Date(a.productionDate).getTime() - new Date(b.productionDate).getTime());

    if (materialBatches.length === 0) {
      toast.error('该物料暂无可用库存');
      return;
    }

    // 使用最早批次
    const earliestBatch = materialBatches[0];

    // 检查是否已添加
    const existingItem = outboundItems.find(item => item.batchNo === earliestBatch.batchNo);
    if (existingItem) {
      toast.error('该批次已添加，请在列表中修改数量');
      return;
    }

    const newItem = {
      id: `temp-${Date.now()}`,
      materialId: earliestBatch.materialId,
      materialName: earliestBatch.materialName,
      spec: earliestBatch.spec,
      unit: earliestBatch.unit,
      batchNo: earliestBatch.batchNo,
      availableQuantity: earliestBatch.quantity,
      quantity: 1,
      unitPrice: earliestBatch.unitPrice,
      amount: earliestBatch.unitPrice,
      locationId: earliestBatch.locationId,
      locationCode: earliestBatch.locationCode,
      productionDate: earliestBatch.productionDate,
      expiryDate: earliestBatch.expiryDate,
    };

    setOutboundItems([...outboundItems, newItem]);
    setSelectedMaterialId('');
  };

  // 更新出库数量
  const handleUpdateOutboundQuantity = (itemId: string, quantity: number) => {
    setOutboundItems(outboundItems.map(item => {
      if (item.id === itemId) {
        const validQuantity = Math.max(1, Math.min(quantity, item.availableQuantity));
        return {
          ...item,
          quantity: validQuantity,
          amount: validQuantity * item.unitPrice,
        };
      }
      return item;
    }));
  };

  // 删除出库物料
  const handleRemoveOutboundItem = (itemId: string) => {
    setOutboundItems(outboundItems.filter(item => item.id !== itemId));
  };

  // 提交出库单
  const handleSubmitOutbound = () => {
    // 验证表单
    if (!outboundFormData.recipient) {
      toast.error('请填写领用人/客户');
      return;
    }

    if (!outboundFormData.purpose) {
      toast.error('请填写出库用途');
      return;
    }

    // 如果是调拨出库，必须选择目标仓库
    if (outboundFormData.type === '调拨出库' && !outboundFormData.targetWarehouseId) {
      toast.error('调拨出库必须选择入库仓库');
      return;
    }

    if (outboundItems.length === 0) {
      toast.error('请添加出库物料');
      return;
    }

    // 生成出库记录
    const newRecord: OutboundRecord = {
      id: `out-${outboundRecords.length + 1}`,
      recordNo: `OUT-2024-${String(outboundRecords.length + 1).padStart(3, '0')}`,
      type: outboundFormData.type,
      warehouseId: outboundFormData.warehouseId,
      warehouseName: outboundFormData.warehouseName,
      targetWarehouseId: outboundFormData.targetWarehouseId || undefined,
      targetWarehouseName: outboundFormData.targetWarehouseName || undefined,
      recipient: outboundFormData.recipient,
      recipientType: outboundFormData.recipientType,
      purpose: outboundFormData.purpose,
      fieldId: outboundFormData.fieldId || undefined,
      fieldName: outboundFormData.fieldName || undefined,
      taskId: outboundFormData.taskId || undefined,
      taskName: outboundFormData.taskName || undefined,
      items: outboundItems.map(item => ({
        id: `item-${Date.now()}-${Math.random()}`,
        materialId: item.materialId,
        materialName: item.materialName,
        spec: item.spec,
        quantity: item.quantity,
        unit: item.unit,
        batchNo: item.batchNo,
        unitPrice: item.unitPrice,
        amount: item.amount,
        locationId: item.locationId,
        locationCode: item.locationCode,
      })),
      totalAmount: outboundItems.reduce((sum, item) => sum + item.amount, 0),
      operator: '当前用户',
      outboundDate: outboundFormData.outboundDate,
      status: '待审核',
      notes: outboundFormData.notes,
      rejectReason: undefined,
      createdAt: new Date().toLocaleString('zh-CN'),
    };

    setOutboundRecords([newRecord, ...outboundRecords]);

    toast.success('出库单创建成功', {
      description: `出库单号: ${newRecord.recordNo}，待审核后自动核减库存`,
    });

    // 重置并关闭对话框
    setShowOutboundDialog(false);
    setOutboundFormData({
      type: '生产领用',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      targetWarehouseId: '',
      targetWarehouseName: '',
      recipient: '',
      recipientType: '员工',
      purpose: '',
      fieldId: '',
      fieldName: '',
      taskId: '',
      taskName: '',
      outboundDate: new Date().toISOString().split('T')[0],
      notes: '',
    });
    setOutboundItems([]);
    setSelectedMaterialId('');
  };

  // 出库审批
  const handleOpenOutboundApproval = (record: OutboundRecord, action: 'approve' | 'reject') => {
    setSelectedRecord(record);
    setApprovalAction(action);
    setApprovalNotes('');
    setShowApprovalDialog(true);
  };

  // 提交出库审批
  const handleSubmitOutboundApproval = () => {
    if (!selectedRecord) return;

    const updatedRecords = outboundRecords.map(record => {
      if (record.id === selectedRecord.id) {
        return {
          ...record,
          status: approvalAction === 'approve' ? '已审核' : '已驳回',
          rejectReason: approvalAction === 'reject' ? approvalNotes : undefined,
        };
      }
      return record;
    });

    setOutboundRecords(updatedRecords);

    // 如果审批通过，核减库存
    if (approvalAction === 'approve') {
      toast.success('审批通过，库存已核减', {
        description: `出库单 ${selectedRecord.recordNo} 已审核通过`,
      });
    } else {
      toast.success('已驳回', {
        description: `出库单 ${selectedRecord.recordNo} 已被驳回`,
      });
    }

    setShowApprovalDialog(false);
    setSelectedRecord(null);
    setApprovalNotes('');
  };

  // 打开出库详情
  const handleOpenOutboundDetail = (record: OutboundRecord) => {
    setSelectedRecord(record);
    setShowDetailDialog(true);
  };

  // 盘点相关函数
  // 创建盘点任务时，初始化盘点项
  const handleInitCheckItems = () => {
    // 根据仓库获取可用物料和库存信息
    const items = availableStockBatches
      .filter(batch => batch.warehouseId === checkFormData.warehouseId)
      .map(batch => ({
        id: `check-item-${Date.now()}-${Math.random()}`,
        materialId: batch.materialId,
        materialName: batch.materialName,
        spec: batch.spec,
        unit: batch.unit,
        locationCode: batch.locationCode,
        batchNo: batch.batchNo,
        bookQuantity: batch.quantity,
        actualQuantity: undefined, // 创建时不填写实盘数量，后续盘点时才录入
        difference: 0,
        status: '待盘点' as '待盘点' | '正常' | '盘盈' | '盘亏',
        selected: checkFormData.checkType === '全盘', // 全盘时全选，抽盘时默认不选
        notes: '',
      }));

    setCheckItems(items);
  };

  // 切换盘点物料选中状态
  const handleToggleCheckItem = (itemId: string) => {
    setCheckItems(checkItems.map(item => 
      item.id === itemId ? { ...item, selected: !item.selected } : item
    ));
  };

  // 全选/取消全选盘点物料
  const handleToggleAllCheckItems = (checked: boolean) => {
    setCheckItems(checkItems.map(item => ({ ...item, selected: checked })));
  };

  // 更新盘点物料实盘数量
  const handleUpdateCheckQuantity = (itemId: string, actualQuantity: number | undefined) => {
    setCheckItems(checkItems.map(item => {
      if (item.id === itemId) {
        const difference = actualQuantity !== undefined ? actualQuantity - item.bookQuantity : 0;
        return {
          ...item,
          actualQuantity,
          difference,
          status: actualQuantity === undefined ? '待盘点' : (difference > 0 ? '盘盈' : (difference < 0 ? '盘亏' : '正常')),
        };
      }
      return item;
    }));
  };

  // 提交盘点任务
  const handleSubmitCheck = () => {
    if (!checkFormData.taskName) {
      toast.error('请填写任务名称');
      return;
    }

    if (checkItems.length === 0) {
      toast.error('请初始化盘点物料');
      return;
    }

    // 获取选中的盘点物料（抽盘时只提交选中的，全盘时全部提交）
    const selectedItems = checkFormData.checkType === '抽盘' 
      ? checkItems.filter(item => item.selected)
      : checkItems;

    if (selectedItems.length === 0) {
      toast.error('请至少选择一个物料进行盘点');
      return;
    }

    // 创建时不计算盘盈盘亏数量，等待实盘录入
    const profit = 0;
    const loss = 0;

    // 创建盘点任务
    const newTask: StockCheckTask = {
      id: `check-${checkTasks.length + 1}`,
      taskNo: `CHECK-2024-${String(checkTasks.length + 1).padStart(3, '0')}`,
      taskName: checkFormData.taskName,
      warehouseId: checkFormData.warehouseId,
      warehouseName: checkFormData.warehouseName,
      status: '待盘点',
      checkType: checkFormData.checkType,
      planDate: checkFormData.planDate,
      actualDate: undefined, // 实际盘点日期在录入时记录
      items: selectedItems,
      profit,
      loss,
      checker: checkFormData.checker,
      notes: checkFormData.notes,
      createdAt: new Date().toISOString().split('T')[0],
    };

    setCheckTasks([newTask, ...checkTasks]);

    toast.success('盘点任务创建成功', {
      description: `任务编号: ${newTask.taskNo}，请进行实地盘点并录入实盘数量`,
    });

    // 重置并关闭对话框
    setShowCheckDialog(false);
    setCheckFormData({
      taskName: '',
      warehouseId: 'wh-1',
      warehouseName: '1号仓库',
      checkType: '全盘',
      planDate: new Date().toISOString().split('T')[0],
      checker: '当前用户',
      notes: '',
    });
    setCheckItems([]);
  };

  // 打开盘点录入对话框
  const handleOpenCheckInput = (task: StockCheckTask) => {
    setSelectedCheckTask(task);
    setInputCheckItems([...task.items]);
    setShowCheckInputDialog(true);
  };

  // 更新盘点录入数量
  const handleUpdateInputCheckQuantity = (itemId: string, actualQuantity: number | undefined) => {
    setInputCheckItems(inputCheckItems.map(item => {
      if (item.id === itemId) {
        const difference = actualQuantity !== undefined ? actualQuantity - item.bookQuantity : 0;
        return {
          ...item,
          actualQuantity,
          difference,
          status: actualQuantity === undefined ? '待盘点' : (difference > 0 ? '盘盈' : (difference < 0 ? '盘亏' : '正常')),
        };
      }
      return item;
    }));
  };

  // 提交盘点录入
  const handleSubmitCheckInput = () => {
    if (!selectedCheckTask) return;

    // 检查是否有未录入的实盘数量
    const uninputItems = inputCheckItems.filter(item => item.actualQuantity === undefined);
    if (uninputItems.length > 0) {
      toast.error(`还有 ${uninputItems.length} 个物料未录入实盘数量`);
      return;
    }

    // 计算盘盈盘亏数量
    const profit = inputCheckItems.filter(item => item.difference > 0).length;
    const loss = inputCheckItems.filter(item => item.difference < 0).length;

    // 更新盘点任务
    const updatedTasks = checkTasks.map(task => {
      if (task.id === selectedCheckTask.id) {
        return {
          ...task,
          items: inputCheckItems,
          profit,
          loss,
          status: '待审批' as '待盘点' | '待审批' | '已完成' | '已取消',
          actualDate: new Date().toISOString().split('T')[0],
        };
      }
      return task;
    });

    setCheckTasks(updatedTasks);

    toast.success('盘点录入完成', {
      description: `盘点任务 ${selectedCheckTask.taskNo} 已录入完成，待审批后调整库存`,
    });

    setShowCheckInputDialog(false);
    setSelectedCheckTask(null);
    setInputCheckItems([]);
  };

  // 盘点审批 - 从列表打开审批确认对话框
  const handleOpenCheckApproval = (task: StockCheckTask, action: 'approve' | 'reject') => {
    setSelectedCheckTask(task);
    setApprovalAction(action);
    setApprovalNotes('');
    
    // 打开对应的确认对话框
    if (action === 'approve') {
      setShowCheckApprovalConfirm(true);
    } else {
      setShowCheckRejectConfirm(true);
    }
  };

  // 打印盘点表
  const handlePrintCheckList = (task: StockCheckTask) => {
    setPrintTask(task);
    // 延迟打印，确保DOM更新完成
    setTimeout(() => {
      window.print();
      setPrintTask(null);
    }, 100);
  };

  // 提交盘点审批
  const handleSubmitCheckApproval = (action?: '通过' | '驳回') => {
    if (!selectedCheckTask) return;

    const finalAction = action || (approvalAction === 'approve' ? '通过' : '驳回');

    const updatedTasks = checkTasks.map(task => {
      if (task.id === selectedCheckTask.id) {
        return {
          ...task,
          status: finalAction === '通过' ? '已完成' : '待盘点',
          approver: finalAction === '通过' ? '当前用户' : undefined,
        };
      }
      return task;
    });

    setCheckTasks(updatedTasks);

    // 如果审批通过，调整账面库存
    if (finalAction === '通过') {
      toast.success('审批通过，库存已调整', {
        description: `盘点任务 ${selectedCheckTask.taskNo} 已完成，账面库存已更新`,
      });
    } else {
      toast.success('已驳回', {
        description: `盘点任务 ${selectedCheckTask.taskNo} 已被驳回，请重新盘点`,
      });
    }

    setShowApprovalDialog(false);
    setSelectedCheckTask(null);
    setApprovalNotes('');
  };

  // 库存预警相关函数
  // 自动检查库存并生成预警
  const checkStockAndGenerateWarnings = () => {
    const newWarnings: any[] = [];
    const today = new Date();

    availableStockBatches.forEach(batch => {
      // 获取物料的安全库存设置
      const material = materials.find(m => m.id === batch.materialId);
      if (!material) return;

      const safeStock = material.safeStock || 0;

      // 检查库存不足预警
      if (batch.quantity < safeStock) {
        const percentage = (batch.quantity / safeStock) * 100;
        const level = percentage < 30 ? '高' : (percentage < 60 ? '中' : '低');

        newWarnings.push({
          id: `warn-stock-${batch.batchNo || batch.id || Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
          materialId: batch.materialId,
          materialName: batch.materialName,
          materialType: material.type,
          warehouseId: batch.warehouseId,
          warehouseName: batch.warehouseName,
          warningType: '库存不足',
          warningLevel: level,
          currentStock: batch.quantity,
          safeStock: safeStock,
          unit: batch.unit,
          batchNo: batch.batchNo,
          locationCode: batch.locationCode,
          handled: false,
          notified: false,
          createdAt: new Date().toISOString().split('T')[0],
          message: `${batch.materialName} 当前库存 ${batch.quantity}${batch.unit}，已低于安全库存 ${safeStock}${batch.unit}`,
        });
      }

      // 检查临期预警（有效期前30天预警）
      if (batch.expiryDate) {
        const expiryDate = new Date(batch.expiryDate);
        const daysLeft = Math.floor((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));

        if (daysLeft >= 0 && daysLeft <= 30) {
          const level = daysLeft <= 7 ? '高' : (daysLeft <= 15 ? '中' : '低');

          newWarnings.push({
            id: `warn-expiry-${batch.batchNo || batch.id || Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
            materialId: batch.materialId,
            materialName: batch.materialName,
            materialType: material.type,
            warehouseId: batch.warehouseId,
            warehouseName: batch.warehouseName,
            warningType: '临期预警',
            warningLevel: level,
            currentStock: batch.quantity,
            safeStock: safeStock,
            unit: batch.unit,
            batchNo: batch.batchNo,
            locationCode: batch.locationCode,
            expiryDate: batch.expiryDate,
            daysLeft: daysLeft,
            handled: false,
            notified: false,
            createdAt: new Date().toISOString().split('T')[0],
            message: `${batch.materialName} (批次: ${batch.batchNo}) 将在 ${daysLeft} 天后过期`,
          });
        }
      }
    });

    // 添加新预警到列表（避免重复）
    const existingWarningIds = warnings.map(w => w.id);
    const uniqueNewWarnings = newWarnings.filter(w => !existingWarningIds.includes(w.id));

    if (uniqueNewWarnings.length > 0) {
      setWarnings([...uniqueNewWarnings, ...warnings]);
      toast.info('库存检查完成', {
        description: `发现 ${uniqueNewWarnings.length} 条新预警`,
      });
    } else {
      toast.success('库存检查完成', {
        description: '暂无新预警',
      });
    }
  };

  // 标记预警已处理 - 添加二次确认状态
  const [showWarningHandleConfirm, setShowWarningHandleConfirm] = useState(false);
  const [pendingHandleWarningId, setPendingHandleWarningId] = useState<string | null>(null);

  // 打开标记已处理确认对话框
  const handleMarkWarningHandled = (warningId: string) => {
    setPendingHandleWarningId(warningId);
    setShowWarningHandleConfirm(true);
  };

  // 确认标记已处理
  const confirmMarkWarningHandled = () => {
    if (!pendingHandleWarningId) return;

    const updatedWarnings = warnings.map(w => {
      if (w.id === pendingHandleWarningId) {
        return { ...w, handled: true, handledAt: new Date().toISOString().split('T')[0] };
      }
      return w;
    });

    setWarnings(updatedWarnings);

    toast.success('已标记为已处理', {
      description: '预警已处理，将不再显示在待处理列表中',
    });

    setShowWarningHandleConfirm(false);
    setPendingHandleWarningId(null);
  };

  // 批量处理预警
  const handleBatchHandleWarnings = (level?: string) => {
    const updatedWarnings = warnings.map(w => {
      if (!w.handled && (!level || w.warningLevel === level)) {
        return { ...w, handled: true, handledAt: new Date().toISOString().split('T')[0] };
      }
      return w;
    });

    const handledCount = updatedWarnings.filter(w => w.handled).length - warnings.filter(w => w.handled).length;

    setWarnings(updatedWarnings);

    toast.success('批量处理完成', {
      description: `已处理 ${handledCount} 条预警`,
    });
  };

  // 生成采购计划（从预警）
  const handleGeneratePurchasePlanFromWarning = (warning: any) => {
    // 计算建议采购数量
    const suggestedQuantity = warning.safeStock * 1.5 - warning.currentStock;

    toast.success('已生成采购计划建议', {
      description: `建议采购 ${suggestedQuantity.toFixed(0)} ${warning.unit} ${warning.materialName}`,
    });

    // 标记预警已处理
    handleMarkWarningHandled(warning.id);
  };

  // 发送预警通知
  const handleSendWarningNotification = (warning: any) => {
    const updatedWarnings = warnings.map(w => {
      if (w.id === warning.id) {
        return { ...w, notified: true, notifiedAt: new Date().toISOString() };
      }
      return w;
    });

    setWarnings(updatedWarnings);

    toast.success('预警通知已发送', {
      description: '已通过短信、邮件、系统消息发送预警通知',
    });
  };

  // 批量发送预警通知
  const handleBatchSendNotifications = () => {
    const unnotifiedWarnings = warnings.filter(w => !w.notified && !w.handled);
    
    const updatedWarnings = warnings.map(w => {
      if (!w.notified && !w.handled) {
        return { ...w, notified: true, notifiedAt: new Date().toISOString() };
      }
      return w;
    });

    setWarnings(updatedWarnings);

    toast.success('批量通知已发送', {
      description: `已向库管和采购人员发送 ${unnotifiedWarnings.length} 条预警通知`,
    });
  };

  // 库存明细相关函数
  // 添加库存变动记录
  const addStockTransaction = (transaction: {
    type: '入库' | '出库' | '调拨' | '盘盈' | '盘亏';
    materialId: string;
    materialName: string;
    quantity: number;
    unit: string;
    batchNo: string;
    warehouseId: string;
    warehouseName: string;
    locationCode?: string;
    beforeStock: number;
    afterStock: number;
    operator: string;
    relatedNo?: string;
    notes?: string;
  }) => {
    const newTransaction = {
      id: `trans-${Date.now()}-${Math.random()}`,
      transactionNo: `TRANS${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${String(transactions.length + 1).padStart(4, '0')}`,
      ...transaction,
      createdAt: new Date().toISOString(),
      createdDate: new Date().toISOString().split('T')[0],
      createdTime: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
    };

    setTransactions([newTransaction, ...transactions]);
    return newTransaction;
  };

  // 生成追溯链
  const generateTraceChain = (batchNo: string) => {
    // 查找该批次的所有变动记录
    const batchTransactions = transactions.filter(t => t.batchNo === batchNo);
    
    // 按时间排序
    const sortedTransactions = batchTransactions.sort((a, b) => 
      new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
    );

    setTraceChainData(sortedTransactions);
    setShowTraceChainDialog(true);
  };

  // 导出库存明细
  const handleExportDetail = () => {
    const filteredTransactions = getFilteredTransactions();
    
    toast.success('导出成功', {
      description: `已导出 ${filteredTransactions.length} 条库存变动记录`,
    });
  };

  // 打印库存明细
  const handlePrintDetail = () => {
    const filteredTransactions = getFilteredTransactions();
    
    toast.success('打印预览', {
      description: `共 ${filteredTransactions.length} 条记录`,
    });
  };

  // 获取筛选后的交易记录
  const getFilteredTransactions = () => {
    return transactions.filter(trans => {
      // 搜索文本筛选
      const searchMatch = !detailSearchText || 
        trans.materialName.toLowerCase().includes(detailSearchText.toLowerCase()) ||
        trans.batchNo.toLowerCase().includes(detailSearchText.toLowerCase()) ||
        trans.transactionNo.toLowerCase().includes(detailSearchText.toLowerCase());

      // 类型筛选
      const typeMatch = detailTypeFilter === 'all' || trans.type === detailTypeFilter;

      // 仓库筛选
      const warehouseMatch = detailWarehouseFilter === 'all' || trans.warehouseId === detailWarehouseFilter;

      // 日期范围筛选
      const dateMatch = (!detailDateRange.start || trans.createdDate >= detailDateRange.start) &&
        (!detailDateRange.end || trans.createdDate <= detailDateRange.end);

      return searchMatch && typeMatch && warehouseMatch && dateMatch;
    });
  };

  // 重置筛选条件
  const handleResetDetailFilters = () => {
    setDetailSearchText('');
    setDetailTypeFilter('all');
    setDetailWarehouseFilter('all');
    setDetailDateRange({ start: '', end: '' });
    
    toast.success('筛选条件已重置');
  };

  // 统计变动数据
  const getTransactionStats = () => {
    const filtered = getFilteredTransactions();
    
    return {
      total: filtered.length,
      inbound: filtered.filter(t => t.type === '入库').length,
      outbound: filtered.filter(t => t.type === '出库').length,
      transfer: filtered.filter(t => t.type === '调拨').length,
      profit: filtered.filter(t => t.type === '盘盈').length,
      loss: filtered.filter(t => t.type === '盘亏').length,
      totalInQuantity: filtered.filter(t => t.type === '入库' || t.type === '盘盈').reduce((sum, t) => sum + t.quantity, 0),
      totalOutQuantity: filtered.filter(t => t.type === '出库' || t.type === '盘亏').reduce((sum, t) => sum + t.quantity, 0),
    };
  };

  // 库位管理相关函数
  // 库位搜索和筛选
  const getFilteredLocations = () => {
    return locations.filter(location => {
      const searchMatch = !locationSearchText || 
        location.code.toLowerCase().includes(locationSearchText.toLowerCase()) ||
        location.name.toLowerCase().includes(locationSearchText.toLowerCase()) ||
        location.warehouseName.toLowerCase().includes(locationSearchText.toLowerCase()) ||
        location.materials.some(m => m.materialName.toLowerCase().includes(locationSearchText.toLowerCase()));

      const statusMatch = locationStatusFilter === 'all' || location.status === locationStatusFilter;

      // 只显示选中仓库的库位
      const warehouseMatch = !selectedWarehouse || location.warehouseId === selectedWarehouse;

      return searchMatch && statusMatch && warehouseMatch;
    });
  };

  // 打开库位详情
  const handleOpenLocationDetail = (location: WarehouseLocation) => {
    setSelectedLocation(location);
    setShowLocationDetailDialog(true);
  };

  // 查看库位二维码
  const handleViewLocationQRCode = (location: WarehouseLocation) => {
    setQrCodeLocation(location);
    setShowLocationQRCodeDialog(true);
  };

  // 打开库位编辑
  const handleOpenLocationEdit = (location: WarehouseLocation) => {
    setSelectedLocation(location);
    setLocationFormData({
      warehouseId: location.warehouseId,
      warehouseName: location.warehouseName,
      name: location.name,
      notes: location.notes || '',
    });
    setShowLocationDialog(true);
  };

  // 提交库位表单
  const handleSubmitLocation = () => {
    if (!locationFormData.name || locationFormData.name.trim() === '') {
      toast.error('请填写位置名称');
      return;
    }

    if (!locationFormData.warehouseId) {
      toast.error('请选择所属仓库');
      return;
    }

    // 生成库位编码（简单递增）
    const warehouseLocations = locations.filter(l => l.warehouseId === locationFormData.warehouseId);
    const maxCode = warehouseLocations.length > 0 
      ? Math.max(...warehouseLocations.map(l => parseInt(l.code.split('-')[1]) || 0))
      : 0;
    const code = `LOC-${String(maxCode + 1).padStart(3, '0')}`;

    if (selectedLocation) {
      // 编辑库位
      setLocations(locations.map(loc => {
        if (loc.id === selectedLocation.id) {
          return {
            ...loc,
            name: locationFormData.name,
            warehouseId: locationFormData.warehouseId,
            warehouseName: locationFormData.warehouseName,
            notes: locationFormData.notes,
          };
        }
        return loc;
      }));

      toast.success('库位更新成功');
    } else {
      // 新增库位
      const newLocation: WarehouseLocation = {
        id: `loc-${Date.now()}`,
        code,
        name: locationFormData.name,
        warehouseId: locationFormData.warehouseId,
        warehouseName: locationFormData.warehouseName,
        status: '空闲',
        materials: [],
        notes: locationFormData.notes,
      };

      setLocations([...locations, newLocation]);

      // 更新仓库的库位数量
      setWarehouses(warehouses.map(wh => {
        if (wh.id === locationFormData.warehouseId) {
          return { ...wh, locationCount: wh.locationCount + 1 };
        }
        return wh;
      }));

      toast.success('库位创建成功', {
        description: `库位编码: ${code}`,
      });
    }

    // 重置表单
    setShowLocationDialog(false);
    setSelectedLocation(null);
    setLocationFormData({
      warehouseId: selectedWarehouse || 'wh-1',
      warehouseName: warehouses.find(w => w.id === (selectedWarehouse || 'wh-1'))?.name || '1号仓库',
      name: '',
      notes: '',
    });
  };

  // 禁用/启用库位
  const handleToggleLocationStatus = (locationId: string) => {
    const location = locations.find(l => l.id === locationId);
    if (!location) return;

    if (location.status === '使用中' && location.materials.length > 0) {
      toast.error('该库位仍有物料存放，无法禁用');
      return;
    }

    setLocations(locations.map(loc => {
      if (loc.id === locationId) {
        const newStatus = loc.status === '禁用' ? '空闲' : '禁用';
        return { ...loc, status: newStatus };
      }
      return loc;
    }));

    toast.success(location.status === '禁用' ? '库位已启用' : '库位已禁用');
  };

  // 打开库位删除确认对话框
  const handleOpenLocationDeleteConfirm = (location: WarehouseLocation) => {
    setLocationToDelete(location);
    setShowLocationDeleteConfirm(true);
  };

  // 删除库位
  const handleDeleteLocation = () => {
    if (!locationToDelete) return;

    // 检查库位是否有物料
    if (locationToDelete.materials && locationToDelete.materials.length > 0) {
      toast.error('该库位还有物料，无法删除');
      setShowLocationDeleteConfirm(false);
      setLocationToDelete(null);
      return;
    }

    setLocations(locations.filter(loc => loc.id !== locationToDelete.id));
    
    // 更新仓库的库位数量
    setWarehouses(warehouses.map(wh => {
      if (wh.id === locationToDelete.warehouseId) {
        return { 
          ...wh, 
          locationCount: wh.locationCount - 1,
          usedLocationCount: locationToDelete.status === '使用中' ? wh.usedLocationCount - 1 : wh.usedLocationCount
        };
      }
      return wh;
    }));
    
    toast.success('库位已删除');
    
    setShowLocationDeleteConfirm(false);
    setLocationToDelete(null);
  };

  // 重置库位筛选
  const handleResetLocationFilters = () => {
    setLocationSearchText('');
    setLocationStatusFilter('all');
    
    toast.success('筛选条件已重置');
  };

  // 获取库位统计数据
  const getLocationStats = () => {
    const filtered = getFilteredLocations();
    
    return {
      total: filtered.length,
      inUse: filtered.filter(l => l.status === '使用中').length,
      idle: filtered.filter(l => l.status === '空闲').length,
    };
  };

  // 获取指定仓库的库位列表（含筛选）
  const getWarehouseLocations = (warehouseId: string) => {
    return getFilteredLocations().filter(l => l.warehouseId === warehouseId);
  };

  // 获取库位状态颜色
  const getLocationStatusColor = (status: string) => {
    switch (status) {
      case '使用中':
        return 'bg-success-muted text-success-muted-foreground';
      case '空闲':
        return 'bg-muted text-muted-foreground';
      case '维护中':
        return 'bg-warning-muted text-warning-muted-foreground';
      case '禁用':
        return 'bg-error-muted text-error-muted-foreground';
      default:
        return 'bg-muted text-muted-foreground';
    }
  };

  // 仓库管理相关函数
  // 切换仓库展开/折叠
  const toggleWarehouseExpand = (warehouseId: string) => {
    const newExpanded = new Set(expandedWarehouses);
    if (newExpanded.has(warehouseId)) {
      newExpanded.delete(warehouseId);
    } else {
      newExpanded.add(warehouseId);
    }
    setExpandedWarehouses(newExpanded);
  };

  // 选中仓库
  const handleSelectWarehouse = (warehouseId: string) => {
    setSelectedWarehouse(warehouseId);
  };

  // 新增仓库
  const handleAddWarehouse = () => {
    setEditingWarehouse(null);
    setWarehouseFormData({
      name: '',
      code: '',
      type: '综合仓库',
      address: '',
      area: 0,
      manager: '',
      contact: '',
      notes: '',
    });
    setShowWarehouseDialog(true);
  };

  // 编辑仓库
  const handleEditWarehouse = (warehouse: Warehouse) => {
    setEditingWarehouse(warehouse);
    setWarehouseFormData({
      name: warehouse.name,
      code: warehouse.code,
      type: warehouse.type,
      address: warehouse.address || '',
      area: warehouse.area || 0,
      manager: warehouse.manager || '',
      contact: warehouse.contact || '',
      notes: warehouse.notes || '',
    });
    setShowWarehouseDialog(true);
  };

  // 提交仓库表单
  const handleSubmitWarehouse = () => {
    if (!warehouseFormData.name || !warehouseFormData.code) {
      toast.error('请填写仓库名称和编码');
      return;
    }

    // 检查编码是否重复
    const isDuplicate = warehouses.some(w => 
      w.code === warehouseFormData.code && 
      (!editingWarehouse || w.id !== editingWarehouse.id)
    );

    if (isDuplicate) {
      toast.error('仓库编码已存在');
      return;
    }

    if (editingWarehouse) {
      // 编辑仓库
      setWarehouses(warehouses.map(w => {
        if (w.id === editingWarehouse.id) {
          return {
            ...w,
            ...warehouseFormData,
          };
        }
        return w;
      }));
      toast.success('仓库更新成功');
    } else {
      // 新增仓库
      const newWarehouse: Warehouse = {
        id: `wh-${Date.now()}`,
        ...warehouseFormData,
        status: '正常',
        locationCount: 0,
        usedLocationCount: 0,
        createdAt: new Date().toISOString().split('T')[0],
      };
      setWarehouses([...warehouses, newWarehouse]);
      toast.success('仓库创建成功');
    }

    setShowWarehouseDialog(false);
  };

  // 打开仓库删除确认对话框
  const handleOpenWarehouseDeleteConfirm = (warehouse: Warehouse) => {
    setWarehouseToDelete(warehouse);
    setShowWarehouseDeleteConfirm(true);
  };

  // 删除仓库
  const handleDeleteWarehouse = () => {
    if (!warehouseToDelete) return;

    const warehouseLocations = locations.filter(l => l.warehouseId === warehouseToDelete.id);
    if (warehouseLocations.length > 0) {
      toast.error('该仓库下还有库位，无法删除');
      setShowWarehouseDeleteConfirm(false);
      setWarehouseToDelete(null);
      return;
    }

    setWarehouses(warehouses.filter(w => w.id !== warehouseToDelete.id));
    if (selectedWarehouse === warehouseToDelete.id) {
      setSelectedWarehouse(warehouses[0]?.id || null);
    }
    toast.success('仓库已删除');
    setShowWarehouseDeleteConfirm(false);
    setWarehouseToDelete(null);
  };

  // 采购建议相关函数
  // 智能计算采购建议
  const handleRecalculateSuggestions = () => {
    setIsCalculating(true);

    // 模拟计算过程
    setTimeout(() => {
      const newSuggestions: PurchaseSuggestion[] = [];

      // 遍历所有物料，计算采购建议
      materials.forEach(material => {
        // 获取该物料的当前库存（从库存批次汇总）
        const batches = availableStockBatches.filter(b => b.materialId === material.id);
        const currentStock = batches.reduce((sum, b) => sum + b.quantity, 0);
        const safeStock = material.safeStock;

        // 计算日均消耗（模拟数据：基于物料类型设置）
        let avgDailyConsumption = 0;
        if (material.type === '种子') avgDailyConsumption = 5;
        else if (material.type === '化肥') avgDailyConsumption = 8;
        else if (material.type === '农药') avgDailyConsumption = 3;
        else avgDailyConsumption = 2;

        // 预测未来N天的消耗量
        const forecastConsumption = avgDailyConsumption * forecastDays;

        // 计算建议采购数量
        // 建议采购量 = 安全库存 + 预测消耗 - 当前库存
        const suggestedQuantity = Math.max(0, safeStock + forecastConsumption - currentStock);

        // 只有需要采购时才加入建议列表
        if (suggestedQuantity > 0) {
          // 计算优先级
          const stockRatio = currentStock / safeStock;
          const priority: '高' | '中' | '低' = 
            stockRatio < 0.5 ? '高' : 
            stockRatio < 0.8 ? '中' : '低';

          // 获取最近采购价格（从可用物料列表）
          const lastPrice = availableMaterials.find(m => m.id === material.id)?.lastPrice || 100;

          // 生成建议原因
          let reason = '';
          if (currentStock < safeStock) {
            reason = `当前库存${currentStock}已低于安全库存${safeStock}`;
          } else {
            reason = `预测${forecastDays}天后库存不足`;
          }
          reason += `，预计消耗${forecastConsumption}`;

          newSuggestions.push({
            id: `sug-${material.id}-${Date.now()}`,
            materialId: material.id,
            materialName: material.name,
            materialType: material.type,
            currentStock,
            safeStock,
            avgDailyConsumption,
            forecastDays,
            forecastConsumption,
            suggestedQuantity: Math.ceil(suggestedQuantity),
            unit: availableMaterials.find(m => m.id === material.id)?.unit || '个',
            lastPurchasePrice: lastPrice,
            estimatedAmount: Math.ceil(suggestedQuantity) * lastPrice,
            priority,
            reason,
          });
        }
      });

      // 按优先级排序
      newSuggestions.sort((a, b) => {
        const priorityOrder = { '高': 0, '中': 1, '低': 2 };
        return priorityOrder[a.priority] - priorityOrder[b.priority];
      });

      setSuggestions(newSuggestions);
      setIsCalculating(false);

      toast.success('采购建议计算完成', {
        description: `基于${forecastDays}天预测，生成${newSuggestions.length}条建议`,
      });
    }, 1000);
  };

  // 查看建议详情
  const handleViewSuggestionDetail = (suggestion: PurchaseSuggestion) => {
    setSelectedSuggestion(suggestion);
    setShowSuggestionDetailDialog(true);
  };

  // 加入采购计划（单个）
  const handleAddToPurchasePlan = (suggestion: PurchaseSuggestion) => {
    setSelectedSuggestions([suggestion]);
    setPlanFormData({
      planNo: `PLAN-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${Math.floor(Math.random() * 1000)}`,
      supplierId: '',
      expectedDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 默认7天后
      notes: '',
    });
    setShowAddPlanDialog(true);
  };

  // 提交采购计划
  const handleSubmitPurchasePlan = () => {
    if (!planFormData.supplierId) {
      toast.error('请选择供应商');
      return;
    }

    if (!planFormData.expectedDate) {
      toast.error('请选择期望交货日期');
      return;
    }

    const totalQuantity = selectedSuggestions.reduce((sum, s) => sum + s.suggestedQuantity, 0);
    const totalAmount = selectedSuggestions.reduce((sum, s) => sum + s.estimatedAmount, 0);

    toast.success('采购计划已创建', {
      description: `计划单号: ${planFormData.planNo}，共${selectedSuggestions.length}个物料，预估总金额¥${totalAmount.toLocaleString()}`,
    });

    // 这里可以添加逻辑：
    // 1. 保存采购计划到状态/后端
    // 2. 跳转到采购管理-采购计划页面查看

    setShowAddPlanDialog(false);
    setSelectedSuggestions([]);
    setPlanFormData({
      planNo: '',
      supplierId: '',
      expectedDate: new Date().toISOString().split('T')[0],
      notes: '',
    });
  };

  const getWarningLevelColor = (level: string) => {
    switch (level) {
      case '高': return 'bg-error-muted text-error-muted-foreground';
      case '中': return 'bg-warning-muted text-warning-muted-foreground';
      case '低': return 'bg-warning-muted text-warning-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  // 统计数据
  const totalWarnings = warnings.length;
  const unhandledWarnings = warnings.filter(w => !w.handled).length;
  const totalLocations = locations.length;
  const usedLocations = locations.filter(l => l.status === '使用中').length;
  const totalSuggestions = suggestions.length;
  const highPriority = suggestions.filter(s => s.priority === '高').length;

  const COLORS = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#6b7280'];

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-success">库存管理</h2>
        <p className="text-muted-foreground">
          入库、出库、盘点与库存追溯全流程管理
        </p>
      </div>

      {/* 统计概览 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">库存预警</p>
              <p className="mt-2 text-3xl text-warning">{totalWarnings}</p>
              <p className="text-xs text-error mt-1">
                {unhandledWarnings} 项待处理
              </p>
            </div>
            <Bell className="w-12 h-12 text-warning 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-info">{totalLocations}</p>
              <p className="text-xs text-success mt-1">
                {usedLocations} 个使用中
              </p>
            </div>
            <MapPin className="w-12 h-12 text-info 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-foreground">{totalSuggestions}</p>
              <p className="text-xs text-warning mt-1">
                {highPriority} 项高优先级
              </p>
            </div>
            <ShoppingCart className="w-12 h-12 text-foreground 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-success">3</p>
              <p className="text-xs text-muted-foreground mt-1">
                今日出库: 2
              </p>
            </div>
            <Activity className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={(value) => {
        setActiveTab(value);
        // 同时触发路径更新，但这需要通过回调传递
        // 由于我们已经有useEffect监听activePath，这里暂时不需要额外处理
      }}>
        <TabsList className="grid w-full grid-cols-7">
          <TabsTrigger value="in">入库管理</TabsTrigger>
          <TabsTrigger value="out">出库管理</TabsTrigger>
          <TabsTrigger value="check">盘点管理</TabsTrigger>
          <TabsTrigger value="warning">库存预警</TabsTrigger>
          <TabsTrigger value="detail">库存明细</TabsTrigger>
          <TabsTrigger value="location">库位管理</TabsTrigger>
          <TabsTrigger value="suggest">采购建议</TabsTrigger>
        </TabsList>

        {/* 入库管理 */}
        <TabsContent value="in" className="space-y-4">
          <Card className="p-4 bg-success-muted border-success">
            <div className="flex items-start gap-2">
              <ArrowDownCircle className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-muted-foreground">
                <p className="mb-2">入库管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>多物料入库</strong>: 支持每次入库多个物料，提高效率</li>
                  <li>• <strong>多种入库方式</strong>: 支持基于订单入库和手动创建入库</li>
                  <li>• <strong>订单联动</strong>: 依据采购订单自动生成入库单</li>
                  <li>• <strong>批次管理</strong>: 记录批次号、生产日期、有效期</li>
                  <li>• <strong>价格记录</strong>: 记录单价、金额，用于成本核算</li>
                  <li>• <strong>库位分配</strong>: 指定物品存放库位</li>
                  <li>• <strong>即时更新</strong>: 入库后库存即时更新</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-success hover:bg-success/90" onClick={() => setShowInboundDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新增入库
            </Button>
          </div>

          <div className="space-y-4">
            {inboundRecords.map(record => (
              <Card key={record.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 bg-success-muted rounded-lg">
                      <ArrowDownCircle className="w-6 h-6 text-success" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{record.recordNo}</h4>
                        <Badge variant="outline">{record.type}</Badge>
                        <Badge className={
                          record.status === '已审核' ? 'bg-green-100 text-green-800' :
                          record.status === '待审核' ? 'bg-orange-100 text-orange-800' :
                          'bg-red-100 text-red-800'
                        }>
                          {record.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        仓库: {record.warehouseName} | 供应商: {record.supplierName} | {record.inboundDate}
                      </p>
                      {record.orderNo && (
                        <p className="text-xs text-blue-600 mt-1">
                          关联订单: {record.orderNo}
                        </p>
                      )}
                    </div>
                  </div>
                </div>

                <div className="overflow-x-auto mb-4">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-left p-2">物料名称</th>
                        <th className="text-left p-2">规格</th>
                        <th className="text-right p-2">数量</th>
                        <th className="text-left p-2">批次号</th>
                        <th className="text-left p-2">生产日期</th>
                        <th className="text-left p-2">有效期至</th>
                        <th className="text-left p-2">库位</th>
                        <th className="text-right p-2">单价</th>
                        <th className="text-right p-2">金额</th>
                      </tr>
                    </thead>
                    <tbody>
                      {record.items.map(item => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{item.materialName}</td>
                          <td className="p-2">{item.spec}</td>
                          <td className="text-right p-2">{item.quantity} {item.unit}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.batchNo}
                            </Badge>
                          </td>
                          <td className="p-2">{item.productionDate}</td>
                          <td className="p-2">{item.expiryDate}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.locationCode || '未分配'}
                            </Badge>
                          </td>
                          <td className="text-right p-2">¥{item.unitPrice}</td>
                          <td className="text-right p-2 font-medium">¥{item.amount.toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                <div className="flex items-center justify-between">
                  <div className="text-sm">
                    <span className="text-muted-foreground">操作人: </span>
                    <span>{record.operator}</span>
                    <span className="mx-2">|</span>
                    <span className="text-muted-foreground">总金额: </span>
                    <span className="font-medium text-green-600">
                      ¥{record.totalAmount.toLocaleString()}
                    </span>
                  </div>
                  <div className="flex gap-2">
                    {record.status === '待审核' ? (
                      <>
                        <Button 
                          size="sm" 
                          className="bg-green-600 hover:bg-green-700"
                          onClick={() => handleOpenApproval(record, 'approve')}
                        >
                          <CheckCircle2 className="w-4 h-4 mr-2" />
                          审批通过
                        </Button>
                        <Button 
                          size="sm" 
                          variant="outline"
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                          onClick={() => handleOpenApproval(record, 'reject')}
                        >
                          <XCircle className="w-4 h-4 mr-2" />
                          驳回
                        </Button>
                      </>
                    ) : (
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleOpenDetail(record)}
                      >
                        <Eye className="w-4 h-4 mr-2" />
                        详情
                      </Button>
                    )}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 出库管理 */}
        <TabsContent value="out" className="space-y-4">
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <ArrowUpCircle className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">出库管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>领用关联</strong>: 关联领用人/客户信息</li>
                  <li>• <strong>用途追踪</strong>: 记录具体地块或任务，便于溯源</li>
                  <li>• <strong>先进先出</strong>: 自动选择最早批次出库</li>
                  <li>• <strong>成本核算</strong>: 记录出库单价和金额</li>
                  <li>• <strong>库位管理</strong>: 记录出库库位信息</li>
                  <li>• <strong>即时核减</strong>: 出库后库存即时核减</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowOutboundDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新增出库
            </Button>
          </div>

          <div className="space-y-4">
            {outboundRecords.map(record => (
              <Card key={record.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 bg-blue-100 rounded-lg">
                      <ArrowUpCircle className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{record.recordNo}</h4>
                        <Badge variant="outline">{record.type}</Badge>
                        <Badge className={
                          record.status === '已审核' ? 'bg-green-100 text-green-800' :
                          record.status === '待审核' ? 'bg-orange-100 text-orange-800' :
                          'bg-red-100 text-red-800'
                        }>
                          {record.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        出库仓库: {record.warehouseName}
                        {record.type === '调拨出库' && record.targetWarehouseName && (
                          <> → 入库仓库: {record.targetWarehouseName}</>
                        )}
                        {record.type !== '调拨出库' && <> | 领用人: {record.recipient}</>}
                        {' | '}{record.outboundDate}
                      </p>
                      <p className="text-xs text-purple-600 mt-1">
                        用途: {record.purpose}
                        {record.fieldName && ` - ${record.fieldName}`}
                        {record.taskName && ` - ${record.taskName}`}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="overflow-x-auto mb-4">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-left p-2">物料名称</th>
                        <th className="text-left p-2">规格</th>
                        <th className="text-right p-2">数量</th>
                        <th className="text-left p-2">批次号</th>
                        <th className="text-left p-2">库位</th>
                        <th className="text-right p-2">单价</th>
                        <th className="text-right p-2">金额</th>
                      </tr>
                    </thead>
                    <tbody>
                      {record.items.map(item => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{item.materialName}</td>
                          <td className="p-2">{item.spec}</td>
                          <td className="text-right p-2">{item.quantity} {item.unit}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.batchNo}
                            </Badge>
                          </td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.locationCode}
                            </Badge>
                          </td>
                          <td className="text-right p-2">¥{item.unitPrice}</td>
                          <td className="text-right p-2 font-medium">¥{item.amount.toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                <div className="flex items-center justify-between">
                  <div className="text-sm">
                    <span className="text-muted-foreground">操作人: </span>
                    <span>{record.operator}</span>
                    <span className="mx-2">|</span>
                    <span className="text-muted-foreground">总金额: </span>
                    <span className="font-medium text-blue-600">
                      ¥{record.totalAmount.toLocaleString()}
                    </span>
                  </div>
                  <div className="flex gap-2">
                    {record.status === '待审核' && (
                      <>
                        <Button 
                          size="sm" 
                          className="bg-green-600 hover:bg-green-700"
                          onClick={() => handleOpenOutboundApproval(record, 'approve')}
                        >
                          <CheckCircle2 className="w-4 h-4 mr-2" />
                          审批通过
                        </Button>
                        <Button 
                          size="sm" 
                          variant="outline"
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                          onClick={() => handleOpenOutboundApproval(record, 'reject')}
                        >
                          <XCircle className="w-4 h-4 mr-2" />
                          驳回
                        </Button>
                      </>
                    )}
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => handleOpenOutboundDetail(record)}
                    >
                      <Eye className="w-4 h-4 mr-2" />
                      详情
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 盘点管理 */}
        <TabsContent value="check" className="space-y-4">
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <ClipboardList 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>
                  <li>• <strong>账实相符</strong>: 确保库存账实��致</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowCheckDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              创建盘点任务
            </Button>
          </div>

          <div className="space-y-4">
            {checkTasks.map(task => (
              <Card key={task.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 bg-purple-100 rounded-lg">
                      <ClipboardList className="w-6 h-6 text-purple-600" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{task.taskName}</h4>
                        <Badge variant="outline">{task.checkType}</Badge>
                        <Badge className={
                          task.status === '已完成' ? 'bg-green-100 text-green-800' :
                          task.status === '待审批' ? 'bg-orange-100 text-orange-800' :
                          task.status === '待盘点' ? 'bg-blue-100 text-blue-800' :
                          'bg-gray-100 text-gray-800'
                        }>
                          {task.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        任务编号: {task.taskNo} | 仓库: {task.warehouseName} | 盘点人: {task.checker}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-4 gap-4 mb-4">
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">计划日期</p>
                    <p className="mt-1 font-medium">{task.planDate}</p>
                  </div>
                  <div className="p-3 bg-green-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">盘盈</p>
                    <p className="mt-1 text-xl font-medium text-green-600">
                      {task.profit} 项
                    </p>
                  </div>
                  <div className="p-3 bg-red-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">盘亏</p>
                    <p className="mt-1 text-xl font-medium text-red-600">
                      {task.loss} 项
                    </p>
                  </div>
                  <div className="p-3 bg-purple-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">盘点项数</p>
                    <p className="mt-1 text-xl font-medium text-purple-600">
                      {task.items.length} 项
                    </p>
                  </div>
                </div>

                <div className="overflow-x-auto mb-4">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-left p-2">物料名称</th>
                        <th className="text-left p-2">库位</th>
                        <th className="text-right p-2">账面数量</th>
                        <th className="text-right p-2">实盘数量</th>
                        <th className="text-right p-2">差异</th>
                        <th className="text-left p-2">状态</th>
                        <th className="text-left p-2">备注</th>
                      </tr>
                    </thead>
                    <tbody>
                      {task.items.map(item => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{item.materialName}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.locationCode}
                            </Badge>
                          </td>
                          <td className="text-right p-2">{item.bookQuantity} {item.unit}</td>
                          <td className="text-right p-2">{item.actualQuantity} {item.unit}</td>
                          <td className="text-right p-2">
                            <span className={
                              item.difference > 0 ? 'text-green-600 font-medium' :
                              item.difference < 0 ? 'text-red-600 font-medium' :
                              'text-gray-600'
                            }>
                              {item.difference > 0 ? '+' : ''}{item.difference} {item.unit}
                            </span>
                          </td>
                          <td className="p-2">
                            <Badge className={
                              item.status === '盘盈' ? 'bg-green-100 text-green-800' :
                              item.status === '盘亏' ? 'bg-red-100 text-red-800' :
                              'bg-gray-100 text-gray-800'
                            }>
                              {item.status}
                            </Badge>
                          </td>
                          <td className="p-2 text-xs">{item.notes || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                <div className="flex items-center justify-between">
                  <div className="text-sm text-muted-foreground">
                    创建时间: {task.createdAt}
                  </div>
                  <div className="flex gap-2">
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => handlePrintCheckList(task)}
                    >
                      <Printer className="w-4 h-4 mr-2" />
                      打印盘点表
                    </Button>
                    {task.status === '待盘点' && (
                      <Button 
                        size="sm" 
                        className="bg-blue-600 hover:bg-blue-700"
                        onClick={() => handleOpenCheckInput(task)}
                      >
                        <Edit className="w-4 h-4 mr-2" />
                        盘点录入
                      </Button>
                    )}
                    {task.status === '待审批' && (
                      <>
                        <Button 
                          size="sm" 
                          className="bg-green-600 hover:bg-green-700"
                          onClick={() => handleOpenCheckApproval(task, 'approve')}
                        >
                          <CheckCircle2 className="w-4 h-4 mr-2" />
                          审批通过
                        </Button>
                        <Button 
                          size="sm" 
                          variant="outline"
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                          onClick={() => handleOpenCheckApproval(task, 'reject')}
                        >
                          <XCircle className="w-4 h-4 mr-2" />
                          驳回
                        </Button>
                      </>
                    )}
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => {
                        setSelectedCheckTask(task);
                        setShowCheckItemDialog(true);
                      }}
                    >
                      <Eye className="w-4 h-4 mr-2" />
                      详情
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 库存预警 */}
        <TabsContent value="warning" className="space-y-4">
          <Card className="p-4 bg-orange-50 border-orange-200">
            <div className="flex items-start gap-2">
              <Bell 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>: 提前30天预警即将过期的物品</li>
                  <li>• <strong>多渠道通知</strong>: 界面、短信、邮件等方式通知库管和采购人员</li>
                  <li>• <strong>分级管理</strong>: 高/中/低三级预警（高：&lt;30%，中：30-60%，低：60-100%）</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 操作按钮和筛选 */}
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-2">
              <Select
                value={warningFilter.level}
                onValueChange={(value) => setWarningFilter({ ...warningFilter, level: value })}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部级别</SelectItem>
                  <SelectItem value="高">高级预警</SelectItem>
                  <SelectItem value="中">中级预警</SelectItem>
                  <SelectItem value="低">低级预警</SelectItem>
                </SelectContent>
              </Select>

              <Select
                value={warningFilter.type}
                onValueChange={(value) => setWarningFilter({ ...warningFilter, type: value })}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="库存不足">库存不足</SelectItem>
                  <SelectItem value="临期预警">临期预警</SelectItem>
                </SelectContent>
              </Select>

              <Select
                value={warningFilter.handled}
                onValueChange={(value) => setWarningFilter({ ...warningFilter, handled: value })}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="unhandled">待处理</SelectItem>
                  <SelectItem value="handled">已处理</SelectItem>
                </SelectContent>
              </Select>

              <Badge className="bg-red-100 text-red-800">
                {warnings.filter(w => 
                  (warningFilter.level === 'all' || w.warningLevel === warningFilter.level) &&
                  (warningFilter.type === 'all' || w.warningType === warningFilter.type) &&
                  (warningFilter.handled === 'all' || 
                    (warningFilter.handled === 'unhandled' ? !w.handled : w.handled))
                ).length} 条预警
              </Badge>
            </div>

            <div className="flex gap-2">
              <Button 
                variant="outline"
                onClick={checkStockAndGenerateWarnings}
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                检查库存
              </Button>
              <Button 
                className="bg-orange-600 hover:bg-orange-700"
                onClick={() => setShowWarningRuleDialog(true)}
              >
                <Settings className="w-4 h-4 mr-2" />
                预警设置
              </Button>
            </div>
          </div>

          {/* 统计卡片 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-4 bg-red-50 border-red-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">高级预警</p>
                  <p className="text-2xl font-medium text-red-600 mt-1">
                    {warnings.filter(w => w.warningLevel === '高' && !w.handled).length}
                  </p>
                </div>
                <AlertTriangle className="w-8 h-8 text-red-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-orange-50 border-orange-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">中级预警</p>
                  <p className="text-2xl font-medium text-orange-600 mt-1">
                    {warnings.filter(w => w.warningLevel === '中' && !w.handled).length}
                  </p>
                </div>
                <AlertTriangle className="w-8 h-8 text-orange-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-yellow-50 border-yellow-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">低级预警</p>
                  <p className="text-2xl font-medium text-yellow-600 mt-1">
                    {warnings.filter(w => w.warningLevel === '低' && !w.handled).length}
                  </p>
                </div>
                <AlertTriangle className="w-8 h-8 text-yellow-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-green-50 border-green-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">已处理</p>
                  <p className="text-2xl font-medium text-green-600 mt-1">
                    {warnings.filter(w => w.handled).length}
                  </p>
                </div>
                <CheckCircle2 className="w-8 h-8 text-green-600 opacity-20" />
              </div>
            </Card>
          </div>

          <div className="space-y-4">
            {warnings
              .filter(w => 
                (warningFilter.level === 'all' || w.warningLevel === warningFilter.level) &&
                (warningFilter.type === 'all' || w.warningType === warningFilter.type) &&
                (warningFilter.handled === 'all' || 
                  (warningFilter.handled === 'unhandled' ? !w.handled : w.handled))
              )
              .map(warning => (
              <Card key={warning.id} className={`p-6 border-l-4 ${
                warning.handled ? 'border-l-gray-300 bg-gray-50' :
                warning.warningLevel === '高' ? 'border-l-red-500 bg-red-50' :
                warning.warningLevel === '中' ? 'border-l-orange-500 bg-orange-50' :
                'border-l-yellow-500 bg-yellow-50'
              }`}>
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className={`p-3 rounded-lg ${
                      warning.handled ? 'bg-gray-100' :
                      warning.warningLevel === '高' ? 'bg-red-100' :
                      warning.warningLevel === '中' ? 'bg-orange-100' :
                      'bg-yellow-100'
                    }`}>
                      {warning.handled ? (
                        <CheckCircle2 className="w-6 h-6 text-green-600" />
                      ) : (
                        <AlertTriangle className={`w-6 h-6 ${
                          warning.warningLevel === '高' ? 'text-red-600' :
                          warning.warningLevel === '中' ? 'text-orange-600' :
                          'text-yellow-600'
                        }`} />
                      )}
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{warning.materialName}</h4>
                        <Badge variant="outline">{warning.materialType}</Badge>
                        {!warning.handled && (
                          <Badge className={getWarningLevelColor(warning.warningLevel)}>
                            {warning.warningLevel}预警
                          </Badge>
                        )}
                        <Badge className={
                          warning.warningType === '库存不足' ? 'bg-orange-100 text-orange-800' :
                          warning.warningType === '临期预警' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-red-100 text-red-800'
                        }>
                          {warning.warningType}
                        </Badge>
                        {warning.handled && (
                          <Badge className="bg-green-100 text-green-800">已处理</Badge>
                        )}
                        {warning.notified && !warning.handled && (
                          <Badge className="bg-blue-100 text-blue-800">已通知</Badge>
                        )}
                      </div>
                      <p className="text-sm text-muted-foreground">
                        仓库: {warning.warehouseName} | 批次: {warning.batchNo} | 库位: {warning.locationCode}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        预警时间: {warning.createdAt} 
                        {warning.handled && ` | 处理时间: ${warning.handledAt}`}
                        {warning.notified && ` | 通知时间: ${new Date(warning.notifiedAt).toLocaleString()}`}
                      </p>
                    </div>
                  </div>
                  {!warning.handled && (
                    <div className="flex gap-2">
                      <Button 
                        size="sm" 
                        className="bg-green-600 hover:bg-green-700"
                        onClick={() => handleMarkWarningHandled(warning.id)}
                      >
                        <CheckCircle2 className="w-4 h-4 mr-2" />
                        标记已处理
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => {
                          setSelectedWarning(warning);
                          setShowWarningDetailDialog(true);
                        }}
                      >
                        <Eye className="w-4 h-4 mr-2" />
                        详情
                      </Button>
                    </div>
                  )}
                </div>

                <div className="mb-4 p-3 bg-white border border-orange-200 rounded-lg">
                  <p className="text-sm">
                    <AlertCircle className="w-4 h-4 inline mr-2 text-orange-600" />
                    <strong>预警消息：</strong>{warning.message}
                  </p>
                </div>

                <div className="grid grid-cols-4 gap-4">
                  <div className="p-3 bg-white rounded-lg border">
                    <p className="text-xs text-muted-foreground">当前库存</p>
                    <p className={`mt-1 text-xl font-medium ${
                      warning.warningType === '库存不足' ? 'text-orange-600' : 'text-gray-600'
                    }`}>
                      {warning.currentStock} {warning.unit}
                    </p>
                    {warning.warningType === '库存不足' && (
                      <p className="text-xs text-red-600 mt-1">
                        {((warning.currentStock / warning.safeStock) * 100).toFixed(1)}% 库存率
                      </p>
                    )}
                  </div>
                  <div className="p-3 bg-white rounded-lg border">
                    <p className="text-xs text-muted-foreground">安全库存</p>
                    <p className="mt-1 text-xl font-medium text-green-600">
                      {warning.safeStock} {warning.unit}
                    </p>
                    {warning.warningType === '库存不足' && (
                      <p className="text-xs text-orange-600 mt-1">
                        缺口: {(warning.safeStock - warning.currentStock).toFixed(0)} {warning.unit}
                      </p>
                    )}
                  </div>
                  {warning.expiryDate ? (
                    <>
                      <div className="p-3 bg-white rounded-lg border">
                        <p className="text-xs text-muted-foreground">有效期至</p>
                        <p className="mt-1 font-medium">{warning.expiryDate}</p>
                      </div>
                      <div className="p-3 bg-white rounded-lg border">
                        <p className="text-xs text-muted-foreground">剩余天数</p>
                        <p className={`mt-1 text-xl font-medium ${
                          warning.daysLeft <= 7 ? 'text-red-600' :
                          warning.daysLeft <= 15 ? 'text-orange-600' :
                          'text-yellow-600'
                        }`}>
                          {warning.daysLeft} 天
                        </p>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="p-3 bg-white rounded-lg border">
                        <p className="text-xs text-muted-foreground">建议采购</p>
                        <p className="mt-1 text-xl font-medium text-purple-600">
                          {((warning.safeStock * 1.5) - warning.currentStock).toFixed(0)} {warning.unit}
                        </p>
                      </div>
                      <div className="p-3 bg-white rounded-lg border">
                        <p className="text-xs text-muted-foreground">预计金额</p>
                        <p className="mt-1 text-xl font-medium text-blue-600">
                          待估算
                        </p>
                      </div>
                    </>
                  )}
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 库存明细 */}
        <TabsContent value="detail" className="space-y-4">
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <FileText className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">库存明细功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>完整记录</strong>: 自动记录每一笔库存变动（入库、出库、调拨、盘点调整）</li>
                  <li>• <strong>详细信息</strong>: 记录时间、数量、变动前后库存、操作人、相关单号</li>
                  <li>• <strong>多维筛选</strong>: 按物品、仓库、类型、时间范围精确查询</li>
                  <li>• <strong>批次追溯</strong>: 查看某个批次的完整变动历史链</li>
                  <li>• <strong>全链追溯</strong>: 从源头到消耗的完整库存流转记录</li>
                  <li>• <strong>审计支持</strong>: 为财务审计和质量追溯提供完整凭证</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 统计卡片 */}
          <div className="grid grid-cols-5 gap-4">
            <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">总变动记录</p>
                  <p className="text-2xl font-medium text-blue-600 mt-1">
                    {getTransactionStats().total}
                  </p>
                </div>
                <FileText className="w-8 h-8 text-blue-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">入库记录</p>
                  <p className="text-2xl font-medium text-green-600 mt-1">
                    {getTransactionStats().inbound}
                  </p>
                </div>
                <ArrowDownCircle className="w-8 h-8 text-green-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-orange-50 to-orange-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">出库记录</p>
                  <p className="text-2xl font-medium text-orange-600 mt-1">
                    {getTransactionStats().outbound}
                  </p>
                </div>
                <ArrowUpCircle className="w-8 h-8 text-orange-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">盘点调整</p>
                  <p className="text-2xl font-medium text-purple-600 mt-1">
                    {getTransactionStats().profit + getTransactionStats().loss}
                  </p>
                </div>
                <ClipboardList className="w-8 h-8 text-purple-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-gray-50 to-gray-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">调拨记录</p>
                  <p className="text-2xl font-medium text-gray-600 mt-1">
                    {getTransactionStats().transfer}
                  </p>
                </div>
                <Package className="w-8 h-8 text-gray-600 opacity-20" />
              </div>
            </Card>
          </div>

          {/* 筛选区域 */}
          <Card className="p-4">
            <div className="grid grid-cols-4 gap-4 mb-4">
              <div>
                <Label>搜索</Label>
                <Input 
                  placeholder="物料名称/批次号/流水号..."
                  value={detailSearchText}
                  onChange={(e) => setDetailSearchText(e.target.value)}
                />
              </div>
              
              <div>
                <Label>变动类型</Label>
                <Select value={detailTypeFilter} onValueChange={setDetailTypeFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="入库">入库</SelectItem>
                  <SelectItem value="出库">出库</SelectItem>
                  <SelectItem value="调拨">调拨</SelectItem>
                  <SelectItem value="盘盈">盘盈</SelectItem>
                  <SelectItem value="盘亏">盘亏</SelectItem>
                </SelectContent>
              </Select>
              </div>

              <div>
                <Label>仓库</Label>
                <Select value={detailWarehouseFilter} onValueChange={setDetailWarehouseFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部仓库</SelectItem>
                    <SelectItem value="wh-1">1号仓库</SelectItem>
                    <SelectItem value="wh-2">2号仓库</SelectItem>
                    <SelectItem value="wh-3">3号仓库</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>时间范围</Label>
                <div className="flex gap-2">
                  <Input 
                    type="date"
                    value={detailDateRange.start}
                    onChange={(e) => setDetailDateRange({ ...detailDateRange, start: e.target.value })}
                    className="w-full"
                  />
                  <span className="flex items-center text-muted-foreground">至</span>
                  <Input 
                    type="date"
                    value={detailDateRange.end}
                    onChange={(e) => setDetailDateRange({ ...detailDateRange, end: e.target.value })}
                    className="w-full"
                  />
                </div>
              </div>
            </div>

            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Badge className="bg-blue-100 text-blue-800">
                  {getFilteredTransactions().length} 条记录
                </Badge>
                {(detailSearchText || detailTypeFilter !== 'all' || detailWarehouseFilter !== 'all' || detailDateRange.start || detailDateRange.end) && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={handleResetDetailFilters}
                  >
                    重置筛选
                  </Button>
                )}
              </div>
            </div>
          </Card>

          {/* 变动记录表格 */}
          <Card className="p-6">
            <div className="mb-4 flex items-center justify-between">
              <h4>库存变动记录</h4>
              <p className="text-sm text-muted-foreground">
                共 {getFilteredTransactions().length} 条记录
                {getFilteredTransactions().length > 0 && (
                  <span className="ml-4">
                    入库合计: <span className="text-green-600 font-medium">
                      +{getTransactionStats().totalInQuantity.toFixed(2)}
                    </span> | 
                    出库合计: <span className="text-red-600 font-medium">
                      -{getTransactionStats().totalOutQuantity.toFixed(2)}
                    </span>
                  </span>
                )}
              </p>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="text-left p-3">流水号</th>
                    <th className="text-left p-3">变动类型</th>
                    <th className="text-left p-3">物料名称</th>
                    <th className="text-right p-3">变动数量</th>
                    <th className="text-left p-3">批次号</th>
                    <th className="text-left p-3">仓库</th>
                    <th className="text-left p-3">库位</th>
                    <th className="text-right p-3">变动前</th>
                    <th className="text-right p-3">变动后</th>
                    <th className="text-left p-3">操作人</th>
                    <th className="text-left p-3">关联单号</th>
                    <th className="text-left p-3">变动时间</th>
                    <th className="text-center p-3">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {getFilteredTransactions().length === 0 ? (
                    <tr>
                      <td colSpan={13} className="text-center p-8 text-muted-foreground">
                        <FileSearch className="w-12 h-12 mx-auto mb-2 opacity-50" />
                        <p>暂无变动记录</p>
                      </td>
                    </tr>
                  ) : (
                    getFilteredTransactions().map(trans => (
                      <tr key={trans.id} className="border-t hover:bg-gray-50">
                        <td className="p-3">
                          <span className="font-mono text-xs">{trans.transactionNo}</span>
                        </td>
                        <td className="p-3">
                          <Badge className={
                            trans.type === '入库' ? 'bg-green-100 text-green-800' :
                            trans.type === '出库' ? 'bg-blue-100 text-blue-800' :
                            trans.type === '盘盈' ? 'bg-purple-100 text-purple-800' :
                            trans.type === '盘亏' ? 'bg-red-100 text-red-800' :
                            'bg-gray-100 text-gray-800'
                          }>
                            {trans.type}
                          </Badge>
                        </td>
                        <td className="p-3">
                          <div>{trans.materialName}</div>
                          <div className="text-xs text-muted-foreground">{trans.unit}</div>
                        </td>
                        <td className="text-right p-3">
                          <span className={
                            trans.type === '入库' || trans.type === '盘盈' ? 'text-green-600 font-medium' :
                            'text-red-600 font-medium'
                          }>
                            {trans.type === '入库' || trans.type === '盘盈' ? '+' : '-'}
                            {trans.quantity} {trans.unit}
                          </span>
                        </td>
                        <td className="p-3">
                          <div className="flex items-center gap-2">
                            <Badge variant="outline" className="text-xs font-mono">
                              {trans.batchNo}
                            </Badge>
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-6 px-2"
                              onClick={() => generateTraceChain(trans.batchNo)}
                              title="查看批次追溯链"
                            >
                              <FileSearch className="w-3 h-3" />
                            </Button>
                          </div>
                        </td>
                        <td className="p-3">{trans.warehouseName}</td>
                        <td className="p-3">
                          <Badge variant="outline" className="text-xs">
                            {trans.locationCode || '-'}
                          </Badge>
                        </td>
                        <td className="text-right p-3 text-muted-foreground">
                          {trans.beforeStock} {trans.unit}
                        </td>
                        <td className="text-right p-3 font-medium">
                          {trans.afterStock} {trans.unit}
                        </td>
                        <td className="p-3">
                          <div className="flex items-center gap-2">
                            <User className="w-4 h-4 text-muted-foreground" />
                            {trans.operator}
                          </div>
                        </td>
                        <td className="p-3">
                          {trans.relatedNo ? (
                            <Badge variant="outline" className="text-xs font-mono">
                              {trans.relatedNo}
                            </Badge>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </td>
                        <td className="p-3">
                          <div className="text-xs">
                            <div>{trans.createdDate}</div>
                            <div className="text-muted-foreground">{trans.createdTime}</div>
                          </div>
                        </td>
                        <td className="p-3 text-center">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => {
                              setSelectedTransaction(trans);
                              setShowDetailDialog(true);
                            }}
                          >
                            <Eye className="w-4 h-4 mr-1" />
                            详情
                          </Button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>

        {/* 库位管理 */}
        <TabsContent value="location" className="space-y-4">
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <Warehouse className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">仓库与库位管理：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>树状管理</strong>: 先添加仓库，再在仓库下添加库位，层级结构清晰</li>
                  <li>• <strong>仓库管理</strong>: 管理仓库基本信息、仓库类型、负责人等</li>
                  <li>• <strong>库位管理</strong>: 为仓库创建存储位置，记录位置名称和编码</li>
                  <li>• <strong>快速找货</strong>: 通过库位码快速定位物品存放位置，提高拣货效率</li>
                  <li>• <strong>二维码功能</strong>: 每个库位支持生成二维码，方便扫码查询和管理</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 树状结构：左侧仓库列表，右侧库位列表 */}
          <div className="grid grid-cols-12 gap-4">
            {/* 左侧：仓库列表 */}
            <div className="col-span-4">
              <Card className="p-4">
                <div className="flex items-center justify-between mb-4">
                  <h4>仓库列表</h4>
                  <Button 
                    size="sm"
                    className="bg-green-600 hover:bg-green-700"
                    onClick={handleAddWarehouse}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    新增仓库
                  </Button>
                </div>

                <div className="space-y-2">
                  {warehouses.map(warehouse => {
                    const warehouseLocations = locations.filter(l => l.warehouseId === warehouse.id);
                    const usedLocations = warehouseLocations.filter(l => l.status === '使用中').length;
                    const isExpanded = expandedWarehouses.has(warehouse.id);
                    const isSelected = selectedWarehouse === warehouse.id;

                    return (
                      <div key={warehouse.id}>
                        <div 
                          className={`p-3 border rounded-lg cursor-pointer hover:bg-gray-50 transition-colors ${
                            isSelected ? 'bg-green-50 border-green-300' : 'bg-white'
                          }`}
                          onClick={() => handleSelectWarehouse(warehouse.id)}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-2 flex-1">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  toggleWarehouseExpand(warehouse.id);
                                }}
                                className="mt-0.5"
                              >
                                {isExpanded ? (
                                  <svg className="w-4 h-4 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                  </svg>
                                ) : (
                                  <svg className="w-4 h-4 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                  </svg>
                                )}
                              </button>
                              <Warehouse className={`w-5 h-5 mt-0.5 ${isSelected ? 'text-green-600' : 'text-gray-600'}`} />
                              <div className="flex-1">
                                <div className="flex items-center gap-2">
                                  <span className={`font-medium ${isSelected ? 'text-green-900' : ''}`}>
                                    {warehouse.name}
                                  </span>
                                  <Badge variant="outline" className="text-xs">
                                    {warehouse.type}
                                  </Badge>
                                </div>
                                <p className="text-xs text-muted-foreground mt-1">
                                  {warehouse.code} | {warehouseLocations.length} 个库位
                                </p>
                              </div>
                            </div>
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleEditWarehouse(warehouse);
                                }}
                              >
                                <Edit className="w-3 h-3" />
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleOpenWarehouseDeleteConfirm(warehouse);
                                }}
                              >
                                <Trash2 className="w-3 h-3 text-red-600" />
                              </Button>
                            </div>
                          </div>

                          {isExpanded && (
                            <div className="mt-2 ml-6 space-y-1">
                              {warehouseLocations.map(loc => (
                                <div key={loc.id} className="text-xs p-2 bg-gray-50 rounded flex items-center justify-between">
                                  <div className="flex items-center gap-2">
                                    <MapPin className="w-3 h-3 text-gray-500" />
                                    <span>{loc.code}</span>
                                    <Badge className={`text-xs ${
                                      loc.status === '使用中' ? 'bg-green-100 text-green-800' :
                                      loc.status === '空闲' ? 'bg-gray-100 text-gray-800' :
                                      loc.status === '维护中' ? 'bg-orange-100 text-orange-800' :
                                      'bg-red-100 text-red-800'
                                    }`}>
                                      {loc.status}
                                    </Badge>
                                  </div>
                                  <span className="text-muted-foreground">
                                    {loc.usedCapacity}/{loc.capacity}
                                  </span>
                                </div>
                              ))}
                              {warehouseLocations.length === 0 && (
                                <p className="text-xs text-muted-foreground p-2">暂无库位</p>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </Card>
            </div>

            {/* 右侧：库位列表 */}
            <div className="col-span-8 space-y-4">
              {/* 筛选和操作区域 */}
              <Card className="p-4">
                <div className="grid grid-cols-3 gap-4 mb-4">
                  <div>
                    <Label>搜索</Label>
                    <Input 
                      placeholder="库位码/物料..."
                      value={locationSearchText}
                      onChange={(e) => setLocationSearchText(e.target.value)}
                    />
                  </div>

                  <div>
                    <Label>状态</Label>
                    <Select value={locationStatusFilter} onValueChange={setLocationStatusFilter}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部状态</SelectItem>
                        <SelectItem value="空闲">空闲</SelectItem>
                        <SelectItem value="使用中">使用中</SelectItem>
                        <SelectItem value="维护中">维护中</SelectItem>
                        <SelectItem value="禁用">禁用</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Badge className="bg-blue-100 text-blue-800">
                      {selectedWarehouse ? getWarehouseLocations(selectedWarehouse).length : 0} 个库位
                    </Badge>
                    {(locationSearchText || locationStatusFilter !== 'all') && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={handleResetLocationFilters}
                      >
                        重置筛选
                      </Button>
                    )}
                  </div>

                  <Button 
                    className="bg-green-600 hover:bg-green-700"
                    disabled={!selectedWarehouse}
                    onClick={() => {
                      if (!selectedWarehouse) return;
                      const warehouse = warehouses.find(w => w.id === selectedWarehouse);
                      setSelectedLocation(null);
                      setLocationFormData({
                        warehouseId: selectedWarehouse,
                        warehouseName: warehouse?.name || '',
                        name: '',
                        notes: '',
                      });
                      setShowLocationDialog(true);
                    }}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    新增库位
                  </Button>
                </div>
              </Card>

              {/* 库位列表 */}
              <div className="grid grid-cols-2 gap-4">
                {!selectedWarehouse ? (
                  <Card className="col-span-2 p-8 text-center">
                    <Warehouse className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-muted-foreground">请先选择仓库</p>
                  </Card>
                ) : getWarehouseLocations(selectedWarehouse).length === 0 ? (
                  <Card className="col-span-2 p-8 text-center">
                    <Package className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-muted-foreground">该仓库暂无库位</p>
                  </Card>
                ) : (
                  getWarehouseLocations(selectedWarehouse).map(location => {
                    return (
                      <Card key={location.id} className={`p-6 ${
                        location.status === '禁用' ? 'opacity-60' : ''
                      }`}>
                        <div className="flex items-start justify-between mb-4">
                          <div className="flex items-start gap-3">
                            <div className={`p-3 rounded-lg ${
                              location.status === '使用中' ? 'bg-green-100' :
                          location.status === '空闲' ? 'bg-gray-100' :
                          location.status === '维护中' ? 'bg-orange-100' :
                          'bg-red-100'
                        }`}>
                          <Box className={`w-6 h-6 ${
                            location.status === '使用中' ? 'text-green-600' :
                            location.status === '空闲' ? 'text-gray-600' :
                            location.status === '维护中' ? 'text-orange-600' :
                            'text-red-600'
                          }`} />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h4 className="font-mono text-sm text-muted-foreground">{location.code}</h4>
                            <Badge className={getLocationStatusColor(location.status)}>
                              {location.status}
                            </Badge>
                          </div>
                          <h4 className="mb-1">{location.name}</h4>
                          <p className="text-sm text-muted-foreground">
                            {location.warehouseName}
                          </p>
                        </div>
                      </div>
                    </div>

                    {location.materials.length > 0 ? (
                      <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                        <div className="flex items-center gap-2 mb-2">
                          <Package className="w-4 h-4 text-blue-600" />
                          <p className="text-xs font-medium text-blue-900">
                            存储物料 ({location.materials.length}种)
                          </p>
                        </div>
                        <div className="space-y-1">
                          {location.materials.slice(0, 2).map((mat, i) => (
                            <div key={i} className="text-sm flex items-center justify-between">
                              <span className="text-blue-900">• {mat.materialName}</span>
                              <span className="font-medium text-blue-600">
                                {mat.quantity} {mat.unit}
                              </span>
                            </div>
                          ))}
                          {location.materials.length > 2 && (
                            <p className="text-xs text-blue-600 mt-1">
                              +{location.materials.length - 2} 种物料...
                            </p>
                          )}
                        </div>
                      </div>
                    ) : (
                      <div className="p-3 bg-gray-50 rounded-lg text-center">
                        <Package className="w-6 h-6 text-gray-400 mx-auto mb-1" />
                        <p className="text-xs text-muted-foreground">暂无物料</p>
                      </div>
                    )}

                    {location.notes && (
                      <div className="mt-3 text-xs text-muted-foreground p-2 bg-yellow-50 rounded border border-yellow-200">
                        <AlertCircle className="w-3 h-3 inline mr-1" />
                        {location.notes}
                      </div>
                    )}

                    <div className="flex gap-2 mt-4">
                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="flex-1"
                        onClick={() => handleOpenLocationEdit(location)}
                        disabled={location.status === '禁用'}
                      >
                        <Edit className="w-4 h-4 mr-1" />
                        编辑
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleViewLocationQRCode(location)}
                        title="查看二维码"
                      >
                        <QrCode className="w-4 h-4" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleOpenLocationDetail(location)}
                        title="查看详情"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        className="text-red-600 hover:bg-red-50"
                        onClick={() => handleOpenLocationDeleteConfirm(location)}
                        disabled={location.materials.length > 0}
                        title={location.materials.length > 0 ? "该库位还有物料，无法删除" : "删除库位"}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                        </div>
                      </Card>
                    );
                  })
                )}
              </div>
            </div>
          </div>
        </TabsContent>

        {/* 采购建议 */}
        <TabsContent value="suggest" className="space-y-4">
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Zap 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>: 基于日均消耗预测未来N天的计划消耗量，避免断货</li>
                  <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-4 gap-4">
            <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">建议总数</p>
                  <p className="text-2xl font-medium text-purple-600 mt-1">
                    {suggestions.length}
                  </p>
                </div>
                <Target className="w-8 h-8 text-purple-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">高优先级</p>
                  <p className="text-2xl font-medium text-red-600 mt-1">
                    {suggestions.filter(s => s.priority === '高').length}
                  </p>
                </div>
                <AlertCircle className="w-8 h-8 text-red-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-orange-50 to-orange-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">中优先级</p>
                  <p className="text-2xl font-medium text-orange-600 mt-1">
                    {suggestions.filter(s => s.priority === '中').length}
                  </p>
                </div>
                <AlertTriangle className="w-8 h-8 text-orange-600 opacity-20" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">预估总金额</p>
                  <p className="text-xl font-medium text-green-600 mt-1">
                    ¥{suggestions.reduce((sum, s) => sum + s.estimatedAmount, 0).toLocaleString()}
                  </p>
                </div>
                <ShoppingCart className="w-8 h-8 text-green-600 opacity-20" />
              </div>
            </Card>
          </div>

          {/* 操作栏 */}
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <div className="flex items-center gap-2">
                  <Label>预测天数</Label>
                  <Select value={String(forecastDays)} onValueChange={(value) => setForecastDays(Number(value))}>
                    <SelectTrigger className="w-40">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="7">未来7天</SelectItem>
                      <SelectItem value="15">未来15天</SelectItem>
                      <SelectItem value="30">未来30天</SelectItem>
                      <SelectItem value="60">未来60天</SelectItem>
                      <SelectItem value="90">未来90天</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Button 
                  variant="outline"
                  onClick={handleRecalculateSuggestions}
                  disabled={isCalculating}
                >
                  {isCalculating ? (
                    <>
                      <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                      计算中...
                    </>
                  ) : (
                    <>
                      <Zap className="w-4 h-4 mr-2" />
                      重新计算
                    </>
                  )}
                </Button>
              </div>

              <div className="flex gap-2">
                {suggestions.length > 0 && (
                  <Badge className="bg-purple-100 text-purple-800 px-3 py-2">
                    <CheckCircle2 className="w-4 h-4 mr-2" />
                    共 {suggestions.length} 条建议，点击"加入采购计划"按钮进行处理
                  </Badge>
                )}
              </div>
            </div>
          </Card>

          {/* 建议列表 */}
          {suggestions.length === 0 ? (
            <Card className="p-12 text-center">
              <Target className="w-16 h-16 text-gray-400 mx-auto mb-4" />
              <h4 className="mb-2">暂无采购建议</h4>
              <p className="text-sm text-muted-foreground mb-4">
                当前所有物料库存充足，无需采购
              </p>
              <Button 
                variant="outline"
                onClick={handleRecalculateSuggestions}
              >
                <Zap className="w-4 h-4 mr-2" />
                重新计算建议
              </Button>
            </Card>
          ) : (
            <div className="space-y-4">
              {suggestions.map(sug => (
                <Card key={sug.id} className={`p-6 border-l-4 transition-all hover:shadow-lg ${
                  sug.priority === '高' ? 'border-l-red-500' :
                  sug.priority === '中' ? 'border-l-orange-500' :
                  'border-l-blue-500'
                }`}>
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-start gap-3 flex-1">
                      <div className={`p-3 rounded-lg ${
                        sug.priority === '高' ? 'bg-red-100' :
                        sug.priority === '中' ? 'bg-orange-100' :
                        'bg-blue-100'
                      }`}>
                        <Target className={`w-6 h-6 ${
                          sug.priority === '高' ? 'text-red-600' :
                          sug.priority === '中' ? 'text-orange-600' :
                          'text-blue-600'
                        }`} />
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{sug.materialName}</h4>
                          <Badge variant="outline">{sug.materialType}</Badge>
                          <Badge className={
                            sug.priority === '高' ? 'bg-red-100 text-red-800' :
                            sug.priority === '中' ? 'bg-orange-100 text-orange-800' :
                            'bg-blue-100 text-blue-800'
                          }>
                            {sug.priority}优先级
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          {sug.reason}
                        </p>
                      </div>
                    </div>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => handleViewSuggestionDetail(sug)}
                    >
                      <Eye className="w-4 h-4 mr-1" />
                      详情
                    </Button>
                  </div>

                  {/* 数据指标 */}
                  <div className="grid grid-cols-5 gap-3 mb-4">
                    <div className="p-3 bg-orange-50 rounded-lg border border-orange-200">
                      <div className="flex items-center gap-2 mb-1">
                        <Package className="w-4 h-4 text-orange-600" />
                        <p className="text-xs text-muted-foreground">当前库存</p>
                      </div>
                      <p className="text-xl font-medium text-orange-600">
                        {sug.currentStock} <span className="text-sm">{sug.unit}</span>
                      </p>
                      <div className="mt-1 h-1 bg-orange-200 rounded-full overflow-hidden">
                        <div 
                          className="h-full bg-orange-500" 
                          style={{ width: `${Math.min((sug.currentStock / sug.safeStock) * 100, 100)}%` }}
                        />
                      </div>
                    </div>

                    <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center gap-2 mb-1">
                        <CheckCircle2 className="w-4 h-4 text-green-600" />
                        <p className="text-xs text-muted-foreground">安全库存</p>
                      </div>
                      <p className="text-xl font-medium text-green-600">
                        {sug.safeStock} <span className="text-sm">{sug.unit}</span>
                      </p>
                    </div>

                    <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                      <div className="flex items-center gap-2 mb-1">
                        <TrendingDown className="w-4 h-4 text-blue-600" />
                        <p className="text-xs text-muted-foreground">日均消耗</p>
                      </div>
                      <p className="text-xl font-medium text-blue-600">
                        {sug.avgDailyConsumption} <span className="text-sm">{sug.unit}/天</span>
                      </p>
                    </div>

                    <div className="p-3 bg-purple-50 rounded-lg border border-purple-200">
                      <div className="flex items-center gap-2 mb-1">
                        <Calendar className="w-4 h-4 text-purple-600" />
                        <p className="text-xs text-muted-foreground">预测消耗</p>
                      </div>
                      <p className="text-xl font-medium text-purple-600">
                        {sug.forecastConsumption} <span className="text-sm">{sug.unit}</span>
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        未来{sug.forecastDays}天
                      </p>
                    </div>

                    <div className="p-3 bg-yellow-50 rounded-lg border-2 border-yellow-400">
                      <div className="flex items-center gap-2 mb-1">
                        <ShoppingCart className="w-4 h-4 text-yellow-600" />
                        <p className="text-xs font-medium text-yellow-900">建议采购</p>
                      </div>
                      <p className="text-2xl font-bold text-yellow-600">
                        {sug.suggestedQuantity}
                      </p>
                      <p className="text-xs text-yellow-600 mt-1">{sug.unit}</p>
                    </div>
                  </div>

                  {/* 底部操作区 */}
                  <div className="flex items-center justify-between p-4 bg-gradient-to-r from-green-50 to-blue-50 rounded-lg border border-green-200">
                    <div>
                      <p className="text-sm text-muted-foreground mb-1">预估采购金额</p>
                      <p className="text-2xl font-medium text-green-600">
                        ¥{sug.estimatedAmount.toLocaleString()}
                      </p>
                      <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1">
                        <Barcode className="w-3 h-3" />
                        基于上次采购价 ¥{sug.lastPurchasePrice}/{sug.unit}
                      </p>
                    </div>
                    <Button 
                      className="bg-green-600 hover:bg-green-700"
                      onClick={() => handleAddToPurchasePlan(sug)}
                    >
                      <Plus className="w-4 h-4 mr-2" />
                      加入采购计划
                    </Button>
                  </div>

                  {/* 计算公式提示 */}
                  <div className="mt-3 p-3 bg-blue-50 rounded border border-blue-200">
                    <div className="flex items-start gap-2">
                      <FileText className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                      <div className="text-xs text-blue-900">
                        <strong>计算逻辑：</strong> 建议采购量 = 安全库存({sug.safeStock}) + 预测消耗({sug.forecastConsumption}) - 当前库存({sug.currentStock}) = {sug.suggestedQuantity} {sug.unit}
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

      {/* 加入采购计划对话框 */}
      <Dialog open={showAddPlanDialog} onOpenChange={setShowAddPlanDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ShoppingCart className="w-5 h-5 text-green-600" />
              加入采购计划
            </DialogTitle>
            <DialogDescription>
              将选中的物料建议加入到采购计划中，系统将自动创建采购计划单
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 计划基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>计划单号 *</Label>
                <Input
                  value={planFormData.planNo}
                  onChange={(e) => setPlanFormData({ ...planFormData, planNo: e.target.value })}
                  placeholder="系统自动生成"
                  disabled
                />
              </div>

              <div>
                <Label>供应商 *</Label>
                <Select
                  value={planFormData.supplierId}
                  onValueChange={(value) => setPlanFormData({ ...planFormData, supplierId: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择供应商" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="sup-1">北方农资有限公司</SelectItem>
                    <SelectItem value="sup-2">绿野化肥集团</SelectItem>
                    <SelectItem value="sup-3">现代农药科技</SelectItem>
                    <SelectItem value="sup-4">金穗种业公司</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>期望交货日期 *</Label>
                <Input
                  type="date"
                  value={planFormData.expectedDate}
                  onChange={(e) => setPlanFormData({ ...planFormData, expectedDate: e.target.value })}
                />
              </div>

              <div>
                <Label>计划状态</Label>
                <div className="field-value">
                  <Badge className="bg-blue-100 text-blue-800">待审批</Badge>
                </div>
              </div>
            </div>

            <div>
              <Label>备注说明</Label>
              <Textarea
                value={planFormData.notes}
                onChange={(e) => setPlanFormData({ ...planFormData, notes: e.target.value })}
                placeholder="填写备注信息（可选）"
                rows={3}
              />
            </div>

            {/* 物料列表 */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <Label>物料明细</Label>
                <Badge className="bg-purple-100 text-purple-800">
                  共 {selectedSuggestions.length} 个物料
                </Badge>
              </div>

              <div className="border rounded-lg overflow-hidden">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="text-left p-3 border-b">序号</th>
                      <th className="text-left p-3 border-b">物料名称</th>
                      <th className="text-left p-3 border-b">类型</th>
                      <th className="text-right p-3 border-b">当前库存</th>
                      <th className="text-right p-3 border-b">安全库存</th>
                      <th className="text-right p-3 border-b">建议数量</th>
                      <th className="text-right p-3 border-b">预估单价</th>
                      <th className="text-right p-3 border-b">预估金额</th>
                      <th className="text-left p-3 border-b">优先级</th>
                    </tr>
                  </thead>
                  <tbody>
                    {selectedSuggestions.map((sug, index) => (
                      <tr key={sug.id} className="border-b last:border-b-0 hover:bg-gray-50">
                        <td className="p-3">{index + 1}</td>
                        <td className="p-3">
                          <div>
                            <p className="font-medium">{sug.materialName}</p>
                            <p className="text-xs text-muted-foreground">{sug.reason}</p>
                          </div>
                        </td>
                        <td className="p-3">
                          <Badge variant="outline">{sug.materialType}</Badge>
                        </td>
                        <td className="text-right p-3 text-orange-600">
                          {sug.currentStock} {sug.unit}
                        </td>
                        <td className="text-right p-3 text-green-600">
                          {sug.safeStock} {sug.unit}
                        </td>
                        <td className="text-right p-3 font-medium text-purple-600">
                          {sug.suggestedQuantity} {sug.unit}
                        </td>
                        <td className="text-right p-3">
                          ¥{sug.lastPurchasePrice}
                        </td>
                        <td className="text-right p-3 font-medium text-green-600">
                          ¥{sug.estimatedAmount.toLocaleString()}
                        </td>
                        <td className="p-3">
                          <Badge className={
                            sug.priority === '高' ? 'bg-red-100 text-red-800' :
                            sug.priority === '中' ? 'bg-orange-100 text-orange-800' :
                            'bg-blue-100 text-blue-800'
                          }>
                            {sug.priority}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                  <tfoot className="bg-green-50">
                    <tr>
                      <td colSpan={5} className="p-3 font-medium">合计</td>
                      <td className="text-right p-3 font-medium text-purple-600">
                        {selectedSuggestions.reduce((sum, s) => sum + s.suggestedQuantity, 0)} 件
                      </td>
                      <td className="text-right p-3">-</td>
                      <td className="text-right p-3 font-medium text-green-600">
                        ¥{selectedSuggestions.reduce((sum, s) => sum + s.estimatedAmount, 0).toLocaleString()}
                      </td>
                      <td className="p-3">-</td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </div>

            {/* 操作提示 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                <div className="text-sm text-blue-900">
                  <p className="font-medium mb-1">温馨提示：</p>
                  <ul className="space-y-1 text-xs">
                    <li>• 创建采购计划后，系统将自动生成计划单号，状态为"待审批"</li>
                    <li>• 计划需经过审批流程通过后，才能转为采购订单</li>
                    <li>• 建议数量和金额仅供参考，实际采购以订单为准</li>
                    <li>• 期望交货日期可根据实际情况与供应商协商调整</li>
                  </ul>
                </div>
              </div>
            </Card>

            {/* 底部操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => {
                  setShowAddPlanDialog(false);
                  setSelectedSuggestions([]);
                }}
              >
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSubmitPurchasePlan}
              >
                <Save className="w-4 h-4 mr-2" />
                确认创建
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 入库对话框 */}
      <Dialog open={showInboundDialog} onOpenChange={setShowInboundDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ArrowDownCircle className="w-5 h-5 text-green-600" />
              新增入库
            </DialogTitle>
            <DialogDescription>
              可基于已审批通过的采购订单生成入库单（自动加载多个物料），或手动创建入库单（可添加多个物料）
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 入库类型选择 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="inboundType"
                    value="order"
                    checked={inboundType === 'order'}
                    onChange={() => setInboundType('order')}
                    className="w-4 h-4"
                  />
                  <FileSearch className="w-4 h-4 text-blue-600" />
                  <span>基于采购订单</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="inboundType"
                    value="manual"
                    checked={inboundType === 'manual'}
                    onChange={() => setInboundType('manual')}
                    className="w-4 h-4"
                  />
                  <Edit className="w-4 h-4 text-green-600" />
                  <span>手动创建</span>
                </label>
              </div>
            </Card>

            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>入库仓库 *</Label>
                <Select
                  value={inboundFormData.warehouseId}
                  onValueChange={(value) => {
                    const warehouse = warehouses.find(w => w.id === value);
                    setInboundFormData({
                      ...inboundFormData,
                      warehouseId: value,
                      warehouseName: warehouse?.name || '',
                    });
                  }}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {warehouses.map(wh => (
                      <SelectItem key={wh.id} value={wh.id}>
                        {wh.name} ({wh.type})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>入库日期 *</Label>
                <Input
                  type="date"
                  value={inboundFormData.inboundDate}
                  onChange={(e) => setInboundFormData({
                    ...inboundFormData,
                    inboundDate: e.target.value,
                  })}
                />
              </div>
            </div>

            {/* 采购订单选择 */}
            {inboundType === 'order' && (
              <div>
                <Label>选择采购订单 *</Label>
                <Select
                  value={selectedOrderId}
                  onValueChange={handleSelectOrder}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="请选择已审批通过的采购订单" />
                  </SelectTrigger>
                  <SelectContent>
                    {availablePurchaseOrders
                      .filter(order => 
                        order.approvalStatus === '已通过' && 
                        order.status !== '已完成' && 
                        order.status !== '已取消'
                      )
                      .map(order => (
                        <SelectItem key={order.id} value={order.id}>
                          {order.orderNo} - {order.supplierName} - ¥{order.totalAmount.toLocaleString()}
                          {order.status === '部分到货' && ' (部分到货)'}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>

                {selectedOrderId && (
                  <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <div className="flex items-start gap-2">
                      <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5" />
                      <div className="text-sm text-green-900">
                        <p>供应商: {inboundFormData.supplierName}</p>
                        <p className="text-xs text-green-700 mt-1">
                          已自动加载订单中的{inboundItems.length}个物料，请填写每个物料的批次、日期和库位信息
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* 手动创建 - 供应商和物料选择 */}
            {inboundType === 'manual' && (
              <div className="space-y-4">
                <div>
                  <Label>供应商（可选）</Label>
                  <Select
                    value={inboundFormData.supplierId}
                    onValueChange={(value) => {
                      const supplier = suppliers.find(s => s.id === value);
                      setInboundFormData({
                        ...inboundFormData,
                        supplierId: value,
                        supplierName: supplier?.name || '',
                      });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择供应商（可选）" />
                    </SelectTrigger>
                    <SelectContent>
                      {suppliers.map(sup => (
                        <SelectItem key={sup.id} value={sup.id}>
                          {sup.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <div className="flex items-center justify-between mb-2">
                    <Label>添加入库物料 *</Label>
                    {inboundItems.length > 0 && (
                      <Badge className="bg-blue-100 text-blue-800">
                        已添加 {inboundItems.length} 个物料
                      </Badge>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <Select
                      onValueChange={(value) => {
                        handleAddManualMaterial(value);
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择要添加的农资物料" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableMaterials.map(material => (
                          <SelectItem key={material.id} value={material.id}>
                            {material.name} - {material.spec} - {material.type}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => {
                        toast.info('请从下拉列表中选择物料添加');
                      }}
                    >
                      <Plus className="w-4 h-4" />
                    </Button>
                  </div>
                  <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <div className="flex items-start gap-2">
                      <ListChecks className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                      <div className="text-xs text-blue-900">
                        <p className="mb-1">💡 支持添加多个物料：</p>
                        <ul className="space-y-0.5 text-blue-700">
                          <li>• 从下拉列表中选择物料后自动添加到下方列表</li>
                          <li>• 可重复选择添加多个不同的物料</li>
                          <li>• 每个物料可单独设置数量、批次、库位等信息</li>
                          <li>• 点击删除按钮可移除不需要的物料</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* 物料明细 */}
            {inboundItems.length > 0 && (
              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>入库物料明细</Label>
                  <Badge variant="outline" className="text-green-700 border-green-300">
                    共 {inboundItems.length} 个物料
                  </Badge>
                </div>
                <div className="mt-2 space-y-4">
                  {inboundItems.map((item, index) => (
                    <Card key={index} className="p-4">
                      <div className="flex items-start justify-between mb-3">
                        <div>
                          <h4 className="flex items-center gap-2">
                            {item.materialName}
                            <Badge variant="outline">{item.spec}</Badge>
                            {inboundType === 'manual' && (
                              <Badge className="bg-purple-100 text-purple-800">
                                手动添加
                              </Badge>
                            )}
                          </h4>
                          {inboundType === 'order' ? (
                            <p className="text-sm text-muted-foreground mt-1">
                              订单数量: {item.orderQuantity} {item.unit} | 
                              已入库: {item.receivedQuantity} {item.unit} | 
                              待入库: {item.remainingQuantity} {item.unit}
                            </p>
                          ) : (
                            <p className="text-sm text-muted-foreground mt-1">
                              单位: {item.unit}
                            </p>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          {inboundType === 'manual' && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => handleRemoveMaterialItem(index)}
                            >
                              <Trash2 className="w-4 h-4 text-red-600" />
                            </Button>
                          )}
                        </div>
                      </div>

                      <div className="grid grid-cols-3 gap-3">
                        <div>
                          <Label>本次入库数量 *</Label>
                          <Input
                            type="number"
                            value={item.inboundQuantity}
                            onChange={(e) => handleUpdateInboundItem(index, 'inboundQuantity', Number(e.target.value))}
                            min={1}
                            max={inboundType === 'order' ? item.remainingQuantity : undefined}
                          />
                          {inboundType === 'order' && (
                            <p className="text-xs text-muted-foreground mt-1">
                              最大可入库: {item.remainingQuantity} {item.unit}
                            </p>
                          )}
                        </div>

                        <div>
                          <Label>批次号 *</Label>
                          <Input
                            value={item.batchNo}
                            onChange={(e) => handleUpdateInboundItem(index, 'batchNo', e.target.value)}
                            placeholder="如: BATCH-2024-001"
                          />
                        </div>

                        <div>
                          <Label>库位 *</Label>
                          <Select
                            value={item.locationId}
                            onValueChange={(value) => handleUpdateInboundItem(index, 'locationId', value)}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="选择库位" />
                            </SelectTrigger>
                            <SelectContent>
                              {availableLocations
                                .filter(loc => loc.warehouse === inboundFormData.warehouseId)
                                .map(loc => (
                                  <SelectItem key={loc.id} value={loc.id}>
                                    {loc.code}
                                  </SelectItem>
                                ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div>
                          <Label>生产日期 *</Label>
                          <Input
                            type="date"
                            value={item.productionDate}
                            onChange={(e) => handleUpdateInboundItem(index, 'productionDate', e.target.value)}
                          />
                        </div>

                        <div>
                          <Label>有效期至 *</Label>
                          <Input
                            type="date"
                            value={item.expiryDate}
                            onChange={(e) => handleUpdateInboundItem(index, 'expiryDate', e.target.value)}
                          />
                        </div>

                        <div>
                          <Label>单价 *</Label>
                          {inboundType === 'manual' ? (
                            <Input
                              type="number"
                              value={item.unitPrice}
                              onChange={(e) => handleUpdateInboundItem(index, 'unitPrice', Number(e.target.value))}
                              min={0}
                              step={0.01}
                              placeholder="输入单价"
                            />
                          ) : (
                            <div className="field-value">
                              ¥{item.unitPrice}
                            </div>
                          )}
                        </div>

                        <div>
                          <Label>入库金额</Label>
                          <div className="field-value">
                            ¥{(item.inboundQuantity * item.unitPrice).toLocaleString()}
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>

                {/* 汇总信息 */}
                <Card className="p-4 bg-green-50 border-green-200 mt-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-muted-foreground">总物料项数</p>
                      <p className="text-xl font-medium">{inboundItems.length} 项</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">总入库数量</p>
                      <p className="text-xl font-medium">
                        {inboundItems.reduce((sum, item) => sum + item.inboundQuantity, 0)} 件
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">总入库金额</p>
                      <p className="text-2xl font-medium text-green-600">
                        ¥{inboundItems.reduce((sum, item) => sum + (item.inboundQuantity * item.unitPrice), 0).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </Card>
              </div>
            )}

            {/* 备注 */}
            <div>
              <Label>备注</Label>
              <Textarea
                value={inboundFormData.notes}
                onChange={(e) => setInboundFormData({
                  ...inboundFormData,
                  notes: e.target.value,
                })}
                placeholder="填写备注信息（可选）"
                rows={3}
              />
            </div>

            {/* 操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => {
                  setShowInboundDialog(false);
                  setInboundType('order');
                  setSelectedOrderId('');
                  setInboundItems([]);
                }}
              >
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSubmitInbound}
                disabled={inboundItems.length === 0}
              >
                <Save className="w-4 h-4 mr-2" />
                确认入库
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 审批确认对话框 */}
      <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {approvalAction === 'approve' ? (
                <>
                  <CheckCircle2 className="w-5 h-5 text-green-600" />
                  审批通过确认
                </>
              ) : (
                <>
                  <XCircle className="w-5 h-5 text-red-600" />
                  驳回确认
                </>
              )}
            </DialogTitle>
            <DialogDescription>
              {approvalAction === 'approve' 
                ? `确认审批通过该${selectedRecord?.recordNo?.startsWith('OUT-') ? '出库单' : '入库单'}？审批后将无法撤销。`
                : `确认驳回该${selectedRecord?.recordNo?.startsWith('OUT-') ? '出库单' : '入库单'}？驳回后需要重新提交审批。`
              }
            </DialogDescription>
          </DialogHeader>

          {selectedRecord && (
            <div className="space-y-4 mt-4">
              {/* 入库单基本信息 */}
              <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">{selectedRecord.recordNo}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">入库类型：</span>
                    <Badge variant="outline">{selectedRecord.type}</Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">仓库：</span>
                    <span>{selectedRecord.warehouseName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">供应商：</span>
                    <span>{selectedRecord.supplierName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">入库日期：</span>
                    <span>{selectedRecord.inboundDate}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">操作人：</span>
                    <span>{selectedRecord.operator}</span>
                  </div>
                  {selectedRecord.orderNo && (
                    <div className="col-span-2">
                      <span className="text-muted-foreground">关联订单：</span>
                      <span className="text-blue-600">{selectedRecord.orderNo}</span>
                    </div>
                  )}
                </div>
              </Card>

              {/* 物料明细 */}
              <div>
                <Label>入库物料明细</Label>
                <div className="mt-2 max-h-60 overflow-y-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-100 sticky top-0">
                      <tr>
                        <th className="text-left p-2">物料名称</th>
                        <th className="text-left p-2">规格</th>
                        <th className="text-right p-2">数量</th>
                        <th className="text-right p-2">单价</th>
                        <th className="text-right p-2">金额</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedRecord.items.map((item: InboundItem) => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{item.materialName}</td>
                          <td className="p-2">{item.spec}</td>
                          <td className="text-right p-2">{item.quantity} {item.unit}</td>
                          <td className="text-right p-2">¥{item.unitPrice}</td>
                          <td className="text-right p-2 font-medium">¥{item.amount.toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="mt-2 p-3 bg-green-50 rounded-lg flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">总计：</span>
                  <span className="text-xl font-medium text-green-600">
                    ¥{selectedRecord.totalAmount.toLocaleString()}
                  </span>
                </div>
              </div>

              {/* 审批意见 */}
              <div>
                <Label>{approvalAction === 'approve' ? '审批意见（可选）' : '驳回原因 *'}</Label>
                <Textarea
                  value={approvalNotes}
                  onChange={(e) => setApprovalNotes(e.target.value)}
                  placeholder={approvalAction === 'approve' ? '填写审批意见（可选）' : '请填写驳回原因'}
                  rows={3}
                  className="mt-2"
                />
              </div>

              {/* 警告提示 */}
              {approvalAction === 'approve' ? (
                <Card className="p-3 bg-green-50 border-green-200">
                  <div className="flex items-start gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5" />
                    <div className="text-xs text-green-900">
                      <p className="font-medium mb-1">审批通过后：</p>
                      <ul className="space-y-0.5">
                        <li>• 入库单状态将变更为"已审核"</li>
                        <li>• 库存数量将自动更新</li>
                        <li>• 如有关联采购订单，订单到货数量将更新</li>
                        <li>• 审批记录将被系统记录</li>
                      </ul>
                    </div>
                  </div>
                </Card>
              ) : (
                <Card className="p-3 bg-red-50 border-red-200">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-red-600 mt-0.5" />
                    <div className="text-xs text-red-900">
                      <p className="font-medium mb-1">驳回后：</p>
                      <ul className="space-y-0.5">
                        <li>• 入库单状态将变更为"已驳回"</li>
                        <li>• 需要修改后重新提交审批</li>
                        <li>• 驳回原因将通知操作人</li>
                      </ul>
                    </div>
                  </div>
                </Card>
              )}

              {/* 操作按钮 */}
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowApprovalDialog(false);
                    setSelectedRecord(null);
                    setApprovalNotes('');
                  }}
                >
                  取消
                </Button>
                <Button
                  className={approvalAction === 'approve' ? 'bg-green-600 hover:bg-green-700' : 'bg-red-600 hover:bg-red-700'}
                  onClick={handleSubmitApproval}
                  disabled={approvalAction === 'reject' && !approvalNotes.trim()}
                >
                  {approvalAction === 'approve' ? (
                    <>
                      <CheckCircle2 className="w-4 h-4 mr-2" />
                      确认通过
                    </>
                  ) : (
                    <>
                      <XCircle className="w-4 h-4 mr-2" />
                      确认驳回
                    </>
                  )}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              {selectedRecord?.recordNo?.startsWith('OUT-') ? '出库单详情' : '入库单详情'}
            </DialogTitle>
            <DialogDescription>
              查看完整的{selectedRecord?.recordNo?.startsWith('OUT-') ? '出库单' : '入库单'}信息和物料明细
            </DialogDescription>
          </DialogHeader>

          {selectedRecord && (
            <div className="space-y-6 mt-4">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">基本信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label>{selectedRecord.recordNo?.startsWith('OUT-') ? '出库单号' : '入库单号'}</Label>
                    <div className="field-value">{selectedRecord.recordNo}</div>
                  </div>
                  <div>
                    <Label>{selectedRecord.recordNo?.startsWith('OUT-') ? '出库类型' : '入库类型'}</Label>
                    <div className="field-value">
                      <Badge variant="outline">{selectedRecord.type}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>状态</Label>
                    <div className="field-value">
                      <Badge 
                        className={
                          selectedRecord.status === '已审核' 
                            ? 'bg-green-100 text-green-800' 
                            : selectedRecord.status === '待审核'
                            ? 'bg-orange-100 text-orange-800'
                            : 'bg-red-100 text-red-800'
                        }
                      >
                        {selectedRecord.status}
                      </Badge>
                    </div>
                  </div>
                  {selectedRecord.recordNo?.startsWith('OUT-') ? (
                    <>
                      <div>
                        <Label>出库仓库</Label>
                        <div className="field-value">{selectedRecord.warehouseName}</div>
                      </div>
                      {selectedRecord.targetWarehouseName && (
                        <div>
                          <Label>入库仓库</Label>
                          <div className="field-value">{selectedRecord.targetWarehouseName}</div>
                        </div>
                      )}
                      <div>
                        <Label>领用人/客户</Label>
                        <div className="field-value">
                          {selectedRecord.recipient}
                          <Badge variant="outline" className="ml-2 text-xs">
                            {selectedRecord.recipientType}
                          </Badge>
                        </div>
                      </div>
                      <div>
                        <Label>出库用途</Label>
                        <div className="field-value">{selectedRecord.purpose}</div>
                      </div>
                      {selectedRecord.fieldName && (
                        <div>
                          <Label>关联地块</Label>
                          <div className="field-value text-purple-600">{selectedRecord.fieldName}</div>
                        </div>
                      )}
                      {selectedRecord.taskName && (
                        <div>
                          <Label>关联任务</Label>
                          <div className="field-value text-purple-600">{selectedRecord.taskName}</div>
                        </div>
                      )}
                      <div>
                        <Label>出库日期</Label>
                        <div className="field-value">{selectedRecord.outboundDate}</div>
                      </div>
                    </>
                  ) : (
                    <>
                      {selectedRecord.orderNo && (
                        <div>
                          <Label>关联采购订单</Label>
                          <div className="field-value text-blue-600">{selectedRecord.orderNo}</div>
                        </div>
                      )}
                      <div>
                        <Label>仓库</Label>
                        <div className="field-value">{selectedRecord.warehouseName}</div>
                      </div>
                      <div>
                        <Label>供应商</Label>
                        <div className="field-value">{selectedRecord.supplierName || '-'}</div>
                      </div>
                      <div>
                        <Label>入库日期</Label>
                        <div className="field-value">{selectedRecord.inboundDate}</div>
                      </div>
                    </>
                  )}
                  <div>
                    <Label>操作人</Label>
                    <div className="field-value">{selectedRecord.operator}</div>
                  </div>
                  <div>
                    <Label>创建时间</Label>
                    <div className="field-value">{selectedRecord.createdAt}</div>
                  </div>
                </div>
                {selectedRecord.notes && (
                  <div className="mt-4">
                    <Label>备注</Label>
                    <div className="field-value">{selectedRecord.notes}</div>
                  </div>
                )}
              </div>

              {/* 物料明细 */}
              <div>
                <div className="flex items-center justify-between mb-4 pb-2 border-b">
                  <h4>物料明细</h4>
                  <span className="text-sm text-muted-foreground">
                    共 {selectedRecord.items.length} 项物料
                  </span>
                </div>
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-left p-3 border-b">序号</th>
                        <th className="text-left p-3 border-b">物料名称</th>
                        <th className="text-left p-3 border-b">规格</th>
                        <th className="text-right p-3 border-b">数量</th>
                        <th className="text-left p-3 border-b">批次号</th>
                        {selectedRecord.recordNo?.startsWith('IN-') && (
                          <>
                            <th className="text-left p-3 border-b">生产日期</th>
                            <th className="text-left p-3 border-b">有效期至</th>
                          </>
                        )}
                        <th className="text-left p-3 border-b">库位</th>
                        <th className="text-right p-3 border-b">单价(¥)</th>
                        <th className="text-right p-3 border-b">金额(¥)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedRecord.items.map((item: any, index: number) => (
                        <tr key={item.id} className="border-b hover:bg-gray-50">
                          <td className="p-3">{index + 1}</td>
                          <td className="p-3 font-medium">{item.materialName}</td>
                          <td className="p-3 text-muted-foreground">{item.spec}</td>
                          <td className="text-right p-3">
                            <span className="font-medium">{item.quantity}</span>
                            <span className="text-muted-foreground ml-1">{item.unit}</span>
                          </td>
                          <td className="p-3">
                            <Badge variant="outline" className="text-xs font-mono">
                              {item.batchNo}
                            </Badge>
                          </td>
                          {selectedRecord.recordNo?.startsWith('IN-') && (
                            <>
                              <td className="p-3 text-muted-foreground">{item.productionDate}</td>
                              <td className="p-3 text-muted-foreground">{item.expiryDate}</td>
                            </>
                          )}
                          <td className="p-3">
                            <Badge variant="outline" className="text-xs">
                              {item.locationCode || '未分配'}
                            </Badge>
                          </td>
                          <td className="text-right p-3 text-muted-foreground">
                            {item.unitPrice.toLocaleString()}
                          </td>
                          <td className="text-right p-3 font-medium">
                            {item.amount.toLocaleString()}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 金额汇总 */}
                <Card className="mt-4 p-4 bg-green-50 border-green-200">
                  <div className="flex items-center justify-between">
                    <div className="space-y-1">
                      <p className="text-sm text-muted-foreground">物料总数量</p>
                      <p className="text-lg font-medium">
                        {selectedRecord.items.reduce((sum: number, item: InboundItem) => sum + item.quantity, 0)} 件
                      </p>
                    </div>
                    <div className="space-y-1 text-right">
                      <p className="text-sm text-muted-foreground">入库总金额</p>
                      <p className="text-2xl font-medium text-green-600">
                        ¥{selectedRecord.totalAmount.toLocaleString()}
                      </p>
                    </div>
                  </div>
                </Card>
              </div>

              {/* 底部操作按钮 */}
              <div className="flex justify-end pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowDetailDialog(false)}
                >
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 出库创建对话框 */}
      <Dialog open={showOutboundDialog} onOpenChange={setShowOutboundDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ArrowUpCircle className="w-5 h-5 text-blue-600" />
              新增出库
            </DialogTitle>
            <DialogDescription>
              填写出库信息，系统将自动按先进先出(FIFO)原则选择批次
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>出库类型 *</Label>
                <Select
                  value={outboundFormData.type}
                  onValueChange={(value: any) => setOutboundFormData({
                    ...outboundFormData,
                    type: value,
                  })}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="生产领用">生产领用</SelectItem>
                    <SelectItem value="销售出库">销售出库</SelectItem>
                    <SelectItem value="调拨出库">调拨出库</SelectItem>
                    <SelectItem value="其他出库">其他出库</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>出库仓库 *</Label>
                <Select
                  value={outboundFormData.warehouseId}
                  onValueChange={(value) => {
                    const warehouse = warehouses.find(w => w.id === value);
                    setOutboundFormData({
                      ...outboundFormData,
                      warehouseId: value,
                      warehouseName: warehouse?.name || '',
                    });
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {warehouses.map(wh => (
                      <SelectItem key={wh.id} value={wh.id}>
                        {wh.name} ({wh.type})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 调拨出库时显示入库仓库 */}
              {outboundFormData.type === '调拨出库' && (
                <div>
                  <Label>入库仓库 *</Label>
                  <Select
                    value={outboundFormData.targetWarehouseId}
                    onValueChange={(value) => {
                      const warehouse = warehouses.find(w => w.id === value);
                      setOutboundFormData({
                        ...outboundFormData,
                        targetWarehouseId: value,
                        targetWarehouseName: warehouse?.name || '',
                      });
                    }}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择入库仓库" />
                    </SelectTrigger>
                    <SelectContent>
                      {warehouses
                        .filter(wh => wh.id !== outboundFormData.warehouseId)
                        .map(wh => (
                          <SelectItem key={wh.id} value={wh.id}>
                            {wh.name} ({wh.type})
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              <div>
                <Label>领用人/客户类型 *</Label>
                <Select
                  value={outboundFormData.recipientType}
                  onValueChange={(value: any) => setOutboundFormData({
                    ...outboundFormData,
                    recipientType: value,
                    recipient: '',
                  })}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="员工">员工</SelectItem>
                    <SelectItem value="客户">客户</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>领用人/客户 *</Label>
                {outboundFormData.recipientType === '员工' ? (
                  <Select
                    value={outboundFormData.recipient}
                    onValueChange={(value) => setOutboundFormData({
                      ...outboundFormData,
                      recipient: value,
                    })}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择员工" />
                    </SelectTrigger>
                    <SelectContent>
                      {employeeList.map(emp => (
                        <SelectItem key={emp.id} value={emp.name}>
                          {emp.name} - {emp.department} - {emp.position}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : outboundFormData.recipientType === '客户' ? (
                  <Select
                    value={outboundFormData.recipient}
                    onValueChange={(value) => setOutboundFormData({
                      ...outboundFormData,
                      recipient: value,
                    })}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择客户" />
                    </SelectTrigger>
                    <SelectContent>
                      {customerList.map(cust => (
                        <SelectItem key={cust.id} value={cust.name}>
                          {cust.name} - {cust.type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <Input
                    className="mt-2"
                    value={outboundFormData.recipient}
                    onChange={(e) => setOutboundFormData({
                      ...outboundFormData,
                      recipient: e.target.value,
                    })}
                    placeholder="输入领用人姓名"
                  />
                )}
              </div>

              <div>
                <Label>出库日期 *</Label>
                <Input
                  type="date"
                  className="mt-2"
                  value={outboundFormData.outboundDate}
                  onChange={(e) => setOutboundFormData({
                    ...outboundFormData,
                    outboundDate: e.target.value,
                  })}
                />
              </div>

              <div>
                <Label>出库用途 *</Label>
                <Input
                  className="mt-2"
                  value={outboundFormData.purpose}
                  onChange={(e) => setOutboundFormData({
                    ...outboundFormData,
                    purpose: e.target.value,
                  })}
                  placeholder="如: 春季播种、病虫害防治等"
                />
              </div>

              <div>
                <Label>关联地块（可选）</Label>
                <Select
                  value={outboundFormData.fieldId}
                  onValueChange={(value) => {
                    const field = fieldList.find(f => f.id === value);
                    setOutboundFormData({
                      ...outboundFormData,
                      fieldId: value,
                      fieldName: field?.name || '',
                    });
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择地块（可选）" />
                  </SelectTrigger>
                  <SelectContent>
                    {fieldList.map(field => (
                      <SelectItem key={field.id} value={field.id}>
                        {field.name} - {field.crop} ({field.area}亩)
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>关联任务（可选）</Label>
                <Select
                  value={outboundFormData.taskId}
                  onValueChange={(value) => {
                    const task = taskList.find(t => t.id === value);
                    setOutboundFormData({
                      ...outboundFormData,
                      taskId: value,
                      taskName: task?.name || '',
                    });
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择任务（可选）" />
                  </SelectTrigger>
                  <SelectContent>
                    {taskList.map(task => (
                      <SelectItem key={task.id} value={task.id}>
                        {task.name} - {task.fieldName} ({task.status})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 出库物料 */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label>出库物料 *</Label>
                {outboundItems.length > 0 && (
                  <Badge className="bg-blue-100 text-blue-800">
                    已添加 {outboundItems.length} 个物料
                  </Badge>
                )}
              </div>
              
              <div className="flex gap-2 mb-4">
                <Select
                  value={selectedMaterialId}
                  onValueChange={setSelectedMaterialId}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择物料（系统自动选择最早批次）" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableStockBatches
                      .filter((batch, index, self) => 
                        index === self.findIndex(b => b.materialId === batch.materialId)
                      )
                      .map(batch => (
                        <SelectItem key={batch.materialId} value={batch.materialId}>
                          {batch.materialName} ({batch.spec}) - 可用库存: {
                            availableStockBatches
                              .filter(b => b.materialId === batch.materialId)
                              .reduce((sum, b) => sum + b.quantity, 0)
                          } {batch.unit}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                <Button onClick={handleAddOutboundItem}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加
                </Button>
              </div>

              {outboundItems.length > 0 && (
                <div className="space-y-3">
                  {outboundItems.map(item => (
                    <Card key={item.id} className="p-4">
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex-1">
                          <h4 className="mb-1">{item.materialName}</h4>
                          <p className="text-sm text-muted-foreground">
                            规格: {item.spec} | 批次: {item.batchNo} | 库位: {item.locationCode}
                          </p>
                          <p className="text-xs text-purple-600 mt-1">
                            生产日期: {item.productionDate} | 有效期至: {item.expiryDate}
                          </p>
                        </div>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleRemoveOutboundItem(item.id)}
                        >
                          <Trash2 className="w-4 h-4 text-red-600" />
                        </Button>
                      </div>

                      <div className="grid grid-cols-4 gap-4">
                        <div>
                          <Label className="text-xs">可用数量</Label>
                          <div className="field-value text-xs">
                            {item.availableQuantity} {item.unit}
                          </div>
                        </div>

                        <div>
                          <Label className="text-xs">出库数量 *</Label>
                          <Input
                            type="number"
                            value={item.quantity}
                            onChange={(e) => handleUpdateOutboundQuantity(item.id, parseInt(e.target.value) || 1)}
                            min={1}
                            max={item.availableQuantity}
                            className="mt-1"
                          />
                        </div>

                        <div>
                          <Label className="text-xs">单价</Label>
                          <div className="field-value text-xs">
                            ¥{item.unitPrice.toLocaleString()}
                          </div>
                        </div>

                        <div>
                          <Label className="text-xs">出库金额</Label>
                          <div className="field-value text-xs">
                            ¥{item.amount.toLocaleString()}
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}

              {/* 汇总信息 */}
              {outboundItems.length > 0 && (
                <Card className="p-4 bg-blue-50 border-blue-200 mt-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-muted-foreground">总物料项数</p>
                      <p className="text-xl font-medium">{outboundItems.length} 项</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">总出库数量</p>
                      <p className="text-xl font-medium">
                        {outboundItems.reduce((sum, item) => sum + item.quantity, 0)} 件
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">总出库金额</p>
                      <p className="text-2xl font-medium text-blue-600">
                        ¥{outboundItems.reduce((sum, item) => sum + item.amount, 0).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </Card>
              )}
            </div>

            {/* 备注 */}
            <div>
              <Label>备注</Label>
              <Textarea
                value={outboundFormData.notes}
                onChange={(e) => setOutboundFormData({
                  ...outboundFormData,
                  notes: e.target.value,
                })}
                placeholder="填写备注信息（可选）"
                rows={3}
                className="mt-2"
              />
            </div>

            {/* 操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => {
                  setShowOutboundDialog(false);
                  setOutboundFormData({
                    type: '生产领用',
                    warehouseId: 'wh-1',
                    warehouseName: '1号仓库',
                    recipient: '',
                    recipientType: '员工',
                    purpose: '',
                    fieldId: '',
                    fieldName: '',
                    taskId: '',
                    taskName: '',
                    outboundDate: new Date().toISOString().split('T')[0],
                    notes: '',
                  });
                  setOutboundItems([]);
                  setSelectedMaterialId('');
                }}
              >
                取消
              </Button>
              <Button
                className="bg-blue-600 hover:bg-blue-700"
                onClick={handleSubmitOutbound}
                disabled={outboundItems.length === 0}
              >
                <Save className="w-4 h-4 mr-2" />
                确认出库
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 盘点任务创建对话框 */}
      <Dialog open={showCheckDialog} onOpenChange={setShowCheckDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ClipboardList className="w-5 h-5 text-purple-600" />
              创建盘点任务
            </DialogTitle>
            <DialogDescription>
              创建库存盘点任务，系统将自动生成盘盈盘亏记录，审批后调整账面库存
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>任务名称 *</Label>
                <Input
                  className="mt-2"
                  value={checkFormData.taskName}
                  onChange={(e) => setCheckFormData({
                    ...checkFormData,
                    taskName: e.target.value,
                  })}
                  placeholder="如: 2024年3月月度盘点"
                />
              </div>

              <div>
                <Label>盘点类型 *</Label>
                <Select
                  value={checkFormData.checkType}
                  onValueChange={(value: any) => {
                    setCheckFormData({
                      ...checkFormData,
                      checkType: value,
                    });
                    // 切换盘点类型时，重新初始化选中状态
                    if (checkItems.length > 0) {
                      const isFullCheck = value === '全盘';
                      setCheckItems(checkItems.map(item => ({ ...item, selected: isFullCheck })));
                    }
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="全盘">全盘（全部盘点）</SelectItem>
                    <SelectItem value="抽盘">抽盘（抽样盘点）</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>盘点仓库 *</Label>
                <Select
                  value={checkFormData.warehouseId}
                  onValueChange={(value) => {
                    const warehouse = warehouses.find(w => w.id === value);
                    setCheckFormData({
                      ...checkFormData,
                      warehouseId: value,
                      warehouseName: warehouse?.name || '',
                    });
                    setCheckItems([]); // 切换仓库时清空已有盘点项
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {warehouses.map(wh => (
                      <SelectItem key={wh.id} value={wh.id}>
                        {wh.name} ({wh.type})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>计划日期 *</Label>
                <Input
                  type="date"
                  className="mt-2"
                  value={checkFormData.planDate}
                  onChange={(e) => setCheckFormData({
                    ...checkFormData,
                    planDate: e.target.value,
                  })}
                />
              </div>
            </div>

            {/* 盘点物料 */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label>盘点物料</Label>
                {checkItems.length > 0 && (
                  <div className="flex items-center gap-2">
                    {checkFormData.checkType === '抽盘' && (
                      <Badge className="bg-blue-100 text-blue-800">
                        已选 {checkItems.filter(i => i.selected).length} / {checkItems.length} 个
                      </Badge>
                    )}
                    <Badge className="bg-purple-100 text-purple-800">
                      已加载 {checkItems.length} 个物料
                    </Badge>
                  </div>
                )}
              </div>

              {checkItems.length === 0 ? (
                <Card className="p-6 text-center">
                  <Package className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                  <p className="text-muted-foreground mb-4">
                    点击下方按钮初始化盘点物料，系统将自动加载仓库中的所有物料
                  </p>
                  <Button onClick={handleInitCheckItems}>
                    <Plus className="w-4 h-4 mr-2" />
                    初始化盘点物料
                  </Button>
                </Card>
              ) : (
                <div className="border rounded-lg overflow-hidden">
                  <div className="max-h-96 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="bg-gray-50 sticky top-0">
                        <tr>
                          {checkFormData.checkType === '抽盘' && (
                            <th className="text-center p-2 w-12">
                              <input
                                type="checkbox"
                                checked={checkItems.every(item => item.selected)}
                                onChange={(e) => handleToggleAllCheckItems(e.target.checked)}
                                className="w-4 h-4 cursor-pointer"
                              />
                            </th>
                          )}
                          <th className="text-left p-2">物料名称</th>
                          <th className="text-left p-2">规格</th>
                          <th className="text-left p-2">库位</th>
                          <th className="text-left p-2">批次号</th>
                          <th className="text-right p-2">账面数量</th>
                          <th className="text-left p-2">状态</th>
                        </tr>
                      </thead>
                      <tbody>
                        {checkItems.map(item => (
                          <tr key={item.id} className="border-t">
                            {checkFormData.checkType === '抽盘' && (
                              <td className="text-center p-2">
                                <input
                                  type="checkbox"
                                  checked={item.selected || false}
                                  onChange={() => handleToggleCheckItem(item.id)}
                                  className="w-4 h-4 cursor-pointer"
                                />
                              </td>
                            )}
                            <td className="p-2">{item.materialName}</td>
                            <td className="p-2">{item.spec}</td>
                            <td className="p-2">
                              <Badge variant="outline" className="text-xs">
                                {item.locationCode}
                              </Badge>
                            </td>
                            <td className="p-2">
                              <Badge variant="outline" className="text-xs">
                                {item.batchNo}
                              </Badge>
                            </td>
                            <td className="text-right p-2">
                              {item.bookQuantity} {item.unit}
                            </td>
                            <td className="p-2">
                              <Badge className="bg-blue-100 text-blue-800">
                                {item.status}
                              </Badge>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* 统计信息 */}
                  <div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 border-t">
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">
                        {checkFormData.checkType === '抽盘' ? '待盘点项数' : '盘点总项数'}
                      </p>
                      <p className="text-lg font-medium">
                        {checkFormData.checkType === '抽盘' 
                          ? `${checkItems.filter(i => i.selected).length} 项`
                          : `${checkItems.length} 项`
                        }
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">物料总数</p>
                      <p className="text-lg font-medium text-blue-600">
                        {checkItems.length} 项
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 备注 */}
            <div>
              <Label>备注</Label>
              <Textarea
                value={checkFormData.notes}
                onChange={(e) => setCheckFormData({
                  ...checkFormData,
                  notes: e.target.value,
                })}
                placeholder="填写备注信息（可选）"
                rows={3}
                className="mt-2"
              />
            </div>

            {/* 操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => {
                  setShowCheckDialog(false);
                  setCheckFormData({
                    taskName: '',
                    warehouseId: 'wh-1',
                    warehouseName: '1号仓库',
                    checkType: '全盘',
                    planDate: new Date().toISOString().split('T')[0],
                    checker: '当前用户',
                    notes: '',
                  });
                  setCheckItems([]);
                }}
              >
                取消
              </Button>
              <Button
                className="bg-purple-600 hover:bg-purple-700"
                onClick={handleSubmitCheck}
                disabled={checkItems.length === 0}
              >
                <Save className="w-4 h-4 mr-2" />
                确认创建
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 盘点录入对话框 */}
      <Dialog open={showCheckInputDialog} onOpenChange={setShowCheckInputDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5 text-blue-600" />
              盘点录入
            </DialogTitle>
            <DialogDescription>
              现场盘点后，录入实盘数量。系统将自动计算差异和盘盈盘亏情况。
            </DialogDescription>
          </DialogHeader>

          {selectedCheckTask && (
            <div className="space-y-6 mt-4">
              {/* 任务信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">任务名称</p>
                    <p className="mt-1 font-medium">{selectedCheckTask.taskName}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">任务编号</p>
                    <p className="mt-1 font-medium">{selectedCheckTask.taskNo}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">仓库</p>
                    <p className="mt-1 font-medium">{selectedCheckTask.warehouseName}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">盘点类型</p>
                    <p className="mt-1 font-medium">{selectedCheckTask.checkType}</p>
                  </div>
                </div>
              </Card>

              {/* 盘点物料表格 */}
              <div>
                <div className="flex items-center justify-between mb-4">
                  <h4>盘点物料列表</h4>
                  <Badge className="bg-blue-100 text-blue-800">
                    共 {inputCheckItems.length} 个物料
                  </Badge>
                </div>

                <div className="border rounded-lg overflow-hidden">
                  <div className="max-h-96 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="bg-gray-50 sticky top-0">
                        <tr>
                          <th className="text-left p-2">物料名称</th>
                          <th className="text-left p-2">规格</th>
                          <th className="text-left p-2">库位</th>
                          <th className="text-left p-2">批次号</th>
                          <th className="text-right p-2">账面数量</th>
                          <th className="text-right p-2">实盘数量 *</th>
                          <th className="text-right p-2">差异</th>
                          <th className="text-left p-2">状态</th>
                        </tr>
                      </thead>
                      <tbody>
                        {inputCheckItems.map(item => (
                          <tr key={item.id} className="border-t">
                            <td className="p-2">{item.materialName}</td>
                            <td className="p-2">{item.spec}</td>
                            <td className="p-2">
                              <Badge variant="outline" className="text-xs">
                                {item.locationCode}
                              </Badge>
                            </td>
                            <td className="p-2">
                              <Badge variant="outline" className="text-xs">
                                {item.batchNo}
                              </Badge>
                            </td>
                            <td className="text-right p-2">
                              {item.bookQuantity} {item.unit}
                            </td>
                            <td className="text-right p-2">
                              <Input
                                type="number"
                                value={item.actualQuantity ?? ''}
                                onChange={(e) => handleUpdateInputCheckQuantity(
                                  item.id,
                                  e.target.value ? parseInt(e.target.value) : undefined
                                )}
                                min={0}
                                placeholder="请输入"
                                className="w-24 text-right"
                              />
                            </td>
                            <td className="text-right p-2">
                              {item.actualQuantity !== undefined ? (
                                <span className={
                                  item.difference > 0 ? 'text-green-600 font-medium' :
                                  item.difference < 0 ? 'text-red-600 font-medium' :
                                  'text-gray-600'
                                }>
                                  {item.difference > 0 ? '+' : ''}{item.difference} {item.unit}
                                </span>
                              ) : (
                                <span className="text-gray-400">-</span>
                              )}
                            </td>
                            <td className="p-2">
                              <Badge className={
                                item.status === '盘盈' ? 'bg-green-100 text-green-800' :
                                item.status === '盘亏' ? 'bg-red-100 text-red-800' :
                                item.status === '正常' ? 'bg-gray-100 text-gray-800' :
                                'bg-blue-100 text-blue-800'
                              }>
                                {item.status}
                              </Badge>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* 统计信息 */}
                  <div className="grid grid-cols-4 gap-4 p-4 bg-gray-50 border-t">
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">盘点总项数</p>
                      <p className="text-lg font-medium">
                        {inputCheckItems.length} 项
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">已录入</p>
                      <p className="text-lg font-medium text-blue-600">
                        {inputCheckItems.filter(i => i.actualQuantity !== undefined).length} 项
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">盘盈</p>
                      <p className="text-lg font-medium text-green-600">
                        {inputCheckItems.filter(i => i.status === '盘盈').length} 项
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-muted-foreground">盘亏</p>
                      <p className="text-lg font-medium text-red-600">
                        {inputCheckItems.filter(i => i.status === '盘亏').length} 项
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowCheckInputDialog(false);
                    setSelectedCheckTask(null);
                    setInputCheckItems([]);
                  }}
                >
                  取消
                </Button>
                <Button
                  className="bg-blue-600 hover:bg-blue-700"
                  onClick={handleSubmitCheckInput}
                >
                  <Send className="w-4 h-4 mr-2" />
                  提交审批
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 盘点详情对话框 */}
      <Dialog open={showCheckItemDialog} onOpenChange={setShowCheckItemDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ClipboardList className="w-5 h-5 text-purple-600" />
              盘点任务详情
            </DialogTitle>
            <DialogDescription>
              查看完整的盘点任务信息和盘点明细
            </DialogDescription>
          </DialogHeader>

          {selectedCheckTask && (
            <div className="space-y-6 mt-4">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">基本信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label>任务编号</Label>
                    <div className="field-value">{selectedCheckTask.taskNo}</div>
                  </div>
                  <div>
                    <Label>任务名称</Label>
                    <div className="field-value">{selectedCheckTask.taskName}</div>
                  </div>
                  <div>
                    <Label>盘点类型</Label>
                    <div className="field-value">
                      <Badge variant="outline">{selectedCheckTask.checkType}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>仓库</Label>
                    <div className="field-value">{selectedCheckTask.warehouseName}</div>
                  </div>
                  <div>
                    <Label>盘点人</Label>
                    <div className="field-value">{selectedCheckTask.checker}</div>
                  </div>
                  <div>
                    <Label>状态</Label>
                    <div className="field-value">
                      <Badge className={
                        selectedCheckTask.status === '已完成' ? 'bg-green-100 text-green-800' :
                        selectedCheckTask.status === '待审批' ? 'bg-orange-100 text-orange-800' :
                        'bg-blue-100 text-blue-800'
                      }>
                        {selectedCheckTask.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>计划日期</Label>
                    <div className="field-value">{selectedCheckTask.planDate}</div>
                  </div>
                  <div>
                    <Label>实际日期</Label>
                    <div className="field-value">{selectedCheckTask.actualDate}</div>
                  </div>
                  <div>
                    <Label>创建时间</Label>
                    <div className="field-value">{selectedCheckTask.createdAt}</div>
                  </div>
                </div>
              </div>

              {/* 盘点汇总 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">盘点汇总</h4>
                <div className="grid grid-cols-4 gap-4">
                  <Card className="p-4 bg-purple-50 border-purple-200">
                    <p className="text-sm text-muted-foreground">盘点总项数</p>
                    <p className="text-2xl font-medium text-purple-600 mt-1">
                      {selectedCheckTask.items.length} 项
                    </p>
                  </Card>
                  <Card className="p-4 bg-gray-50 border-gray-200">
                    <p className="text-sm text-muted-foreground">正常</p>
                    <p className="text-2xl font-medium text-gray-600 mt-1">
                      {selectedCheckTask.items.filter(i => i.status === '正常').length} 项
                    </p>
                  </Card>
                  <Card className="p-4 bg-green-50 border-green-200">
                    <p className="text-sm text-muted-foreground">盘盈</p>
                    <p className="text-2xl font-medium text-green-600 mt-1">
                      {selectedCheckTask.profit} 项
                    </p>
                  </Card>
                  <Card className="p-4 bg-red-50 border-red-200">
                    <p className="text-sm text-muted-foreground">盘亏</p>
                    <p className="text-2xl font-medium text-red-600 mt-1">
                      {selectedCheckTask.loss} 项
                    </p>
                  </Card>
                </div>
              </div>

              {/* 盘点明细 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">盘点明细</h4>
                <div className="border rounded-lg overflow-hidden">
                  <div className="max-h-96 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="bg-gray-50 sticky top-0">
                        <tr>
                          <th className="text-left p-3">物料名称</th>
                          <th className="text-left p-3">库位</th>
                          <th className="text-right p-3">账面数量</th>
                          <th className="text-right p-3">实盘数量</th>
                          <th className="text-right p-3">差异</th>
                          <th className="text-left p-3">状态</th>
                          <th className="text-left p-3">备注</th>
                        </tr>
                      </thead>
                      <tbody>
                        {selectedCheckTask.items.map(item => (
                          <tr key={item.id} className="border-t">
                            <td className="p-3">
                              <div>{item.materialName}</div>
                              <div className="text-xs text-muted-foreground">{item.spec}</div>
                            </td>
                            <td className="p-3">
                              <Badge variant="outline" className="text-xs">
                                {item.locationCode}
                              </Badge>
                            </td>
                            <td className="text-right p-3">
                              {item.bookQuantity} {item.unit}
                            </td>
                            <td className="text-right p-3">
                              {item.actualQuantity} {item.unit}
                            </td>
                            <td className="text-right p-3">
                              <span className={
                                item.difference > 0 ? 'text-green-600 font-medium' :
                                item.difference < 0 ? 'text-red-600 font-medium' :
                                'text-gray-600'
                              }>
                                {item.difference > 0 ? '+' : ''}{item.difference} {item.unit}
                              </span>
                            </td>
                            <td className="p-3">
                              <Badge className={
                                item.status === '盘盈' ? 'bg-green-100 text-green-800' :
                                item.status === '盘亏' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'
                              }>
                                {item.status}
                              </Badge>
                            </td>
                            <td className="p-3 text-xs">{item.notes || '-'}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>

              {/* 底部操作按钮 */}
              <div className="flex justify-between gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowCheckItemDialog(false)}
                >
                  关闭
                </Button>
                
                {selectedCheckTask.status === '待审批' && (
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      className="text-orange-600 hover:bg-orange-50"
                      onClick={() => setShowCheckRejectConfirm(true)}
                    >
                      <X className="w-4 h-4 mr-2" />
                      驳回
                    </Button>
                    <Button
                      className="bg-green-600 hover:bg-green-700"
                      onClick={() => setShowCheckApprovalConfirm(true)}
                    >
                      <CheckCircle2 className="w-4 h-4 mr-2" />
                      审批通过
                    </Button>
                  </div>
                )}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 预警设置对话框 */}
      <Dialog open={showWarningRuleDialog} onOpenChange={setShowWarningRuleDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5 text-orange-600" />
              库存预警设置
            </DialogTitle>
            <DialogDescription>
              配置安全库存阈值和预警规则，系统将定时检查并自动生成预警
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 预警规则说明 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <div className="flex items-start gap-2">
                <AlertCircle 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 font-medium">预警规则说明：</p>
                  <ul className="space-y-1 text-xs">
                    <li>• <strong>库存不足预警</strong>: 当前库存 &lt; 安全库存时触发预警</li>
                    <li>• <strong>预警级别</strong>: 高(&lt;30%)、中(30-60%)、低(60-100%)</li>
                    <li>• <strong>临期预警</strong>: 距离有效期≤30天时触发预警</li>
                    <li>• <strong>临期级别</strong>: 高(≤7天)、中(8-15天)、低(16-30天)</li>
                    <li>• <strong>检查频率</strong>: 系统每小时自动检查一次库存状态</li>
                    <li>• <strong>通知方式</strong>: 系统消息 + 短信 + 邮件（可配置）</li>
                  </ul>
                </div>
              </div>
            </Card>

            {/* 通知设置 */}
            <div>
              <h4 className="mb-4 pb-2 border-b">通知设置</h4>
              <div className="space-y-3">
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Bell className="w-5 h-5 text-orange-600" />
                    <div>
                      <p className="font-medium">系统消息通知</p>
                      <p className="text-xs text-muted-foreground">在系统消息中心显示预警</p>
                    </div>
                  </div>
                  <Switch
                    checked={warningNotificationSettings.systemMessage}
                    onCheckedChange={(checked) =>
                      setWarningNotificationSettings({
                        ...warningNotificationSettings,
                        systemMessage: checked,
                      })
                    }
                  />
                </div>

                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Smartphone className="w-5 h-5 text-blue-600" />
                    <div>
                      <p className="font-medium">短信通知</p>
                      <p className="text-xs text-muted-foreground">向库管和采购人员发送短信</p>
                    </div>
                  </div>
                  <Switch
                    checked={warningNotificationSettings.sms}
                    onCheckedChange={(checked) =>
                      setWarningNotificationSettings({
                        ...warningNotificationSettings,
                        sms: checked,
                      })
                    }
                  />
                </div>

                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Mail className="w-5 h-5 text-purple-600" />
                    <div>
                      <p className="font-medium">邮件通知</p>
                      <p className="text-xs text-muted-foreground">向相关人员发送邮件提醒</p>
                    </div>
                  </div>
                  <Switch
                    checked={warningNotificationSettings.email}
                    onCheckedChange={(checked) =>
                      setWarningNotificationSettings({
                        ...warningNotificationSettings,
                        email: checked,
                      })
                    }
                  />
                </div>
              </div>
            </div>

            {/* 通知对象设置 */}
            <div>
              <h4 className="mb-4 pb-2 border-b">通知对象</h4>
              <p className="text-sm text-muted-foreground mb-4">选择接收预警通知的人员</p>
              
              <div className="space-y-4">
                {/* 库管人员 */}
                <div>
                  <div className="flex items-center gap-2 mb-3">
                    <User className="w-4 h-4 text-blue-600" />
                    <p className="font-medium">库管人员</p>
                  </div>
                  <div className="space-y-2 pl-6">
                    {notificationTargets.filter(t => t.type === 'warehouse').map(target => (
                      <div key={target.id} className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                        <div className="flex items-center gap-3">
                          <Checkbox
                            checked={selectedNotificationTargets.includes(target.id)}
                            onCheckedChange={(checked) => {
                              if (checked) {
                                setSelectedNotificationTargets([...selectedNotificationTargets, target.id]);
                              } else {
                                setSelectedNotificationTargets(
                                  selectedNotificationTargets.filter(id => id !== target.id)
                                );
                              }
                            }}
                          />
                          <span className="text-sm">{target.name}</span>
                        </div>
                        <Badge variant="outline" className="text-xs">{target.role}</Badge>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 采购人员 */}
                <div>
                  <div className="flex items-center gap-2 mb-3">
                    <ShoppingCart className="w-4 h-4 text-purple-600" />
                    <p className="font-medium">采购人员</p>
                  </div>
                  <div className="space-y-2 pl-6">
                    {notificationTargets.filter(t => t.type === 'purchase').map(target => (
                      <div key={target.id} className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                        <div className="flex items-center gap-3">
                          <Checkbox
                            checked={selectedNotificationTargets.includes(target.id)}
                            onCheckedChange={(checked) => {
                              if (checked) {
                                setSelectedNotificationTargets([...selectedNotificationTargets, target.id]);
                              } else {
                                setSelectedNotificationTargets(
                                  selectedNotificationTargets.filter(id => id !== target.id)
                                );
                              }
                            }}
                          />
                          <span className="text-sm">{target.name}</span>
                        </div>
                        <Badge variant="outline" className="text-xs">{target.role}</Badge>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                    <p className="text-xs text-blue-900">
                      已选择 <span className="font-medium">{selectedNotificationTargets.length}</span> 位接收人员
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* 底部操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => setShowWarningRuleDialog(false)}
              >
                关闭
              </Button>
              <Button 
                className="bg-orange-600 hover:bg-orange-700"
                onClick={() => {
                  const enabledChannels = [];
                  if (warningNotificationSettings.systemMessage) enabledChannels.push('系统消息');
                  if (warningNotificationSettings.sms) enabledChannels.push('短信');
                  if (warningNotificationSettings.email) enabledChannels.push('邮件');

                  const selectedTargetNames = notificationTargets
                    .filter(t => selectedNotificationTargets.includes(t.id))
                    .map(t => t.name);

                  toast.success('预警设置已保存', {
                    description: `通知方式：${enabledChannels.join('、') || '无'}；通知对象：${selectedTargetNames.join('、') || '无'}`,
                  });
                  setShowWarningRuleDialog(false);
                }}
              >
                <Save className="w-4 h-4 mr-2" />
                保存设置
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 预警详情对话框 */}
      <Dialog open={showWarningDetailDialog} onOpenChange={setShowWarningDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-orange-600" />
              预警详情
            </DialogTitle>
            <DialogDescription>
              查看预警详细信息和处理建议
            </DialogDescription>
          </DialogHeader>

          {selectedWarning && (
            <div className="space-y-6 mt-4">
              {/* 预警基本信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">预警信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>物料名称</Label>
                    <div className="field-value">{selectedWarning.materialName}</div>
                  </div>
                  <div>
                    <Label>物料类型</Label>
                    <div className="field-value">
                      <Badge variant="outline">{selectedWarning.materialType}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>预警类型</Label>
                    <div className="field-value">
                      <Badge className={
                        selectedWarning.warningType === '库存不足' ? 'bg-orange-100 text-orange-800' :
                        'bg-yellow-100 text-yellow-800'
                      }>
                        {selectedWarning.warningType}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>预警级别</Label>
                    <div className="field-value">
                      <Badge className={getWarningLevelColor(selectedWarning.warningLevel)}>
                        {selectedWarning.warningLevel}预警
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>仓库</Label>
                    <div className="field-value">{selectedWarning.warehouseName}</div>
                  </div>
                  <div>
                    <Label>库位</Label>
                    <div className="field-value">{selectedWarning.locationCode}</div>
                  </div>
                  <div>
                    <Label>批次号</Label>
                    <div className="field-value">{selectedWarning.batchNo}</div>
                  </div>
                  <div>
                    <Label>预警时间</Label>
                    <div className="field-value">{selectedWarning.createdAt}</div>
                  </div>
                </div>
              </div>

              {/* 库存信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">库存信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <Card className="p-4 bg-orange-50 border-orange-200">
                    <p className="text-sm text-muted-foreground">当前库存</p>
                    <p className="text-2xl font-medium text-orange-600 mt-1">
                      {selectedWarning.currentStock} {selectedWarning.unit}
                    </p>
                    {selectedWarning.warningType === '库存不足' && (
                      <p className="text-xs text-muted-foreground mt-1">
                        库存率: {((selectedWarning.currentStock / selectedWarning.safeStock) * 100).toFixed(1)}%
                      </p>
                    )}
                  </Card>

                  <Card className="p-4 bg-green-50 border-green-200">
                    <p className="text-sm text-muted-foreground">安全库存</p>
                    <p className="text-2xl font-medium text-green-600 mt-1">
                      {selectedWarning.safeStock} {selectedWarning.unit}
                    </p>
                  </Card>

                  <Card className="p-4 bg-purple-50 border-purple-200">
                    <p className="text-sm text-muted-foreground">库存缺口</p>
                    <p className="text-2xl font-medium text-purple-600 mt-1">
                      {(selectedWarning.safeStock - selectedWarning.currentStock).toFixed(0)} {selectedWarning.unit}
                    </p>
                  </Card>
                </div>
              </div>

              {/* 有效期信息（如果是临期预警） */}
              {selectedWarning.expiryDate && (
                <div>
                  <h4 className="mb-4 pb-2 border-b">有效期信息</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <Card className="p-4">
                      <p className="text-sm text-muted-foreground">有效期至</p>
                      <p className="text-xl font-medium mt-1">{selectedWarning.expiryDate}</p>
                    </Card>

                    <Card className="p-4">
                      <p className="text-sm text-muted-foreground">剩余天数</p>
                      <p className={`text-xl font-medium mt-1 ${
                        selectedWarning.daysLeft <= 7 ? 'text-red-600' :
                        selectedWarning.daysLeft <= 15 ? 'text-orange-600' :
                        'text-yellow-600'
                      }`}>
                        {selectedWarning.daysLeft} 天
                      </p>
                    </Card>
                  </div>
                </div>
              )}

              {/* 处理建议 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">处理建议</h4>
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <div className="space-y-2 text-sm">
                    {selectedWarning.warningType === '库存不足' ? (
                      <>
                        <p><strong>建议操作：</strong></p>
                        <ul className="space-y-1 ml-4">
                          <li>• 建议采购数量: {((selectedWarning.safeStock * 1.5) - selectedWarning.currentStock).toFixed(0)} {selectedWarning.unit}</li>
                          <li>• 预计可维持: {Math.floor(selectedWarning.currentStock / (selectedWarning.safeStock * 0.1))} 天（按正常消耗估算）</li>
                          <li>• 建议联系供应商尽快补货</li>
                          <li>• 可考虑从其他仓库调拨</li>
                        </ul>
                      </>
                    ) : (
                      <>
                        <p><strong>建议操作：</strong></p>
                        <ul className="space-y-1 ml-4">
                          <li>• 优先使用该批次物料（批次号: {selectedWarning.batchNo}）</li>
                          <li>• 检查物料质量，确认是否可用</li>
                          <li>• 如已变质，及时报废处理</li>
                          <li>• 加强临期物料的监控和使用</li>
                        </ul>
                      </>
                    )}
                  </div>
                </Card>
              </div>

              {/* 通知记录 */}
              {selectedWarning.notified && (
                <div>
                  <h4 className="mb-4 pb-2 border-b">通知记录</h4>
                  <Card className="p-4">
                    <div className="flex items-start gap-3">
                      <CheckCircle2 className="w-5 h-5 text-green-600 mt-0.5" />
                      <div className="flex-1">
                        <p className="font-medium mb-1">已发送通知</p>
                        <p className="text-sm text-muted-foreground">
                          通知时间: {new Date(selectedWarning.notifiedAt).toLocaleString()}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          通知方式: 系统消息 + 短信 + 邮件
                        </p>
                        <p className="text-sm text-muted-foreground">
                          通知对象: 库管人员、采购人员
                        </p>
                      </div>
                    </div>
                  </Card>
                </div>
              )}

              {/* 底部操作按钮 */}
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowWarningDetailDialog(false)}
                >
                  关闭
                </Button>
                {!selectedWarning.handled && (
                  <Button
                    className="bg-green-600 hover:bg-green-700"
                    onClick={() => {
                      handleMarkWarningHandled(selectedWarning.id);
                      setShowWarningDetailDialog(false);
                    }}
                  >
                    <CheckCircle2 className="w-4 h-4 mr-2" />
                    标记已处理
                  </Button>
                )}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 标记已处理确认对话框 */}
      <AlertDialog open={showWarningHandleConfirm} onOpenChange={setShowWarningHandleConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5 text-green-600" />
              确认标记已处理
            </AlertDialogTitle>
            <AlertDialogDescription>
              确定要将此预警标记为已处理吗？标记后该预警将移至已处理列表，不再显示在待处理预警中。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setShowWarningHandleConfirm(false);
              setPendingHandleWarningId(null);
            }}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              className="bg-green-600 hover:bg-green-700"
              onClick={confirmMarkWarningHandled}
            >
              确认标记
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 库存变动详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              库存变动详情
            </DialogTitle>
            <DialogDescription>
              查看库存变动的完整信息和相关记录
            </DialogDescription>
          </DialogHeader>

          {selectedTransaction && (
            <div className="space-y-6 mt-4">
              {/* 流水信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">流水信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>流水号</Label>
                    <div className="field-value font-mono text-blue-600">
                      {selectedTransaction.transactionNo}
                    </div>
                  </div>
                  <div>
                    <Label>变动类型</Label>
                    <div className="field-value">
                      <Badge className={
                        selectedTransaction.type === '入库' ? 'bg-green-100 text-green-800' :
                        selectedTransaction.type === '出库' ? 'bg-blue-100 text-blue-800' :
                        selectedTransaction.type === '盘盈' ? 'bg-purple-100 text-purple-800' :
                        selectedTransaction.type === '盘亏' ? 'bg-red-100 text-red-800' :
                        'bg-gray-100 text-gray-800'
                      }>
                        {selectedTransaction.type}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>变动时间</Label>
                    <div className="field-value">
                      {selectedTransaction.createdDate} {selectedTransaction.createdTime}
                    </div>
                  </div>
                  <div>
                    <Label>操作人</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-muted-foreground" />
                        {selectedTransaction.operator}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 物料信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">物料信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label>物料名称</Label>
                    <div className="field-value font-medium">
                      {selectedTransaction.materialName}
                    </div>
                  </div>
                  <div>
                    <Label>批次号</Label>
                    <div className="field-value">
                      <Badge variant="outline" className="font-mono">
                        {selectedTransaction.batchNo}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>单位</Label>
                    <div className="field-value">
                      {selectedTransaction.unit}
                    </div>
                  </div>
                </div>
              </div>

              {/* 仓库信息 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">仓库信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>仓库</Label>
                    <div className="field-value">
                      {selectedTransaction.warehouseName}
                    </div>
                  </div>
                  <div>
                    <Label>库位</Label>
                    <div className="field-value">
                      <Badge variant="outline">
                        {selectedTransaction.locationCode || '未指定'}
                      </Badge>
                    </div>
                  </div>
                </div>
              </div>

              {/* 变动数量 */}
              <div>
                <h4 className="mb-4 pb-2 border-b">变动数量</h4>
                <div className="grid grid-cols-3 gap-4">
                  <Card className="p-4 bg-gray-50 border-gray-200">
                    <p className="text-sm text-muted-foreground">变动前库存</p>
                    <p className="text-2xl font-medium text-gray-600 mt-1">
                      {selectedTransaction.beforeStock} {selectedTransaction.unit}
                    </p>
                  </Card>

                  <Card className={`p-4 ${
                    selectedTransaction.type === '入库' || selectedTransaction.type === '盘盈' 
                      ? 'bg-green-50 border-green-200' 
                      : 'bg-red-50 border-red-200'
                  }`}>
                    <p className="text-sm text-muted-foreground">变动数量</p>
                    <p className={`text-2xl font-medium mt-1 ${
                      selectedTransaction.type === '入库' || selectedTransaction.type === '盘盈' 
                        ? 'text-green-600' 
                        : 'text-red-600'
                    }`}>
                      {selectedTransaction.type === '入库' || selectedTransaction.type === '盘盈' ? '+' : '-'}
                      {selectedTransaction.quantity} {selectedTransaction.unit}
                    </p>
                  </Card>

                  <Card className="p-4 bg-blue-50 border-blue-200">
                    <p className="text-sm text-muted-foreground">变动后库存</p>
                    <p className="text-2xl font-medium text-blue-600 mt-1">
                      {selectedTransaction.afterStock} {selectedTransaction.unit}
                    </p>
                  </Card>
                </div>
              </div>

              {/* 关联信息 */}
              {selectedTransaction.relatedNo && (
                <div>
                  <h4 className="mb-4 pb-2 border-b">关联信息</h4>
                  <div>
                    <Label>关联单号</Label>
                    <div className="field-value">
                      <Badge variant="outline" className="font-mono text-blue-600">
                        {selectedTransaction.relatedNo}
                      </Badge>
                    </div>
                  </div>
                </div>
              )}

              {/* 备注信息 */}
              {selectedTransaction.notes && (
                <div>
                  <h4 className="mb-4 pb-2 border-b">备注信息</h4>
                  <Card className="p-4 bg-gray-50">
                    <p className="text-sm">{selectedTransaction.notes}</p>
                  </Card>
                </div>
              )}

              {/* 底部操作按钮 */}
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowDetailDialog(false)}
                >
                  关闭
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowDetailDialog(false);
                    generateTraceChain(selectedTransaction.batchNo);
                  }}
                >
                  <FileSearch className="w-4 h-4 mr-2" />
                  查看批次追溯链
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 批次追溯链对话框 */}
      <Dialog open={showTraceChainDialog} onOpenChange={setShowTraceChainDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileSearch className="w-5 h-5 text-purple-600" />
              批次追溯链
            </DialogTitle>
            <DialogDescription>
              查看批次的完整变动历史，从入库到出库的全流程记录
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 mt-4">
            {/* 批次信息 */}
            {traceChainData.length > 0 && (
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-start gap-3">
                  <Package className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="font-medium mb-2">批次号: {traceChainData[0].batchNo}</p>
                    <div className="grid grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-muted-foreground">物料名称</p>
                        <p className="font-medium">{traceChainData[0].materialName}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">变动次数</p>
                        <p className="font-medium text-purple-600">{traceChainData.length} 次</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">累计入库</p>
                        <p className="font-medium text-green-600">
                          +{traceChainData.filter(t => t.type === '入库' || t.type === '盘盈').reduce((sum, t) => sum + t.quantity, 0)} {traceChainData[0].unit}
                        </p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">累计出库</p>
                        <p className="font-medium text-red-600">
                          -{traceChainData.filter(t => t.type === '出库' || t.type === '盘亏').reduce((sum, t) => sum + t.quantity, 0)} {traceChainData[0].unit}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>
            )}

            {/* 追溯链时间线 */}
            <div>
              <h4 className="mb-4 pb-2 border-b">变动时间线</h4>
              
              {traceChainData.length === 0 ? (
                <Card className="p-8 text-center">
                  <FileSearch className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                  <p className="text-muted-foreground">该批次暂无变动记录</p>
                </Card>
              ) : (
                <div className="relative">
                  {/* 时间线 */}
                  <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-gray-200"></div>

                  {/* 变动记录 */}
                  <div className="space-y-6">
                    {traceChainData.map((record, index) => (
                      <div key={record.id} className="relative pl-20">
                        {/* 时间线节点 */}
                        <div className={`absolute left-6 w-5 h-5 rounded-full border-2 ${
                          record.type === '入库' ? 'bg-green-500 border-green-600' :
                          record.type === '出库' ? 'bg-blue-500 border-blue-600' :
                          record.type === '盘盈' ? 'bg-purple-500 border-purple-600' :
                          record.type === '盘亏' ? 'bg-red-500 border-red-600' :
                          'bg-gray-500 border-gray-600'
                        }`}></div>

                        {/* 变动卡片 */}
                        <Card className={`p-4 border-l-4 ${
                          record.type === '入库' ? 'border-l-green-500 bg-green-50' :
                          record.type === '出库' ? 'border-l-blue-500 bg-blue-50' :
                          record.type === '盘盈' ? 'border-l-purple-500 bg-purple-50' :
                          record.type === '盘亏' ? 'border-l-red-500 bg-red-50' :
                          'border-l-gray-500 bg-gray-50'
                        }`}>
                          <div className="flex items-start justify-between mb-3">
                            <div className="flex items-center gap-2">
                              <Badge className={
                                record.type === '入库' ? 'bg-green-100 text-green-800' :
                                record.type === '出库' ? 'bg-blue-100 text-blue-800' :
                                record.type === '盘盈' ? 'bg-purple-100 text-purple-800' :
                                record.type === '盘亏' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'
                              }>
                                {record.type}
                              </Badge>
                              <span className="text-sm font-mono text-muted-foreground">
                                #{index + 1}
                              </span>
                            </div>
                            <div className="text-sm text-muted-foreground">
                              {record.createdDate} {record.createdTime}
                            </div>
                          </div>

                          <div className="grid grid-cols-4 gap-4">
                            <div>
                              <p className="text-xs text-muted-foreground">变动数量</p>
                              <p className={`font-medium ${
                                record.type === '入库' || record.type === '盘盈' 
                                  ? 'text-green-600' 
                                  : 'text-red-600'
                              }`}>
                                {record.type === '入库' || record.type === '盘盈' ? '+' : '-'}
                                {record.quantity} {record.unit}
                              </p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">变动前</p>
                              <p className="font-medium">{record.beforeStock} {record.unit}</p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">变动后</p>
                              <p className="font-medium text-blue-600">{record.afterStock} {record.unit}</p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">操作人</p>
                              <p className="font-medium">{record.operator}</p>
                            </div>
                          </div>

                          {record.relatedNo && (
                            <div className="mt-3 pt-3 border-t">
                              <p className="text-xs text-muted-foreground mb-1">关联单号:</p>
                              <Badge variant="outline" className="text-xs font-mono">
                                {record.relatedNo}
                              </Badge>
                            </div>
                          )}

                          {record.notes && (
                            <div className="mt-3 pt-3 border-t">
                              <p className="text-xs text-muted-foreground mb-1">备注:</p>
                              <p className="text-sm">{record.notes}</p>
                            </div>
                          )}
                        </Card>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* 底部操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => setShowTraceChainDialog(false)}
              >
                关闭
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 仓库管理对话框 */}
      <Dialog open={showWarehouseDialog} onOpenChange={setShowWarehouseDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Warehouse className="w-5 h-5 text-green-600" />
              {editingWarehouse ? '编辑仓库' : '新增仓库'}
            </DialogTitle>
            <DialogDescription>
              设置仓库基本信息、类型、负责人等
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 mt-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>仓库名称 *</Label>
                <Input
                  placeholder="如：1号仓库"
                  value={warehouseFormData.name}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, name: e.target.value })}
                />
              </div>

              <div>
                <Label>仓库编码 *</Label>
                <Input
                  placeholder="如：WH-001"
                  value={warehouseFormData.code}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, code: e.target.value })}
                />
              </div>

              <div>
                <Label>仓库类型 *</Label>
                <Select
                  value={warehouseFormData.type}
                  onValueChange={(value) => setWarehouseFormData({ ...warehouseFormData, type: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="综合仓库">综合仓库</SelectItem>
                    <SelectItem value="农药专用仓库">农药专用仓库</SelectItem>
                    <SelectItem value="机具仓库">机具仓库</SelectItem>
                    <SelectItem value="冷藏仓库">冷藏仓库</SelectItem>
                    <SelectItem value="种子仓库">种子仓库</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>仓库面积（㎡）</Label>
                <Input
                  type="number"
                  placeholder="如：500"
                  value={warehouseFormData.area || ''}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, area: Number(e.target.value) })}
                />
              </div>

              <div>
                <Label>仓库地址</Label>
                <Input
                  placeholder="如：农场东区"
                  value={warehouseFormData.address}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, address: e.target.value })}
                />
              </div>

              <div>
                <Label>仓库负责人</Label>
                <Input
                  placeholder="如：张三"
                  value={warehouseFormData.manager}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, manager: e.target.value })}
                />
              </div>

              <div className="col-span-2">
                <Label>联系电话</Label>
                <Input
                  placeholder="如：13800001111"
                  value={warehouseFormData.contact}
                  onChange={(e) => setWarehouseFormData({ ...warehouseFormData, contact: e.target.value })}
                />
              </div>
            </div>

            {/* 备注 */}
            <div>
              <Label>备注说明</Label>
              <Textarea
                placeholder="填写备注信息（可选）"
                value={warehouseFormData.notes}
                onChange={(e) => setWarehouseFormData({ ...warehouseFormData, notes: e.target.value })}
                rows={3}
              />
            </div>

            {/* 底部操作按钮 */}
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                variant="outline"
                onClick={() => {
                  setShowWarehouseDialog(false);
                  setEditingWarehouse(null);
                }}
              >
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSubmitWarehouse}
              >
                <Save className="w-4 h-4 mr-2" />
                {editingWarehouse ? '更新' : '创建'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 库位表单对话框 */}
      <Dialog open={showLocationDialog} onOpenChange={setShowLocationDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MapPin className="w-5 h-5 text-blue-600" />
              {selectedLocation ? '编辑库位' : '新增库位'}
            </DialogTitle>
            <DialogDescription>
              设置库位基本信息，包括所属仓库和位置名称
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 mt-4">
            {/* 仓库选择 */}
            <div>
              <Label>仓库 *</Label>
              <Select
                value={locationFormData.warehouseId}
                onValueChange={(value) => {
                  const warehouse = warehouses.find(w => w.id === value);
                  setLocationFormData({
                    ...locationFormData,
                    warehouseId: value,
                    warehouseName: warehouse?.name || '',
                  });
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map(wh => (
                    <SelectItem key={wh.id} value={wh.id}>
                      {wh.name} - {wh.type}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 位置名称 */}
            <div>
              <Label>位置名称 *</Label>
              <Input
                placeholder="如：A区种子存储位、B区肥料存储位等"
                value={locationFormData.name}
                onChange={(e) => setLocationFormData({
                  ...locationFormData,
                  name: e.target.value,
                })}
              />
            </div>

            {/* 备注 */}
            <div>
              <Label>备注</Label>
              <Textarea
                placeholder="备注信息（选填）"
                value={locationFormData.notes}
                onChange={(e) => setLocationFormData({
                  ...locationFormData,
                  notes: e.target.value,
                })}
              />
            </div>
          </div>

          <div className="flex justify-between gap-2 mt-6">
            <div>
              {selectedLocation && (
                <Button
                  variant="destructive"
                  onClick={() => {
                    setShowLocationDeleteConfirm(true);
                  }}
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  删除库位
                </Button>
              )}
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                onClick={() => {
                  setShowLocationDialog(false);
                  setSelectedLocation(null);
                }}
              >
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSubmitLocation}
              >
                <Save className="w-4 h-4 mr-2" />
                {selectedLocation ? '更新' : '创建'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 库位删除确认对话框 */}
      <AlertDialog open={showLocationDeleteConfirm} onOpenChange={(open) => {
        setShowLocationDeleteConfirm(open);
        if (!open) {
          setLocationToDelete(null);
        }
      }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <Trash2 className="w-5 h-5 text-red-600" />
              确认删除库位
            </AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除库位"{locationToDelete?.name}"（{locationToDelete?.code}）吗？
              {locationToDelete?.materials && locationToDelete.materials.length > 0 ? (
                <span className="block mt-2 text-red-600">
                  <AlertCircle className="w-4 h-4 inline mr-1" />
                  警告：该库位中还有 {locationToDelete.materials.length} 种物料，无法删除。请先清空库位中的物料。
                </span>
              ) : (
                <span className="block mt-2 text-muted-foreground">
                  该库位当前为空闲状态，可以安全删除。
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setLocationToDelete(null)}>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={handleDeleteLocation}
              disabled={locationToDelete?.materials && locationToDelete.materials.length > 0}
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 仓库删除确认对话框 */}
      <AlertDialog open={showWarehouseDeleteConfirm} onOpenChange={setShowWarehouseDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <Warehouse className="w-5 h-5 text-red-600" />
              确认删除仓库
            </AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除仓库"{warehouseToDelete?.name}"吗？
              {(() => {
                const warehouseLocations = locations.filter(l => l.warehouseId === warehouseToDelete?.id);
                if (warehouseLocations.length > 0) {
                  return (
                    <span className="block mt-2 text-red-600">
                      <AlertCircle className="w-4 h-4 inline mr-1" />
                      警告：该仓库下还有 {warehouseLocations.length} 个库位，无法删除。请先删除或转移所有库位。
                    </span>
                  );
                }
                return (
                  <span className="block mt-2 text-muted-foreground">
                    该仓库下暂无库位，可以安全删除。
                  </span>
                );
              })()}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={handleDeleteWarehouse}
              disabled={locations.filter(l => l.warehouseId === warehouseToDelete?.id).length > 0}
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 库位详情对话框 */}
      <Dialog open={showLocationDetailDialog} onOpenChange={setShowLocationDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MapPin className="w-5 h-5 text-blue-600" />
              库位详情
            </DialogTitle>
            <DialogDescription>
              查看库位的详细信息和存放的物料清单
            </DialogDescription>
          </DialogHeader>

          {selectedLocation && (
            <div className="space-y-4 mt-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">库位编码</p>
                    <p className="font-mono font-medium text-lg">{selectedLocation.code}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">所属仓库</p>
                    <p className="font-medium">{selectedLocation.warehouseName}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">状态</p>
                    <Badge className={getLocationStatusColor(selectedLocation.status)}>
                      {selectedLocation.status}
                    </Badge>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">层级</p>
                    <p className="font-medium">{selectedLocation.level}</p>
                  </div>
                </div>
              </Card>

              {/* 容量信息 */}
              <Card className="p-4">
                <h4 className="mb-3">容量使用情况</h4>
                <div className="space-y-3">
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">使用率</span>
                      <span className="text-sm font-medium">
                        {((selectedLocation.usedCapacity / selectedLocation.capacity) * 100).toFixed(1)}%
                      </span>
                    </div>
                    <Progress 
                      value={(selectedLocation.usedCapacity / selectedLocation.capacity) * 100} 
                      className="h-3"
                    />
                  </div>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div className="p-3 bg-gray-50 rounded">
                      <p className="text-muted-foreground">总容量</p>
                      <p className="text-xl font-medium mt-1">{selectedLocation.capacity}</p>
                    </div>
                    <div className="p-3 bg-blue-50 rounded">
                      <p className="text-muted-foreground">已用</p>
                      <p className="text-xl font-medium text-blue-600 mt-1">
                        {selectedLocation.usedCapacity}
                      </p>
                    </div>
                    <div className="p-3 bg-green-50 rounded">
                      <p className="text-muted-foreground">可用</p>
                      <p className="text-xl font-medium text-green-600 mt-1">
                        {selectedLocation.capacity - selectedLocation.usedCapacity}
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 物料清单 */}
              <Card className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <h4>存放物料清单</h4>
                  <Badge>{selectedLocation.materials.length} 种</Badge>
                </div>
                
                {selectedLocation.materials.length === 0 ? (
                  <div className="p-8 text-center">
                    <Package className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-muted-foreground">该库位暂无物料</p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {selectedLocation.materials.map((material, index) => (
                      <div 
                        key={index}
                        className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                      >
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-blue-100 rounded">
                            <Package className="w-5 h-5 text-blue-600" />
                          </div>
                          <div>
                            <p className="font-medium">{material.materialName}</p>
                            <p className="text-sm text-muted-foreground">
                              物料ID: {material.materialId}
                            </p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-lg font-medium text-blue-600">
                            {material.quantity}
                          </p>
                          <p className="text-sm text-muted-foreground">{material.unit}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </Card>

              {selectedLocation.notes && (
                <Card className="p-4 bg-yellow-50 border-yellow-200">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="font-medium text-yellow-900 mb-1">备注信息</p>
                      <p className="text-sm text-yellow-800">{selectedLocation.notes}</p>
                    </div>
                  </div>
                </Card>
              )}
            </div>
          )}

          <div className="flex justify-between gap-2 mt-6 pt-4 border-t">
            <div className="flex gap-2">
              {selectedLocation && selectedLocation.status !== '禁用' && (
                <>
                  <Button
                    variant="outline"
                    onClick={() => {
                      handleToggleLocationStatus(selectedLocation.id);
                      setShowLocationDetailDialog(false);
                    }}
                  >
                    禁用库位
                  </Button>
                  {selectedLocation.usedCapacity === 0 && (
                    <Button
                      variant="outline"
                      className="text-red-600 hover:bg-red-50"
                      onClick={() => {
                        handleDeleteLocation(selectedLocation.id);
                        setShowLocationDetailDialog(false);
                      }}
                    >
                      <Trash2 className="w-4 h-4 mr-2" />
                      删除
                    </Button>
                  )}
                </>
              )}
            </div>
            <Button
              variant="outline"
              onClick={() => setShowLocationDetailDialog(false)}
            >
              关闭
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 采购建议详情对话框 */}
      <Dialog open={showSuggestionDetailDialog} onOpenChange={setShowSuggestionDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Target className="w-5 h-5 text-purple-600" />
              采购建议详情
            </DialogTitle>
            <DialogDescription>
              查看详细的采购建议分析和计算逻辑
            </DialogDescription>
          </DialogHeader>

          {selectedSuggestion && (
            <div className="space-y-6 mt-4">
              {/* 物料信息 */}
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-start gap-3">
                  <div className={`p-3 rounded-lg ${
                    selectedSuggestion.priority === '高' ? 'bg-red-100' :
                    selectedSuggestion.priority === '中' ? 'bg-orange-100' :
                    'bg-blue-100'
                  }`}>
                    <Target className={`w-6 h-6 ${
                      selectedSuggestion.priority === '高' ? 'text-red-600' :
                      selectedSuggestion.priority === '中' ? 'text-orange-600' :
                      'text-blue-600'
                    }`} />
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h3>{selectedSuggestion.materialName}</h3>
                      <Badge variant="outline">{selectedSuggestion.materialType}</Badge>
                      <Badge className={
                        selectedSuggestion.priority === '高' ? 'bg-red-100 text-red-800' :
                        selectedSuggestion.priority === '中' ? 'bg-orange-100 text-orange-800' :
                        'bg-blue-100 text-blue-800'
                      }>
                        {selectedSuggestion.priority}优先级
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">{selectedSuggestion.reason}</p>
                  </div>
                </div>
              </Card>

              {/* 数据分析 */}
              <div className="grid grid-cols-2 gap-4">
                <Card className="p-4">
                  <h4 className="mb-4">库存状况</h4>
                  <div className="space-y-4">
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm text-muted-foreground">当前库存</span>
                        <span className="text-2xl font-medium text-orange-600">
                          {selectedSuggestion.currentStock} {selectedSuggestion.unit}
                        </span>
                      </div>
                      <Progress 
                        value={(selectedSuggestion.currentStock / selectedSuggestion.safeStock) * 100} 
                        className="h-2"
                      />
                    </div>
                    <div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-muted-foreground">安全库存</span>
                        <span className="font-medium text-green-600">
                          {selectedSuggestion.safeStock} {selectedSuggestion.unit}
                        </span>
                      </div>
                    </div>
                    <div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-muted-foreground">库存状态</span>
                        <Badge className={
                          selectedSuggestion.currentStock < selectedSuggestion.safeStock * 0.5 
                            ? 'bg-red-100 text-red-800' :
                          selectedSuggestion.currentStock < selectedSuggestion.safeStock 
                            ? 'bg-orange-100 text-orange-800' :
                          'bg-green-100 text-green-800'
                        }>
                          {selectedSuggestion.currentStock < selectedSuggestion.safeStock * 0.5 
                            ? '严重不足' :
                          selectedSuggestion.currentStock < selectedSuggestion.safeStock 
                            ? '低于安全库存' :
                          '正常'}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </Card>

                <Card className="p-4">
                  <h4 className="mb-4">消耗预测</h4>
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">日均消耗</span>
                      <span className="font-medium text-blue-600">
                        {selectedSuggestion.avgDailyConsumption} {selectedSuggestion.unit}/天
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">预测周期</span>
                      <span className="font-medium">{selectedSuggestion.forecastDays} 天</span>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-sm text-muted-foreground">预计总消耗</span>
                        <span className="text-xl font-medium text-purple-600">
                          {selectedSuggestion.forecastConsumption}
                        </span>
                      </div>
                      <p className="text-xs text-muted-foreground">
                        = {selectedSuggestion.avgDailyConsumption} × {selectedSuggestion.forecastDays}
                      </p>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">预计耗尽日期</span>
                      <span className="font-medium text-red-600">
                        {Math.floor(selectedSuggestion.currentStock / selectedSuggestion.avgDailyConsumption)} 天后
                      </span>
                    </div>
                  </div>
                </Card>
              </div>

              {/* 计算逻辑 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <FileText className="w-5 h-5 text-blue-600" />
                  计算逻辑说明
                </h4>
                <div className="space-y-3 text-sm">
                  <div className="p-3 bg-white rounded">
                    <p className="font-medium mb-2">建议采购数量计算公式：</p>
                    <p className="font-mono text-blue-600">
                      建议采购量 = 安全库存 + 预测消耗 - 当前库存
                    </p>
                    <p className="font-mono text-blue-600 mt-1">
                      = {selectedSuggestion.safeStock} + {selectedSuggestion.forecastConsumption} - {selectedSuggestion.currentStock}
                    </p>
                    <p className="font-mono text-blue-600 mt-1">
                      = {selectedSuggestion.suggestedQuantity} {selectedSuggestion.unit}
                    </p>
                  </div>
                  
                  <div className="p-3 bg-white rounded">
                    <p className="font-medium mb-2">优先级判定：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 高优先级：当前库存 &lt; 安全库存 × 50%</li>
                      <li>• 中优先级：当前库存 &lt; 安全库存 × 80%</li>
                      <li>• 低优先级：当前库存 ≥ 安全库存 × 80%</li>
                    </ul>
                    <p className="mt-2">
                      当前: {selectedSuggestion.currentStock} / {selectedSuggestion.safeStock} = 
                      <Badge className="ml-1">
                        {((selectedSuggestion.currentStock / selectedSuggestion.safeStock) * 100).toFixed(1)}%
                      </Badge>
                    </p>
                  </div>
                </div>
              </Card>

              {/* 采购建议 */}
              <Card className="p-6 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
                <div className="flex items-start justify-between">
                  <div>
                    <h4 className="mb-2">采购建议汇总</h4>
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <p className="text-muted-foreground">建议采购数量</p>
                        <p className="text-3xl font-bold text-green-600 mt-1">
                          {selectedSuggestion.suggestedQuantity}
                        </p>
                        <p className="text-muted-foreground">{selectedSuggestion.unit}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">预估采购金额</p>
                        <p className="text-3xl font-bold text-green-600 mt-1">
                          ¥{selectedSuggestion.estimatedAmount.toLocaleString()}
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">
                          基于历史价格 ¥{selectedSuggestion.lastPurchasePrice}/{selectedSuggestion.unit}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <div className="flex justify-end gap-2 mt-6 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => setShowSuggestionDetailDialog(false)}
            >
              关闭
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700"
              onClick={() => {
                if (selectedSuggestion) {
                  handleAddToPurchasePlan(selectedSuggestion);
                  setShowSuggestionDetailDialog(false);
                }
              }}
            >
              <Plus className="w-4 h-4 mr-2" />
              加入采购计划
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 打印区域 - 只在打印时显示 */}
      {printTask && (
        <div className="print-only">
          <style>{`
            @media print {
              body * {
                visibility: hidden;
              }
              .print-only, .print-only * {
                visibility: visible;
              }
              .print-only {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                padding: 20px;
              }
              @page {
                size: A4;
                margin: 15mm;
              }
              .print-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 12px;
              }
              .print-table th,
              .print-table td {
                border: 1px solid #000;
                padding: 8px 4px;
                text-align: left;
              }
              .print-table th {
                background-color: #f0f0f0;
                font-weight: bold;
              }
              .print-header {
                text-align: center;
                margin-bottom: 20px;
              }
              .print-info {
                margin-bottom: 15px;
                display: flex;
                justify-content: space-between;
              }
              .print-signature {
                margin-top: 30px;
                display: flex;
                justify-content: space-between;
              }
              .signature-box {
                width: 200px;
                border-bottom: 1px solid #000;
                padding-bottom: 5px;
                margin-top: 10px;
              }
            }
            @media screen {
              .print-only {
                display: none;
              }
            }
          `}</style>
          
          <div className="print-content">
            {/* 表头 */}
            <div className="print-header">
              <h1 style={{ fontSize: '24px', margin: '0 0 10px 0' }}>库存盘点表</h1>
              <p style={{ fontSize: '14px', margin: 0 }}>Stock Inventory Check List</p>
            </div>

            {/* 基本信息 */}
            <div className="print-info">
              <div>
                <strong>任务名称：</strong>{printTask.taskName}
              </div>
              <div>
                <strong>任务编号：</strong>{printTask.taskNo}
              </div>
            </div>
            
            <div className="print-info">
              <div>
                <strong>仓库：</strong>{printTask.warehouseName}
              </div>
              <div>
                <strong>盘点类型：</strong>{printTask.checkType}
              </div>
              <div>
                <strong>盘点人：</strong>{printTask.checker}
              </div>
            </div>

            <div className="print-info">
              <div>
                <strong>计划日期：</strong>{printTask.planDate}
              </div>
              <div>
                <strong>创建日期：</strong>{printTask.createdAt}
              </div>
              <div>
                <strong>打印日期：</strong>{new Date().toLocaleDateString('zh-CN')}
              </div>
            </div>

            {/* 盘点明细表 */}
            <table className="print-table">
              <thead>
                <tr>
                  <th style={{ width: '5%' }}>序号</th>
                  <th style={{ width: '20%' }}>物料名称</th>
                  <th style={{ width: '15%' }}>规格</th>
                  <th style={{ width: '10%' }}>库位</th>
                  <th style={{ width: '12%' }}>批次号</th>
                  <th style={{ width: '10%', textAlign: 'right' }}>账面数量</th>
                  <th style={{ width: '10%', textAlign: 'right' }}>实盘数量</th>
                  <th style={{ width: '10%', textAlign: 'right' }}>差异</th>
                  <th style={{ width: '8%' }}>备注</th>
                </tr>
              </thead>
              <tbody>
                {printTask.items.map((item, index) => (
                  <tr key={item.id}>
                    <td style={{ textAlign: 'center' }}>{index + 1}</td>
                    <td>{item.materialName}</td>
                    <td>{item.spec}</td>
                    <td>{item.locationCode}</td>
                    <td style={{ fontSize: '10px' }}>{item.batchNo}</td>
                    <td style={{ textAlign: 'right' }}>
                      {item.bookQuantity} {item.unit}
                    </td>
                    <td style={{ textAlign: 'right' }}>
                      {item.actualQuantity !== undefined 
                        ? `${item.actualQuantity} ${item.unit}` 
                        : '___________'
                      }
                    </td>
                    <td style={{ textAlign: 'right' }}>
                      {item.actualQuantity !== undefined
                        ? `${item.difference > 0 ? '+' : ''}${item.difference} ${item.unit}`
                        : '___________'
                      }
                    </td>
                    <td></td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* 统计汇总 */}
            <div style={{ marginTop: '20px', fontSize: '12px' }}>
              <div style={{ display: 'flex', gap: '30px' }}>
                <div>
                  <strong>盘点总项数：</strong>{printTask.items.length} 项
                </div>
                {printTask.status !== '待盘点' && (
                  <>
                    <div>
                      <strong>盘盈：</strong>
                      <span style={{ color: '#16a34a' }}>{printTask.profit} 项</span>
                    </div>
                    <div>
                      <strong>盘亏：</strong>
                      <span style={{ color: '#dc2626' }}>{printTask.loss} 项</span>
                    </div>
                    <div>
                      <strong>正常：</strong>
                      {printTask.items.length - printTask.profit - printTask.loss} 项
                    </div>
                  </>
                )}
              </div>
            </div>

            {/* 备注说明 */}
            {printTask.notes && (
              <div style={{ marginTop: '15px', fontSize: '12px' }}>
                <strong>备注：</strong>{printTask.notes}
              </div>
            )}

            {/* 签字确认 */}
            <div className="print-signature">
              <div>
                <div><strong>盘点人：</strong></div>
                <div className="signature-box"></div>
                <div style={{ marginTop: '5px', fontSize: '12px' }}>日期：_______________</div>
              </div>
              <div>
                <div><strong>复核人：</strong></div>
                <div className="signature-box"></div>
                <div style={{ marginTop: '5px', fontSize: '12px' }}>日期：_______________</div>
              </div>
              <div>
                <div><strong>审批人：</strong></div>
                <div className="signature-box"></div>
                <div style={{ marginTop: '5px', fontSize: '12px' }}>日期：_______________</div>
              </div>
            </div>

            {/* 页脚说明 */}
            <div style={{ 
              marginTop: '30px', 
              paddingTop: '10px', 
              borderTop: '1px solid #ddd',
              fontSize: '10px',
              color: '#666'
            }}>
              <p style={{ margin: 0 }}>说明：1. 实盘数量请在实地盘点后填写；2. 差异 = 实盘数量 - 账面数量；3. 盘点完成后需审批人签字确认。</p>
            </div>
          </div>
        </div>
      )}

      {/* 盘点审批通过确认对话框 */}
      <Dialog open={showCheckApprovalConfirm} onOpenChange={setShowCheckApprovalConfirm}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5 text-green-600" />
              审批通过确认
            </DialogTitle>
            <DialogDescription>
              确认审批通过这个盘点任务吗？审批后将调整库存账面数量，操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex justify-end gap-2 pt-4">
            <Button 
              variant="outline" 
              onClick={() => setShowCheckApprovalConfirm(false)}
            >
              取消
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700"
              onClick={() => {
                handleSubmitCheckApproval('通过');
                setShowCheckItemDialog(false);
                setShowCheckApprovalConfirm(false);
              }}
            >
              确认审批通过
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 盘点驳回确认对话框 */}
      <Dialog open={showCheckRejectConfirm} onOpenChange={setShowCheckRejectConfirm}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <X className="w-5 h-5 text-orange-600" />
              驳回确认
            </DialogTitle>
            <DialogDescription>
              确定要驳回此盘点任务吗？驳回后任务状态将变为"待盘点"，需要重新进行盘点和录入。
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex justify-end gap-2 pt-4">
            <Button 
              variant="outline" 
              onClick={() => setShowCheckRejectConfirm(false)}
            >
              取消
            </Button>
            <Button
              className="bg-orange-600 hover:bg-orange-700"
              onClick={() => {
                handleSubmitCheckApproval('驳回');
                setShowCheckItemDialog(false);
                setShowCheckRejectConfirm(false);
              }}
            >
              确认驳回
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 库位二维码对话框 */}
      <LocationQRCodeDialog
        open={showLocationQRCodeDialog}
        onClose={() => {
          setShowLocationQRCodeDialog(false);
          setQrCodeLocation(null);
        }}
        location={qrCodeLocation}
      />
    </div>
  );
}
