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 { Progress } from '../ui/progress';
import { Checkbox } from '../ui/checkbox';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import {
  ShoppingCart,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  CheckCircle2,
  XCircle,
  Clock,
  AlertTriangle,
  FileText,
  Send,
  Save,
  Package,
  Calendar,
  DollarSign,
  User,
  Building2,
  Target,
  Zap,
  AlertCircle,
  ThumbsUp,
  ThumbsDown,
  ArrowRight,
  CheckCheck,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AssetPurchaseProps {
  activePath?: string;
}

type PlanStatus = '草稿' | '待审批' | '已批准' | '已驳回' | '执行中' | '已完成';
type OrderStatus = '待审批' | '待复审' | '已下单' | '部分到货' | '已完成' | '已取消';
type ApprovalStatus = '待初审' | '待复审' | '已通过' | '已驳回';

interface PurchasePlan {
  id: string;
  planNo: string;
  planName: string;
  status: PlanStatus;
  totalAmount: number;
  itemCount: number;
  items: PurchasePlanItem[];
  reason: string;
  plantingPlanRef?: string;
  marketAnalysis?: string;
  createdBy: string;
  createdAt: string;
  approvedBy?: string;
  approvedAt?: string;
  notes?: string;
}

interface PurchasePlanItem {
  id: string;
  materialName: string;
  materialType: string;
  currentStock: number;
  safeStock: number;
  estimatedDemand: number;
  suggestedQuantity: number;
  unit: string;
  estimatedPrice: number;
  estimatedAmount: number;
  priority: '高' | '中' | '低';
  reason: string;
}

interface PurchaseOrder {
  id: string;
  orderNo: string;
  planId?: string;
  planName?: string;
  supplierId: string;
  supplierName: string;
  status: OrderStatus;
  approvalStatus: ApprovalStatus;
  totalAmount: number;
  paidAmount: number;
  items: OrderItem[];
  deliveries: Delivery[];
  approvalFlow: ApprovalRecord[];
  createdBy: string;
  createdAt: string;
  expectedDeliveryDate: string;
  actualDeliveryDate?: string;
  notes?: string;
}

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

interface Delivery {
  id: string;
  deliveryNo: string;
  deliveryDate: string;
  items: DeliveryItem[];
  receiver: string;
  notes?: string;
  attachments?: string[];
}

interface DeliveryItem {
  orderItemId: string;
  materialName: string;
  quantity: number;
  qualityStatus: '合格' | '不合格' | '待检验';
  notes?: string;
}

interface ApprovalRecord {
  id: string;
  step: number;
  approverRole: string;
  approverName?: string;
  status: '待审批' | '已通过' | '已驳回';
  comment?: string;
  approvedAt?: string;
}

export function AssetPurchase({ activePath }: AssetPurchaseProps) {
  const [activeTab, setActiveTab] = useState('plan');
  const [showPlanDialog, setShowPlanDialog] = useState(false);
  const [showSmartSuggestionDialog, setShowSmartSuggestionDialog] = useState(false);
  const [showOrderDialog, setShowOrderDialog] = useState(false);
  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [showViewPlanDialog, setShowViewPlanDialog] = useState(false);
  const [showEditPlanDialog, setShowEditPlanDialog] = useState(false);
  const [showDeliveryDialog, setShowDeliveryDialog] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<PurchasePlan | null>(null);
  const [selectedOrder, setSelectedOrder] = useState<PurchaseOrder | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [suggestedItems, setSuggestedItems] = useState<PurchasePlanItem[]>([]);
  const [selectedSuggestionIds, setSelectedSuggestionIds] = useState<string[]>([]);
  
  // 确认对话框状态
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    type: 'submit' | 'approve' | 'reject' | null;
    planId: string | null;
    planName: string;
  }>({
    open: false,
    type: null,
    planId: null,
    planName: '',
  });

  // 订单审批确认对话框状态
  const [orderConfirmDialog, setOrderConfirmDialog] = useState<{
    open: boolean;
    type: 'first-approve' | 'second-approve' | 'reject' | null;
    orderId: string | null;
    orderNo: string;
    step: number;
  }>({
    open: false,
    type: null,
    orderId: null,
    orderNo: '',
    step: 0,
  });

  const [planFormData, setPlanFormData] = useState({
    planName: '',
    plantingPlanRef: '',
    reason: '',
    notes: '',
  });
  const [editPlanFormData, setEditPlanFormData] = useState({
    planName: '',
    plantingPlanRef: '',
    reason: '',
    notes: '',
    items: [] as PurchasePlanItem[],
  });

  // 创建订单表单数据
  const [orderFormData, setOrderFormData] = useState({
    planId: '',
    supplierId: '',
    supplierName: '',
    expectedDeliveryDate: '',
    notes: '',
    items: [] as OrderItem[],
  });

  // 订单明细编辑
  const [editingOrderItem, setEditingOrderItem] = useState({
    materialCategory: '', // 物料大类：农资/农具
    materialName: '',
    spec: '',
    quantity: 0,
    unit: '袋',
    unitPrice: 0,
  });

  // 到货登记表单数据
  const [deliveryFormData, setDeliveryFormData] = useState({
    deliveryDate: '',
    receiver: '',
    notes: '',
    items: [] as Array<{
      orderItemId: string;
      materialName: string;
      quantity: number;
      maxQuantity: number;
      qualityStatus: '合格' | '不合格' | '待检验';
      notes: string;
    }>,
  });

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

  // 模拟供应商数据
  const suppliers = [
    { id: 'sup-1', name: '北方农资有限公司', type: '种子供应商', level: 'A级' },
    { id: 'sup-2', name: '绿野化肥集团', type: '化肥供应商', level: 'A级' },
    { id: 'sup-3', name: '现代农药科技', type: '农药供应商', level: 'B级' },
    { id: 'sup-4', name: '金田机械设备', type: '农机供应商', level: 'B级' },
    { id: 'sup-5', name: '丰收农资批发', type: '综合供应商', level: 'C级' },
  ];

  // 模拟可采购物料列表
  const availableMaterials = [
    { id: 'mat-1', name: '优质水稻种子', type: '种子', category: '农资', spec: '25kg/袋', unit: '袋', price: 280 },
    { id: 'mat-2', name: '复合肥', type: '化肥', category: '农资', spec: '50kg/袋', unit: '袋', price: 180 },
    { id: 'mat-3', name: '尿素', type: '化肥', category: '农资', spec: '50kg/袋', unit: '袋', price: 120 },
    { id: 'mat-4', name: '吡虫啉可湿性粉剂', type: '农药', category: '农资', spec: '500ml/瓶', unit: '瓶', price: 45 },
    { id: 'mat-5', name: '草甘膦除草剂', type: '农药', category: '农资', spec: '1L/瓶', unit: '瓶', price: 35 },
    { id: 'mat-6', name: '滴灌设备', type: '农具', category: '农具', spec: '套装', unit: '套', price: 850 },
    { id: 'mat-7', name: '手推式喷雾器', type: '农具', category: '农具', spec: '20L', unit: '台', price: 380 },
    { id: 'mat-8', name: '农用薄膜', type: '农具', category: '农具', spec: '100m/卷', unit: '卷', price: 120 },
  ];

  // 模拟采购计划数据
  const [plans, setPlans] = useState<PurchasePlan[]>([
    {
      id: 'plan-1',
      planNo: 'PL-2024-001',
      planName: '春季水稻种植采购计划',
      status: '已批准',
      totalAmount: 185000,
      itemCount: 5,
      items: [
        {
          id: 'item-1',
          materialName: '优质水稻种子',
          materialType: '种子',
          currentStock: 85,
          safeStock: 100,
          estimatedDemand: 200,
          suggestedQuantity: 115,
          unit: '袋',
          estimatedPrice: 280,
          estimatedAmount: 32200,
          priority: '高',
          reason: '库存低于安全库存，春季种植需求大',
        },
        {
          id: 'item-2',
          materialName: '复合肥',
          materialType: '化肥',
          currentStock: 450,
          safeStock: 200,
          estimatedDemand: 500,
          suggestedQuantity: 250,
          unit: '袋',
          estimatedPrice: 180,
          estimatedAmount: 45000,
          priority: '中',
          reason: '春季追肥需求',
        },
        {
          id: 'item-3',
          materialName: '吡虫啉可湿性粉剂',
          materialType: '农药',
          currentStock: 120,
          safeStock: 50,
          estimatedDemand: 150,
          suggestedQuantity: 80,
          unit: '瓶',
          estimatedPrice: 45,
          estimatedAmount: 3600,
          priority: '低',
          reason: '虫害防治储备',
        },
      ],
      reason: '春季水稻种植季节即将到来，根据种植计划需提前采购农资',
      plantingPlanRef: '2024年春季水稻种植计划',
      marketAnalysis: '近期种子价格稳定，化肥价格小幅上涨5%，建议尽快采购',
      createdBy: '张三',
      createdAt: '2024-03-01',
      approvedBy: '李经理',
      approvedAt: '2024-03-02',
    },
    {
      id: 'plan-2',
      planNo: 'PL-2024-002',
      planName: '农机设备维护用品采购',
      status: '待审批',
      totalAmount: 42000,
      itemCount: 3,
      items: [
        {
          id: 'item-4',
          materialName: '机油',
          materialType: '维护用品',
          currentStock: 20,
          safeStock: 30,
          estimatedDemand: 50,
          suggestedQuantity: 60,
          unit: '桶',
          estimatedPrice: 350,
          estimatedAmount: 21000,
          priority: '高',
          reason: '库存不足，农机保养季节需求大',
        },
      ],
      reason: '农机即将进入春季保养期，需提前准备维护用品',
      createdBy: '李四',
      createdAt: '2024-03-10',
    },
  ]);

  // 模拟采购订单数据
  const [orders, setOrders] = useState<PurchaseOrder[]>([
    {
      id: 'order-1',
      orderNo: 'PO-2024-001',
      planId: 'plan-1',
      planName: '春季水稻种植采购计划',
      supplierId: 'sup-1',
      supplierName: '北方农资有限公司',
      status: '部分到货',
      approvalStatus: '已通过',
      totalAmount: 32200,
      paidAmount: 0,
      items: [
        {
          id: 'oi-1',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          quantity: 115,
          receivedQuantity: 50,
          unit: '袋',
          unitPrice: 280,
          amount: 32200,
        },
      ],
      deliveries: [
        {
          id: 'del-1',
          deliveryNo: 'DEL-2024-001',
          deliveryDate: '2024-03-15',
          items: [
            {
              orderItemId: 'oi-1',
              materialName: '优质水稻种子',
              quantity: 50,
              qualityStatus: '合格',
            },
          ],
          receiver: '王五',
          notes: '第一批到货，质量良好',
        },
      ],
      approvalFlow: [
        {
          id: 'app-1',
          step: 1,
          approverRole: '部门负责人',
          approverName: '李经理',
          status: '已通过',
          comment: '同意采购',
          approvedAt: '2024-03-05 10:30',
        },
        {
          id: 'app-2',
          step: 2,
          approverRole: '财务部',
          approverName: '赵会计',
          status: '已通过',
          comment: '预算充足，同意',
          approvedAt: '2024-03-05 14:20',
        },
      ],
      createdBy: '张三',
      createdAt: '2024-03-05',
      expectedDeliveryDate: '2024-03-20',
    },
    {
      id: 'order-2',
      orderNo: 'PO-2024-002',
      supplierId: 'sup-2',
      supplierName: '中化化肥',
      status: '待复审',
      approvalStatus: '待复审',
      totalAmount: 45000,
      paidAmount: 0,
      items: [
        {
          id: 'oi-2',
          materialId: 'mat-2',
          materialName: '复合肥',
          spec: '50kg/袋',
          quantity: 250,
          receivedQuantity: 0,
          unit: '袋',
          unitPrice: 180,
          amount: 45000,
        },
      ],
      deliveries: [],
      approvalFlow: [
        {
          id: 'app-3',
          step: 1,
          approverRole: '部门负责人',
          approverName: '李经理',
          status: '已通过',
          comment: '同意采购',
          approvedAt: '2024-03-12 09:15',
        },
        {
          id: 'app-4',
          step: 2,
          approverRole: '财务部（复审）',
          status: '待审批',
        },
      ],
      createdBy: '张三',
      createdAt: '2024-03-12',
      expectedDeliveryDate: '2024-03-25',
    },
    {
      id: 'order-3',
      orderNo: 'PO-2024-003',
      supplierId: 'sup-1',
      supplierName: '北方农资有限公司',
      status: '已完成',
      approvalStatus: '已通过',
      totalAmount: 56000,
      paidAmount: 56000,
      items: [
        {
          id: 'oi-3',
          materialId: 'mat-1',
          materialName: '优质水稻种子',
          spec: '25kg/袋',
          quantity: 200,
          receivedQuantity: 200,
          unit: '袋',
          unitPrice: 280,
          amount: 56000,
        },
      ],
      deliveries: [
        {
          id: 'del-2',
          deliveryNo: 'DEL-2024-002',
          deliveryDate: '2024-02-15',
          items: [
            {
              orderItemId: 'oi-3',
              materialName: '优质水稻种子',
              quantity: 200,
              qualityStatus: '合格',
            },
          ],
          receiver: '王五',
          notes: '全部到货，质量检验合格',
        },
      ],
      approvalFlow: [
        {
          id: 'app-5',
          step: 1,
          approverRole: '部门负责人',
          approverName: '李经理',
          status: '已通过',
          approvedAt: '2024-02-10 10:00',
        },
        {
          id: 'app-6',
          step: 2,
          approverRole: '财务部',
          approverName: '赵会计',
          status: '已通过',
          approvedAt: '2024-02-10 15:30',
        },
      ],
      createdBy: '张三',
      createdAt: '2024-02-10',
      expectedDeliveryDate: '2024-02-15',
      actualDeliveryDate: '2024-02-15',
    },
    {
      id: 'order-4',
      orderNo: 'PO-2024-004',
      supplierId: 'sup-3',
      supplierName: '现代农药科技',
      status: '待审批',
      approvalStatus: '待初审',
      totalAmount: 8500,
      paidAmount: 0,
      items: [
        {
          id: 'oi-4',
          materialId: 'mat-4',
          materialName: '吡虫啉可湿性粉剂',
          spec: '500ml/瓶',
          quantity: 100,
          receivedQuantity: 0,
          unit: '瓶',
          unitPrice: 45,
          amount: 4500,
        },
        {
          id: 'oi-5',
          materialId: 'mat-5',
          materialName: '草甘膦除草剂',
          spec: '1L/瓶',
          quantity: 100,
          receivedQuantity: 0,
          unit: '瓶',
          unitPrice: 35,
          amount: 3500,
        },
      ],
      deliveries: [],
      approvalFlow: [
        {
          id: 'app-7',
          step: 1,
          approverRole: '部门负责人（初审）',
          status: '待审批',
        },
        {
          id: 'app-8',
          step: 2,
          approverRole: '财务部（复审）',
          status: '待审批',
        },
      ],
      createdBy: '张三',
      createdAt: '2024-03-18',
      expectedDeliveryDate: '2024-03-30',
    },
  ]);

  // 获取状态颜色
  const getPlanStatusColor = (status: PlanStatus) => {
    switch (status) {
      case '草稿': return 'bg-muted text-muted-foreground';
      case '待审批': return 'bg-warning-muted text-warning-muted-foreground';
      case '已批准': return 'bg-success-muted text-success-muted-foreground';
      case '已驳回': return 'bg-error-muted text-error-muted-foreground';
      case '执行中': return 'bg-info-muted text-info-muted-foreground';
      case '已完成': return 'bg-accent-muted text-accent-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getOrderStatusColor = (status: OrderStatus) => {
    switch (status) {
      case '待审批': return 'bg-warning-muted text-warning-muted-foreground';
      case '待复审': return 'bg-warning-muted text-warning-muted-foreground';
      case '已下单': return 'bg-info-muted text-info-muted-foreground';
      case '部分到货': return 'bg-accent-muted text-accent-foreground';
      case '已完成': return 'bg-success-muted text-success-muted-foreground';
      case '已取消': return 'bg-error-muted text-error';
      default: return 'bg-muted text-muted-foreground';
    }
  };

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

  // 提交审批
  const handleSubmitPlan = (plan: PurchasePlan) => {
    setConfirmDialog({
      open: true,
      type: 'submit',
      planId: plan.id,
      planName: plan.planName,
    });
  };

  // 批准计划
  const handleApprovePlan = (plan: PurchasePlan) => {
    setConfirmDialog({
      open: true,
      type: 'approve',
      planId: plan.id,
      planName: plan.planName,
    });
  };

  // 驳回计划
  const handleRejectPlan = (plan: PurchasePlan) => {
    setConfirmDialog({
      open: true,
      type: 'reject',
      planId: plan.id,
      planName: plan.planName,
    });
  };

  // 确认操作
  const handleConfirmAction = () => {
    const { type, planId } = confirmDialog;
    if (!planId) return;

    switch (type) {
      case 'submit':
        setPlans(plans.map(p =>
          p.id === planId
            ? { ...p, status: '待审批' }
            : p
        ));
        toast.success('采购计划已提交审批！');
        break;
      
      case 'approve':
        setPlans(plans.map(p =>
          p.id === planId
            ? { ...p, status: '已批准', approvedBy: '李经理', approvedAt: new Date().toLocaleString('zh-CN') }
            : p
        ));
        toast.success('采购计划已批准！');
        break;
      
      case 'reject':
        setPlans(plans.map(p =>
          p.id === planId ? { ...p, status: '已驳回' } : p
        ));
        toast.success('采购计划已驳回！');
        break;
    }

    // 关闭对话框
    setConfirmDialog({
      open: false,
      type: null,
      planId: null,
      planName: '',
    });
  };

  // 查看计划详情
  const handleViewPlan = (plan: PurchasePlan) => {
    setSelectedPlan(plan);
    setShowViewPlanDialog(true);
  };

  // 编辑计划
  const handleEditPlan = (plan: PurchasePlan) => {
    if (plan.status !== '草稿' && plan.status !== '已驳回') {
      toast.error('只能编辑草稿或已驳回的计划');
      return;
    }
    setSelectedPlan(plan);
    setEditPlanFormData({
      planName: plan.planName,
      plantingPlanRef: plan.plantingPlanRef || '',
      reason: plan.reason,
      notes: plan.notes || '',
      items: plan.items,
    });
    setShowEditPlanDialog(true);
  };

  // 保存编辑的计划
  const handleSaveEditPlan = () => {
    if (!editPlanFormData.planName) {
      toast.error('请填写计划名称');
      return;
    }

    if (!selectedPlan) return;

    const totalAmount = editPlanFormData.items.reduce((sum, item) => sum + item.estimatedAmount, 0);

    const updatedPlan: PurchasePlan = {
      ...selectedPlan,
      planName: editPlanFormData.planName,
      plantingPlanRef: editPlanFormData.plantingPlanRef,
      reason: editPlanFormData.reason,
      notes: editPlanFormData.notes,
      items: editPlanFormData.items,
      totalAmount,
      itemCount: editPlanFormData.items.length,
    };

    setPlans(plans.map(p => p.id === selectedPlan.id ? updatedPlan : p));
    setShowEditPlanDialog(false);
    toast.success('采购计划已更新');
  };

  // 删除计划明细
  const handleRemovePlanItem = (itemId: string) => {
    setEditPlanFormData({
      ...editPlanFormData,
      items: editPlanFormData.items.filter(item => item.id !== itemId),
    });
    toast.success('物料已删除');
  };

  // 打开初审确认对话框
  const handleOpenFirstApprove = (order: PurchaseOrder) => {
    setOrderConfirmDialog({
      open: true,
      type: 'first-approve',
      orderId: order.id,
      orderNo: order.orderNo,
      step: 1,
    });
  };

  // 打开复审确认对话框
  const handleOpenSecondApprove = (order: PurchaseOrder) => {
    setOrderConfirmDialog({
      open: true,
      type: 'second-approve',
      orderId: order.id,
      orderNo: order.orderNo,
      step: 2,
    });
  };

  // 打开驳回确认对话框
  const handleOpenRejectOrder = (order: PurchaseOrder, step: number) => {
    setOrderConfirmDialog({
      open: true,
      type: 'reject',
      orderId: order.id,
      orderNo: order.orderNo,
      step,
    });
  };

  // 确认订单审批操作
  const handleConfirmOrderAction = () => {
    const { type, orderId, step } = orderConfirmDialog;
    if (!orderId) return;

    switch (type) {
      case 'first-approve':
        // 初审通过
        setOrders(orders.map(o =>
          o.id === orderId
            ? {
                ...o,
                approvalStatus: '待复审',
                status: '待复审',
                approvalFlow: o.approvalFlow.map((a, i) =>
                  a.step === 1
                    ? { ...a, status: '已通过', approverName: '李经理', approvedAt: new Date().toLocaleString('zh-CN'), comment: '初审通过，同意采购' }
                    : a
                ),
              }
            : o
        ));
        toast.success('初审通过！订单已进入复审阶段');
        break;
      
      case 'second-approve':
        // 复审通过
        setOrders(orders.map(o =>
          o.id === orderId
            ? {
                ...o,
                approvalStatus: '已通过',
                status: '已下单',
                approvalFlow: o.approvalFlow.map((a, i) =>
                  a.step === 2
                    ? { ...a, status: '已通过', approverName: '赵会计', approvedAt: new Date().toLocaleString('zh-CN'), comment: '复审通过，预算充足，同意采购' }
                    : a
                ),
              }
            : o
        ));
        toast.success('复审通过！订单审批完成，已下单');
        break;
      
      case 'reject':
        // 驳回订单
        setOrders(orders.map(o =>
          o.id === orderId
            ? {
                ...o,
                approvalStatus: '已驳回',
                status: '已取消',
                approvalFlow: o.approvalFlow.map((a, i) =>
                  a.step === step
                    ? { ...a, status: '已驳回', approverName: step === 1 ? '李经理' : '赵会计', approvedAt: new Date().toLocaleString('zh-CN'), comment: '不符合采购条件，驳回' }
                    : a
                ),
              }
            : o
        ));
        toast.error(`订单已被${step === 1 ? '初审' : '复审'}驳回`);
        break;
    }

    // 关闭对话框
    setOrderConfirmDialog({
      open: false,
      type: null,
      orderId: null,
      orderNo: '',
      step: 0,
    });
  };

  // 智能生成采购建议
  const handleGenerateSmartSuggestion = () => {
    // 模拟库存数据和种植计划需求
    const mockInventory = [
      { name: '优质水稻种子', type: '种子', currentStock: 45, safeStock: 100, unit: '袋', avgPrice: 280, plantingDemand: 200 },
      { name: '复合肥', type: '化肥', currentStock: 120, safeStock: 200, unit: '袋', avgPrice: 180, plantingDemand: 450 },
      { name: '尿素', type: '化肥', currentStock: 180, safeStock: 150, unit: '袋', avgPrice: 120, plantingDemand: 300 },
      { name: '吡虫啉可湿性粉剂', type: '农药', currentStock: 25, safeStock: 50, unit: '瓶', avgPrice: 45, plantingDemand: 100 },
      { name: '草甘膦除草剂', type: '农药', currentStock: 80, safeStock: 60, unit: '瓶', avgPrice: 35, plantingDemand: 120 },
      { name: '机油', type: '维护用品', currentStock: 15, safeStock: 30, unit: '桶', avgPrice: 350, plantingDemand: 50 },
      { name: '柴油滤芯', type: '维护用品', currentStock: 8, safeStock: 20, unit: '个', avgPrice: 85, plantingDemand: 40 },
    ];

    // 市场行情数据（模拟价格趋势）
    const marketTrends: Record<string, { trend: 'up' | 'down' | 'stable', rate: number, suggestion: string }> = {
      '种子': { trend: 'stable', rate: 0, suggestion: '价格稳定，可按计划采购' },
      '化肥': { trend: 'up', rate: 5, suggestion: '价格上涨趋势，建议尽快采购' },
      '农药': { trend: 'down', rate: -3, suggestion: '价格小幅下降，可适当延后采购' },
      '维护用品': { trend: 'stable', rate: 1, suggestion: '价格基本稳定' },
    };

    // 智能计算建议采购量和优先级
    const suggestions: PurchasePlanItem[] = mockInventory.map((item, index) => {
      const stockDeficit = item.safeStock - item.currentStock; // 库存缺口
      const plantingNeed = item.plantingDemand - item.currentStock; // 种植需求缺口
      const marketInfo = marketTrends[item.type];
      
      // 计算建议采购量：取库存缺口和种植需求缺口的较大值
      let suggestedQty = Math.max(stockDeficit, plantingNeed);
      suggestedQty = Math.max(suggestedQty, 0); // 确保不为负数
      
      // 如果价格上涨，增加10%库存
      if (marketInfo.trend === 'up') {
        suggestedQty = Math.ceil(suggestedQty * 1.1);
      }
      
      // 确定优先级
      let priority: '高' | '中' | '低' = '低';
      let reason = '';
      
      if (item.currentStock < item.safeStock * 0.5) {
        // 库存严重不足（低于安全库存50%）
        priority = '高';
        reason = `库存严重不足（${item.currentStock}${item.unit}），远低于安全库存（${item.safeStock}${item.unit}），`;
      } else if (item.currentStock < item.safeStock) {
        // 库存低于安全库存
        priority = '中';
        reason = `库存不足（${item.currentStock}${item.unit}），低于安全库存（${item.safeStock}${item.unit}），`;
      }
      
      // 考虑种植计划需求
      if (item.plantingDemand > item.currentStock) {
        priority = priority === '低' ? '中' : '高';
        reason += `种植计划需求${item.plantingDemand}${item.unit}，当前库存无法满足，`;
      }
      
      // 考虑市场行情
      if (marketInfo.trend === 'up') {
        reason += `${marketInfo.suggestion}，`;
        if (priority === '低') priority = '中';
      } else if (marketInfo.trend === 'down') {
        reason += `价格下降${Math.abs(marketInfo.rate)}%，可适当延后采购`;
        if (suggestedQty > 0 && priority === '高') priority = '中';
      } else {
        reason += `${marketInfo.suggestion}`;
      }
      
      return {
        id: `suggested-${index + 1}`,
        materialName: item.name,
        materialType: item.type,
        currentStock: item.currentStock,
        safeStock: item.safeStock,
        estimatedDemand: item.plantingDemand,
        suggestedQuantity: suggestedQty,
        unit: item.unit,
        estimatedPrice: item.avgPrice,
        estimatedAmount: suggestedQty * item.avgPrice,
        priority,
        reason: reason.replace(/，$/, ''), // 移除末尾逗号
      };
    }).filter(item => item.suggestedQuantity > 0); // 只显示需要采购的物料

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

    setSuggestedItems(suggestions);
    // 默认全选所有建议项
    setSelectedSuggestionIds(suggestions.map(s => s.id));
    setShowSmartSuggestionDialog(true);
    
    // 显示分析结果提示
    const highPriorityCount = suggestions.filter(s => s.priority === '高').length;
    const totalAmount = suggestions.reduce((sum, s) => sum + s.estimatedAmount, 0);
    
    toast.success(
      `智能分析完成！检测到${suggestions.length}项需要采购的物料，其中${highPriorityCount}项为高优先级，预计总金额¥${totalAmount.toLocaleString()}`
    );
  };

  // 从智能建议创建采购计划
  const handleCreatePlanFromSuggestion = () => {
    if (!planFormData.planName) {
      toast.error('请填写计划名称');
      return;
    }

    if (selectedSuggestionIds.length === 0) {
      toast.error('请至少勾选一项物料');
      return;
    }

    // 只保存被勾选的物料
    const selectedItems = suggestedItems.filter(item => selectedSuggestionIds.includes(item.id));
    const totalAmount = selectedItems.reduce((sum, item) => sum + item.estimatedAmount, 0);
    
    // 生成市场分析说明
    const marketAnalysis = `当前市场行情分析：
- 种子类：价格稳定，可按计划采购
- 化肥类：价格上涨趋势约5%，建议尽快采购锁定价格
- 农药类：价格小幅下降3%，可适当延后非紧急采购
- 维护用品：价格基本稳定，正常采购即可

综合建议：本期采购以高优先级物料为主，尤其是库存严重不足和化肥类物资，建议在未来7-10天内完成采购。`;

    const newPlan: PurchasePlan = {
      id: `plan-${Date.now()}`,
      planNo: `PL-${new Date().getFullYear()}-${String(plans.length + 1).padStart(3, '0')}`,
      planName: planFormData.planName,
      status: '草稿',
      totalAmount,
      itemCount: selectedItems.length,
      items: selectedItems,
      reason: planFormData.reason || '根据智能分析系统，综合当前库存状态、种植计划需求和市场行情自动生成',
      plantingPlanRef: planFormData.plantingPlanRef || '2024年春季种植计划',
      marketAnalysis,
      createdBy: '当前用户',
      createdAt: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }),
      notes: planFormData.notes,
    };

    setPlans([newPlan, ...plans]);
    setShowSmartSuggestionDialog(false);
    toast.success(`采购计划创建成功！已添加 ${selectedItems.length} 项物料`);
    
    // 重置表单
    setPlanFormData({
      planName: '',
      plantingPlanRef: '',
      reason: '',
      notes: '',
    });
    setSuggestedItems([]);
    setSelectedSuggestionIds([]);
  };

  // 添加订单物料
  const handleAddOrderItem = () => {
    if (!editingOrderItem.materialName || !editingOrderItem.quantity || !editingOrderItem.unitPrice) {
      toast.error('请填写完整的物料信息');
      return;
    }

    const newItem: OrderItem = {
      id: `oi-${Date.now()}`,
      materialId: `mat-${Date.now()}`,
      materialName: editingOrderItem.materialName,
      spec: editingOrderItem.spec,
      quantity: editingOrderItem.quantity,
      receivedQuantity: 0,
      unit: editingOrderItem.unit,
      unitPrice: editingOrderItem.unitPrice,
      amount: editingOrderItem.quantity * editingOrderItem.unitPrice,
    };

    setOrderFormData({
      ...orderFormData,
      items: [...orderFormData.items, newItem],
    });

    // 重置编辑项
    setEditingOrderItem({
      materialName: '',
      spec: '',
      quantity: 0,
      unit: '袋',
      unitPrice: 0,
    });

    toast.success('物料已添加');
  };

  // 删除订单物料
  const handleRemoveOrderItem = (itemId: string) => {
    setOrderFormData({
      ...orderFormData,
      items: orderFormData.items.filter(item => item.id !== itemId),
    });
    toast.success('物料已删除');
  };

  // 创建采购订单
  const handleCreateOrder = () => {
    if (!orderFormData.supplierId) {
      toast.error('请选择供应商');
      return;
    }

    if (!orderFormData.expectedDeliveryDate) {
      toast.error('请选择预计交货日期');
      return;
    }

    if (orderFormData.items.length === 0) {
      toast.error('请添加采购物料');
      return;
    }

    const totalAmount = orderFormData.items.reduce((sum, item) => sum + item.amount, 0);

    // 创建审批流程
    const approvalFlow: ApprovalRecord[] = [
      {
        id: 'app-1',
        step: 1,
        approverRole: '部门负责人（初审）',
        status: '待审批',
      },
      {
        id: 'app-2',
        step: 2,
        approverRole: '财务部（复审）',
        status: '待审批',
      },
    ];

    const newOrder: PurchaseOrder = {
      id: `order-${Date.now()}`,
      orderNo: `PO-${new Date().getFullYear()}-${String(orders.length + 1).padStart(3, '0')}`,
      planId: orderFormData.planId,
      planName: orderFormData.planId ? plans.find(p => p.id === orderFormData.planId)?.planName : undefined,
      supplierId: orderFormData.supplierId,
      supplierName: orderFormData.supplierName,
      status: '待审批',
      approvalStatus: '待初审',
      totalAmount,
      paidAmount: 0,
      items: orderFormData.items,
      deliveries: [],
      approvalFlow,
      createdBy: '当前用户',
      createdAt: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }),
      expectedDeliveryDate: orderFormData.expectedDeliveryDate,
      notes: orderFormData.notes,
    };

    setOrders([newOrder, ...orders]);
    setShowOrderDialog(false);
    
    // 重置表单
    setOrderFormData({
      planId: '',
      supplierId: '',
      supplierName: '',
      expectedDeliveryDate: '',
      notes: '',
      items: [],
    });

    toast.success('采购订单创建成功，已进入审批流程！');
  };

  // 打开到货登记对话框
  const handleOpenDeliveryDialog = (order: PurchaseOrder) => {
    setSelectedOrder(order);
    
    // 初始化到货登记项（只包含未完全到货的物料）
    const deliveryItems = order.items.map(item => ({
      orderItemId: item.id,
      materialName: item.materialName,
      quantity: 0,
      maxQuantity: item.quantity - item.receivedQuantity,
      qualityStatus: '合格' as '合格' | '不合格' | '待检验',
      notes: '',
    })).filter(item => item.maxQuantity > 0);
    
    setDeliveryFormData({
      deliveryDate: new Date().toISOString().split('T')[0],
      receiver: '当前用户',
      notes: '',
      items: deliveryItems,
    });
    
    setShowDeliveryDialog(true);
  };

  // 确认到货登记
  const handleConfirmDelivery = () => {
    if (!deliveryFormData.deliveryDate) {
      toast.error('请选择到货日期');
      return;
    }

    if (!deliveryFormData.receiver) {
      toast.error('请填写收货人');
      return;
    }

    // 检查是否至少有一项物料填写了到货数量
    const hasDeliveryQuantity = deliveryFormData.items.some(item => item.quantity > 0);
    if (!hasDeliveryQuantity) {
      toast.error('请至少填写一项物料的到货数量');
      return;
    }

    // 验证到货数量不能超过剩余待收数量
    const hasExceeded = deliveryFormData.items.some(item => item.quantity > item.maxQuantity);
    if (hasExceeded) {
      toast.error('到货数量不能超过剩余待收数量');
      return;
    }

    if (!selectedOrder) return;

    // 创建新的到货记录
    const newDelivery: Delivery = {
      id: `del-${Date.now()}`,
      deliveryNo: `DEL-${new Date().getFullYear()}-${String(Date.now()).slice(-3)}`,
      deliveryDate: deliveryFormData.deliveryDate,
      items: deliveryFormData.items
        .filter(item => item.quantity > 0)
        .map(item => ({
          orderItemId: item.orderItemId,
          materialName: item.materialName,
          quantity: item.quantity,
          qualityStatus: item.qualityStatus,
          notes: item.notes,
        })),
      receiver: deliveryFormData.receiver,
      notes: deliveryFormData.notes,
    };

    // 更新订单的到货记录和已收货数量
    setOrders(orders.map(o => {
      if (o.id === selectedOrder.id) {
        // 更新订单项的已收货数量
        const updatedItems = o.items.map(item => {
          const deliveryItem = deliveryFormData.items.find(d => d.orderItemId === item.id);
          if (deliveryItem && deliveryItem.quantity > 0) {
            return {
              ...item,
              receivedQuantity: item.receivedQuantity + deliveryItem.quantity,
            };
          }
          return item;
        });

        // 检查是否全部到货
        const allReceived = updatedItems.every(item => item.receivedQuantity >= item.quantity);
        const someReceived = updatedItems.some(item => item.receivedQuantity > 0);

        return {
          ...o,
          items: updatedItems,
          deliveries: [...o.deliveries, newDelivery],
          status: allReceived ? '已完成' : someReceived ? '部分到货' : o.status,
          actualDeliveryDate: allReceived ? deliveryFormData.deliveryDate : o.actualDeliveryDate,
        };
      }
      return o;
    }));

    // 模拟库存系统联动 - 自动更新库存
    const inventoryUpdate = deliveryFormData.items
      .filter(item => item.quantity > 0)
      .map(item => ({
        materialName: item.materialName,
        quantity: item.quantity,
        qualityStatus: item.qualityStatus,
        deliveryDate: deliveryFormData.deliveryDate,
        receiver: deliveryFormData.receiver,
      }));

    console.log('📦 库存系统自动更新:', inventoryUpdate);

    toast.success(`到货登记成功！已登记 ${newDelivery.items.length} 项物料`, {
      description: `收货人：${deliveryFormData.receiver} | 库存已自动更新`,
    });

    // 重置表单
    setDeliveryFormData({
      deliveryDate: '',
      receiver: '',
      notes: '',
      items: [],
    });
    setShowDeliveryDialog(false);
  };

  // 统计数据
  const totalPlans = plans.length;
  const pendingPlans = plans.filter(p => p.status === '待审批').length;
  const totalOrders = orders.length;
  const pendingOrders = orders.filter(o => o.approvalStatus === '待初审' || o.approvalStatus === '待复审').length;
  const totalAmount = orders.reduce((sum, o) => sum + o.totalAmount, 0);
  const completedOrders = orders.filter(o => o.status === '已完成').length;

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">采购管理</h2>
          <p className="text-muted-foreground">
            智能采购计划与订单管理
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出报表
          </Button>
        </div>
      </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-info">{totalPlans}</p>
              <p className="text-xs text-warning mt-1">
                {pendingPlans} 项待审批
              </p>
            </div>
            <FileText 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-accent">{totalOrders}</p>
              <p className="text-xs text-warning mt-1">
                {pendingOrders} 项审批中
              </p>
            </div>
            <ShoppingCart className="w-12 h-12 text-accent 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">
                ¥{(totalAmount / 10000).toFixed(1)}万
              </p>
            </div>
            <DollarSign className="w-12 h-12 text-success 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-warning">{completedOrders}</p>
              <p className="text-xs text-success mt-1">
                {totalOrders > 0 ? ((completedOrders / totalOrders) * 100).toFixed(0) : 0}% 完成率
              </p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="plan">采购计划</TabsTrigger>
          <TabsTrigger value="order">采购订单</TabsTrigger>
        </TabsList>

        {/* 采购计划 */}
        <TabsContent value="plan" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-info-muted border-info">
            <div className="flex items-start gap-2">
              <Zap className="w-5 h-5 text-info 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>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="计划状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="草稿">草稿</SelectItem>
                  <SelectItem value="待审批">待审批</SelectItem>
                  <SelectItem value="已批准">已批准</SelectItem>
                  <SelectItem value="执行中">执行中</SelectItem>
                  <SelectItem value="已完成">已完成</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button className="bg-success hover:bg-success/90" onClick={handleGenerateSmartSuggestion}>
              <Zap className="w-4 h-4 mr-2" />
              智能生成采购建议
            </Button>
          </div>

          {/* 采购计划列表 */}
          <div className="space-y-4">
            {plans.map(plan => (
              <Card key={plan.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 bg-info-muted rounded-lg">
                      <FileText className="w-6 h-6 text-info" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{plan.planName}</h4>
                        <Badge className={getPlanStatusColor(plan.status)}>
                          {plan.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        计划编号: {plan.planNo} | 创建人: {plan.createdBy} | {plan.createdAt}
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    {plan.status === '草稿' && (
                      <Button size="sm" className="bg-info hover:bg-info/90" onClick={() => handleSubmitPlan(plan)}>
                        <Send className="w-4 h-4 mr-2" />
                        提交审批
                      </Button>
                    )}
                    {plan.status === '待审批' && (
                      <>
                        <Button size="sm" className="bg-success hover:bg-success/90" onClick={() => handleApprovePlan(plan)}>
                          <ThumbsUp className="w-4 h-4 mr-2" />
                          批准
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleRejectPlan(plan)}>
                          <ThumbsDown className="w-4 h-4 mr-2" />
                          驳回
                        </Button>
                      </>
                    )}
                    <Button size="sm" variant="outline" onClick={() => handleViewPlan(plan)}>
                      <Eye className="w-4 h-4" />
                    </Button>
                    {(plan.status === '草稿' || plan.status === '已驳回') && (
                      <Button size="sm" variant="outline" onClick={() => handleEditPlan(plan)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-4 mb-4">
                  <div className="p-3 bg-success-muted rounded-lg">
                    <p className="text-xs text-muted-foreground">采购金额</p>
                    <p className="mt-1 text-xl font-medium text-success">
                      ¥{plan.totalAmount.toLocaleString()}
                    </p>
                  </div>
                  <div className="p-3 bg-info-muted rounded-lg">
                    <p className="text-xs text-muted-foreground">物料数量</p>
                    <p className="mt-1 text-xl font-medium text-info">
                      {plan.itemCount} 项
                    </p>
                  </div>
                  <div className="p-3 bg-accent-muted rounded-lg">
                    <p className="text-xs text-muted-foreground">关联计划</p>
                    <p className="mt-1 text-sm font-medium text-accent">
                      {plan.plantingPlanRef || '无'}
                    </p>
                  </div>
                </div>

                <div className="p-3 bg-muted rounded-lg mb-3">
                  <p className="text-xs text-muted-foreground mb-2">采购原因:</p>
                  <p className="text-sm">{plan.reason}</p>
                </div>

                {plan.marketAnalysis && (
                  <div className="p-3 bg-warning-muted border-warning rounded-lg mb-3">
                    <p className="text-xs text-muted-foreground mb-2">📊 市场分析:</p>
                    <p className="text-sm text-muted-foreground">{plan.marketAnalysis}</p>
                  </div>
                )}

                {/* 采购明细 */}
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-muted">
                      <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-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>
                      {plan.items.slice(0, 3).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.materialType}
                            </Badge>
                          </td>
                          <td className="text-right p-2">
                            <span className={item.currentStock < item.safeStock ? 'text-red-600 font-medium' : ''}>
                              {item.currentStock} {item.unit}
                            </span>
                          </td>
                          <td className="text-right p-2">{item.safeStock} {item.unit}</td>
                          <td className="text-right p-2">{item.estimatedDemand} {item.unit}</td>
                          <td className="text-right p-2 font-medium text-blue-600">
                            {item.suggestedQuantity} {item.unit}
                          </td>
                          <td className="text-right p-2">¥{item.estimatedPrice}</td>
                          <td className="text-right p-2 font-medium">
                            ¥{item.estimatedAmount.toLocaleString()}
                          </td>
                          <td className="p-2">
                            <Badge className={getPriorityColor(item.priority)}>
                              {item.priority}
                            </Badge>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {plan.approvedBy && (
                  <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <p className="text-sm text-green-900">
                      ✅ 已由 <strong>{plan.approvedBy}</strong> 于 {plan.approvedAt} 批准
                    </p>
                  </div>
                )}
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 采购订单 */}
        <TabsContent value="order" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <ShoppingCart className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">采购订单管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>在线创建</strong>: 关联供应商和商品，在线创建采购订单</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 items-center justify-between">
            <div className="flex gap-2">
              <Select>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="订单状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="待审批">待初审</SelectItem>
                  <SelectItem value="待复审">待复审</SelectItem>
                  <SelectItem value="已下单">已下单</SelectItem>
                  <SelectItem value="部分到货">部分到货</SelectItem>
                  <SelectItem value="已完成">已完成</SelectItem>
                  <SelectItem value="已取消">已取消</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowOrderDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              创建采购订单
            </Button>
          </div>

          {/* 订单列表 */}
          <div className="space-y-4">
            {orders.map(order => {
              const deliveryProgress = order.items.reduce((sum, item) => sum + item.receivedQuantity, 0) / 
                                      order.items.reduce((sum, item) => sum + item.quantity, 0) * 100;
              
              return (
                <Card key={order.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">
                        <ShoppingCart className="w-6 h-6 text-purple-600" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>采购订单 {order.orderNo}</h4>
                          <Badge className={getOrderStatusColor(order.status)}>
                            {order.status}
                          </Badge>
                          <Badge variant="outline">
                            {order.approvalStatus}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          供应商: {order.supplierName} | 创建人: {order.createdBy} | {order.createdAt}
                        </p>
                        {order.planName && (
                          <p className="text-xs text-blue-600 mt-1">
                            📋 关联计划: {order.planName}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="flex gap-2">
                      {order.approvalStatus === '待初审' && (
                        <>
                          <Button size="sm" className="bg-green-600 hover:bg-green-700" onClick={() => handleOpenFirstApprove(order)}>
                            <CheckCircle2 className="w-4 h-4 mr-2" />
                            初审通过
                          </Button>
                          <Button size="sm" variant="outline" className="border-red-200 hover:bg-red-50" onClick={() => handleOpenRejectOrder(order, 1)}>
                            <XCircle className="w-4 h-4 mr-2 text-red-600" />
                            初审驳回
                          </Button>
                        </>
                      )}
                      {order.approvalStatus === '待复审' && (
                        <>
                          <Button size="sm" className="bg-blue-600 hover:bg-blue-700" onClick={() => handleOpenSecondApprove(order)}>
                            <CheckCheck className="w-4 h-4 mr-2" />
                            复审通过
                          </Button>
                          <Button size="sm" variant="outline" className="border-red-200 hover:bg-red-50" onClick={() => handleOpenRejectOrder(order, 2)}>
                            <XCircle className="w-4 h-4 mr-2 text-red-600" />
                            复审驳回
                          </Button>
                        </>
                      )}
                      <Button size="sm" variant="outline" onClick={() => { setSelectedOrder(order); setShowApprovalDialog(true); }}>
                        <Eye className="w-4 h-4 mr-2" />
                        审批流程
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-4 gap-4 mb-4">
                    <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">
                        ¥{order.totalAmount.toLocaleString()}
                      </p>
                    </div>
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">已付金额</p>
                      <p className="mt-1 text-xl font-medium text-blue-600">
                        ¥{order.paidAmount.toLocaleString()}
                      </p>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">预计交货</p>
                      <p className="mt-1 text-sm font-medium text-purple-600">
                        {order.expectedDeliveryDate}
                      </p>
                    </div>
                    <div className="p-3 bg-orange-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">到货进度</p>
                      <p className="mt-1 text-xl font-medium text-orange-600">
                        {deliveryProgress.toFixed(0)}%
                      </p>
                    </div>
                  </div>

                  {/* 到货进度条 - 数据来自库存管理系统的入库记录 */}
                  <div className="mb-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">到货进度（由库存入库自动计算）</span>
                      <span className="text-sm font-medium">{deliveryProgress.toFixed(0)}%</span>
                    </div>
                    <Progress value={deliveryProgress} className="h-2" />
                  </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-right p-2">金额</th>
                        </tr>
                      </thead>
                      <tbody>
                        {order.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="text-right p-2">
                              <span className={item.receivedQuantity === item.quantity ? 'text-green-600 font-medium' : 'text-orange-600 font-medium'}>
                                {item.receivedQuantity} {item.unit}
                              </span>
                            </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>

                  {/* 到货记录 - 来自库存管理系统的入库记录 */}
                  {order.deliveries.length > 0 && (
                    <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                      <p className="text-xs text-blue-900 mb-2">
                        📦 到货记录 ({order.deliveries.length}次) - 数据来自库存管理系统:
                      </p>
                      {order.deliveries.map(delivery => (
                        <div key={delivery.id} className="mb-2 last:mb-0">
                          <div className="text-sm">
                            <span className="font-medium">{delivery.deliveryNo}</span>
                            <span className="mx-2">|</span>
                            <span>{delivery.deliveryDate}</span>
                            <span className="mx-2">|</span>
                            <span>收货人: {delivery.receiver}</span>
                          </div>
                          {delivery.items.map((item, i) => (
                            <div key={i} className="text-xs text-blue-800 ml-4">
                              • {item.materialName}: {item.quantity}单位
                              <Badge
                                className={`ml-2 text-xs ${
                                  item.qualityStatus === '合格' ? 'bg-green-100 text-green-800' :
                                  item.qualityStatus === '不合格' ? 'bg-red-100 text-red-800' :
                                  'bg-yellow-100 text-yellow-800'
                                }`}
                              >
                                {item.qualityStatus}
                              </Badge>
                            </div>
                          ))}
                          {delivery.notes && (
                            <p className="text-xs text-blue-700 ml-4 mt-1">备注: {delivery.notes}</p>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        </TabsContent>
      </Tabs>

      {/* 审批流程对话框 */}
      <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>审批流程</DialogTitle>
            <DialogDescription>
              订单 {selectedOrder?.orderNo} 的审批进度
            </DialogDescription>
          </DialogHeader>
          {selectedOrder && (
            <div className="space-y-4">
              {selectedOrder.approvalFlow.map((record, index) => (
                <div key={record.id}>
                  <div className="flex items-start gap-3">
                    <div className={`p-2 rounded-full ${
                      record.status === '已通过' ? 'bg-green-100' :
                      record.status === '已驳回' ? 'bg-red-100' :
                      'bg-gray-100'
                    }`}>
                      {record.status === '已通过' ? (
                        <CheckCircle2 className="w-5 h-5 text-green-600" />
                      ) : record.status === '已驳回' ? (
                        <XCircle className="w-5 h-5 text-red-600" />
                      ) : (
                        <Clock className="w-5 h-5 text-gray-600" />
                      )}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-medium">步骤{record.step}: {record.approverRole}</span>
                        <Badge className={
                          record.status === '已通过' ? 'bg-green-100 text-green-800' :
                          record.status === '已驳回' ? 'bg-red-100 text-red-800' :
                          'bg-gray-100 text-gray-800'
                        }>
                          {record.status}
                        </Badge>
                      </div>
                      {record.approverName && (
                        <p className="text-sm text-muted-foreground">
                          审批人: {record.approverName}
                        </p>
                      )}
                      {record.approvedAt && (
                        <p className="text-xs text-muted-foreground">
                          {record.approvedAt}
                        </p>
                      )}
                      {record.comment && (
                        <p className="text-sm mt-2 p-2 bg-gray-50 rounded">
                          💬 {record.comment}
                        </p>
                      )}
                    </div>
                  </div>
                  {index < selectedOrder.approvalFlow.length - 1 && (
                    <div className="ml-5 my-2">
                      <ArrowRight className="w-4 h-4 text-gray-400" />
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 创建采购订单对话框 */}
      <Dialog open={showOrderDialog} onOpenChange={setShowOrderDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>创建采购订单</DialogTitle>
            <DialogDescription>
              填写订单信息并添加采购物料，提交后将进入审批流程
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <FileText className="w-5 h-5 text-green-600" />
                基本信息
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>关联采购计划</label>
                  <Select 
                    value={orderFormData.planId || 'none'} 
                    onValueChange={(value) => {
                      const plan = plans.find(p => p.id === value);
                      setOrderFormData({ 
                        ...orderFormData, 
                        planId: value === 'none' ? '' : value,
                        // 如果选择了计划，可以自动填充物料
                      });
                    }}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择采购计划（可选）" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">不关联计划</SelectItem>
                      {plans.filter(p => p.status === '已批准').map(plan => (
                        <SelectItem key={plan.id} value={plan.id}>
                          {plan.planNo} - {plan.planName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label>选择供应商 <span className="text-destructive">*</span></label>
                  <Select 
                    value={orderFormData.supplierId} 
                    onValueChange={(value) => {
                      const supplier = suppliers.find(s => s.id === value);
                      setOrderFormData({ 
                        ...orderFormData, 
                        supplierId: value,
                        supplierName: supplier?.name || '',
                      });
                    }}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="请选择供应商" />
                    </SelectTrigger>
                    <SelectContent>
                      {suppliers.map(supplier => (
                        <SelectItem key={supplier.id} value={supplier.id}>
                          {supplier.name} - {supplier.type} ({supplier.level})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label>预计交货日期 <span className="text-destructive">*</span></label>
                  <Input 
                    type="date" 
                    className="mt-2"
                    value={orderFormData.expectedDeliveryDate}
                    onChange={(e) => setOrderFormData({ ...orderFormData, expectedDeliveryDate: e.target.value })}
                  />
                </div>

                <div>
                  <label>备注</label>
                  <Input 
                    placeholder="订单备注信息"
                    className="mt-2"
                    value={orderFormData.notes}
                    onChange={(e) => setOrderFormData({ ...orderFormData, notes: e.target.value })}
                  />
                </div>
              </div>
            </Card>

            {/* 添加物料 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <h4 className="mb-4 flex items-center gap-2">
                <Plus className="w-5 h-5 text-blue-600" />
                添加采购物料
              </h4>
              <div className="grid grid-cols-6 gap-3">
                <div>
                  <label>物料类型 <span className="text-destructive">*</span></label>
                  <Select 
                    value={editingOrderItem.materialCategory}
                    onValueChange={(value) => {
                      setEditingOrderItem({
                        materialCategory: value,
                        materialName: '',
                        spec: '',
                        quantity: 0,
                        unit: '袋',
                        unitPrice: 0,
                      });
                    }}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="农资">农资</SelectItem>
                      <SelectItem value="农具">农具</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="col-span-2">
                  <label>物料名称 <span className="text-destructive">*</span></label>
                  <Select 
                    value={editingOrderItem.materialName}
                    onValueChange={(value) => {
                      const material = availableMaterials.find(m => m.name === value);
                      setEditingOrderItem({
                        ...editingOrderItem,
                        materialName: value,
                        spec: material?.spec || '',
                        unit: material?.unit || '袋',
                        unitPrice: material?.price || 0,
                      });
                    }}
                    disabled={!editingOrderItem.materialCategory}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder={editingOrderItem.materialCategory ? "选择物料" : "请先选择类型"} />
                    </SelectTrigger>
                    <SelectContent>
                      {availableMaterials
                        .filter(material => material.category === editingOrderItem.materialCategory)
                        .map(material => (
                          <SelectItem key={material.id} value={material.name}>
                            {material.name} ({material.type})
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label>规格</label>
                  <Input 
                    placeholder="规格"
                    className="mt-2"
                    value={editingOrderItem.spec}
                    onChange={(e) => setEditingOrderItem({ ...editingOrderItem, spec: e.target.value })}
                  />
                </div>

                <div>
                  <label>数量 <span className="text-destructive">*</span></label>
                  <Input 
                    type="number"
                    placeholder="数量"
                    className="mt-2"
                    value={editingOrderItem.quantity || ''}
                    onChange={(e) => setEditingOrderItem({ ...editingOrderItem, quantity: Number(e.target.value) })}
                  />
                </div>

                <div>
                  <label>单价 <span className="text-destructive">*</span></label>
                  <Input 
                    type="number"
                    placeholder="单价"
                    className="mt-2"
                    value={editingOrderItem.unitPrice || ''}
                    onChange={(e) => setEditingOrderItem({ ...editingOrderItem, unitPrice: Number(e.target.value) })}
                  />
                </div>

                <div className="flex items-end">
                  <Button 
                    className="w-full bg-blue-600 hover:bg-blue-700"
                    onClick={handleAddOrderItem}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    添加
                  </Button>
                </div>
              </div>

              {editingOrderItem.quantity > 0 && editingOrderItem.unitPrice > 0 && (
                <div className="mt-3 p-3 bg-white rounded-lg border border-blue-300">
                  <p className="text-sm text-blue-900">
                    💰 预计金额：¥{(editingOrderItem.quantity * editingOrderItem.unitPrice).toLocaleString()}
                  </p>
                </div>
              )}
            </Card>

            {/* 物料清单 */}
            {orderFormData.items.length > 0 && (
              <Card className="p-4">
                <h4 className="mb-4 flex items-center gap-2">
                  <Package className="w-5 h-5 text-green-600" />
                  采购物料清单 ({orderFormData.items.length}项)
                </h4>
                <div className="overflow-x-auto">
                  <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-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-center p-2">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {orderFormData.items.map((item, index) => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{index + 1}</td>
                          <td className="p-2 font-medium">{item.materialName}</td>
                          <td className="p-2 text-muted-foreground">{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 text-green-600">
                            ¥{item.amount.toLocaleString()}
                          </td>
                          <td className="text-center p-2">
                            <Button 
                              size="sm" 
                              variant="ghost"
                              onClick={() => handleRemoveOrderItem(item.id)}
                            >
                              <Trash2 className="w-4 h-4 text-red-600" />
                            </Button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot className="bg-green-50">
                      <tr>
                        <td colSpan={5} className="p-2 text-right font-medium">合计：</td>
                        <td className="text-right p-2 font-medium text-green-600">
                          ¥{orderFormData.items.reduce((sum, item) => sum + item.amount, 0).toLocaleString()}
                        </td>
                        <td></td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </Card>
            )}

            {/* 审批流程说明 */}
            <Card className="p-4 bg-orange-50 border-orange-200">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h4 className="text-orange-900 mb-2">二次审批流程</h4>
                  <div className="flex items-center gap-3 text-sm text-orange-800">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-orange-200 flex items-center justify-center">1</div>
                      <span>部门负责人初审</span>
                    </div>
                    <ArrowRight className="w-4 h-4" />
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-blue-200 flex items-center justify-center">2</div>
                      <span>财务部复审</span>
                    </div>
                    <ArrowRight className="w-4 h-4" />
                    <div className="flex items-center gap-2">
                      <CheckCircle2 className="w-5 h-5 text-green-600" />
                      <span>审批通过，订单生效</span>
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* 操作按钮 */}
            <div className="flex justify-between items-center pt-4 border-t">
              <div className="text-sm text-muted-foreground">
                {orderFormData.items.length > 0 ? (
                  <span>
                    共 {orderFormData.items.length} 项物料，合计 ¥
                    {orderFormData.items.reduce((sum, item) => sum + item.amount, 0).toLocaleString()}
                  </span>
                ) : (
                  <span>请添加采购物料</span>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => {
                  setShowOrderDialog(false);
                  setOrderFormData({
                    planId: '',
                    supplierId: '',
                    supplierName: '',
                    expectedDeliveryDate: '',
                    notes: '',
                    items: [],
                  });
                }}>
                  取消
                </Button>
                <Button 
                  className="bg-green-600 hover:bg-green-700"
                  onClick={handleCreateOrder}
                >
                  <Send className="w-4 h-4 mr-2" />
                  提交审批
                </Button>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 智能采购建议对话框 */}
      <Dialog open={showSmartSuggestionDialog} onOpenChange={setShowSmartSuggestionDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>智能采购建议</DialogTitle>
            <DialogDescription>
              系统已根据当前库存状态、种植计划需求和市场行情智能分析，为您生成以下采购建议
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 分析概况 */}
            <div className="grid grid-cols-3 gap-4">
              <Card className="p-4 bg-red-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-xs text-muted-foreground">高优先级</p>
                    <p className="mt-1 text-2xl font-medium text-red-600">
                      {suggestedItems.filter(i => i.priority === '高').length}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">需立即采购</p>
                  </div>
                  <AlertCircle className="w-10 h-10 text-red-600 opacity-50" />
                </div>
              </Card>
              <Card className="p-4 bg-yellow-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-xs text-muted-foreground">中优先级</p>
                    <p className="mt-1 text-2xl font-medium text-yellow-600">
                      {suggestedItems.filter(i => i.priority === '中').length}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">建议本月采购</p>
                  </div>
                  <AlertTriangle className="w-10 h-10 text-yellow-600 opacity-50" />
                </div>
              </Card>
              <Card className="p-4 bg-green-50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-xs text-muted-foreground">预计总金额</p>
                    <p className="mt-1 text-2xl font-medium text-green-600">
                      ¥{suggestedItems.reduce((sum, i) => sum + i.estimatedAmount, 0).toLocaleString()}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">{suggestedItems.length}项物料</p>
                  </div>
                  <DollarSign className="w-10 h-10 text-green-600 opacity-50" />
                </div>
              </Card>
            </div>

            {/* 建议物料列表 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h4 className="flex items-center gap-2">
                  <Package className="w-5 h-5 text-green-600" />
                  建议采购物料清单 ({suggestedItems.length}项)
                </h4>
                <div className="flex items-center gap-4 text-sm">
                  <span className="text-muted-foreground">
                    已选择 {selectedSuggestionIds.length} / {suggestedItems.length} 项
                  </span>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => {
                      if (selectedSuggestionIds.length === suggestedItems.length) {
                        setSelectedSuggestionIds([]);
                      } else {
                        setSelectedSuggestionIds(suggestedItems.map(s => s.id));
                      }
                    }}
                  >
                    {selectedSuggestionIds.length === suggestedItems.length ? '取消全选' : '全选'}
                  </Button>
                </div>
              </div>
              <div className="space-y-2 max-h-96 overflow-y-auto">
                {suggestedItems.map((item, index) => (
                  <Card key={item.id} className={`p-4 hover:shadow-md transition-shadow ${
                    selectedSuggestionIds.includes(item.id) ? 'border-green-500 bg-green-50/50' : ''
                  }`}>
                    <div className="flex items-start justify-between">
                      <div className="flex items-start gap-3 flex-1">
                        <Checkbox
                          checked={selectedSuggestionIds.includes(item.id)}
                          onCheckedChange={(checked) => {
                            if (checked) {
                              setSelectedSuggestionIds([...selectedSuggestionIds, item.id]);
                            } else {
                              setSelectedSuggestionIds(selectedSuggestionIds.filter(id => id !== item.id));
                            }
                          }}
                          className="mt-1"
                        />
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                          item.priority === '高' ? 'bg-red-100' :
                          item.priority === '中' ? 'bg-yellow-100' : 'bg-blue-100'
                        }`}>
                          <span className={`text-xs font-medium ${
                            item.priority === '高' ? 'text-red-600' :
                            item.priority === '中' ? 'text-yellow-600' : 'text-blue-600'
                          }`}>
                            {index + 1}
                          </span>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h5>{item.materialName}</h5>
                            <Badge className={getPriorityColor(item.priority)}>
                              {item.priority}优先级
                            </Badge>
                            <Badge variant="outline">{item.materialType}</Badge>
                          </div>
                          
                          {/* 库存和需求信息 */}
                          <div className="grid grid-cols-4 gap-4 mb-2 text-sm">
                            <div className="p-2 bg-gray-50 rounded">
                              <p className="text-xs text-muted-foreground">当前库存</p>
                              <p className={`font-medium ${
                                item.currentStock < item.safeStock * 0.5 ? 'text-red-600' :
                                item.currentStock < item.safeStock ? 'text-orange-600' : 'text-green-600'
                              }`}>
                                {item.currentStock} {item.unit}
                              </p>
                            </div>
                            <div className="p-2 bg-gray-50 rounded">
                              <p className="text-xs text-muted-foreground">安全库存</p>
                              <p className="font-medium">{item.safeStock} {item.unit}</p>
                            </div>
                            <div className="p-2 bg-gray-50 rounded">
                              <p className="text-xs text-muted-foreground">种植需求</p>
                              <p className="font-medium text-blue-600">{item.estimatedDemand} {item.unit}</p>
                            </div>
                            <div className="p-2 bg-green-50 rounded">
                              <p className="text-xs text-muted-foreground mb-1">建议采购</p>
                              <div className="flex items-center gap-1">
                                <Input
                                  type="number"
                                  min="0"
                                  step="1"
                                  className="w-16 h-7 text-sm px-2 text-green-600 font-medium"
                                  value={item.suggestedQuantity}
                                  onChange={(e) => {
                                    const newQuantity = Number(e.target.value) || 0;
                                    const newAmount = newQuantity * item.estimatedPrice;
                                    setSuggestedItems(suggestedItems.map(i =>
                                      i.id === item.id
                                        ? { ...i, suggestedQuantity: newQuantity, estimatedAmount: newAmount }
                                        : i
                                    ));
                                  }}
                                />
                                <span className="text-xs text-green-600 font-medium whitespace-nowrap">{item.unit}</span>
                              </div>
                            </div>
                          </div>

                          {/* 库存进度条 */}
                          <div className="mb-2">
                            <div className="flex items-center justify-between text-xs mb-1">
                              <span className="text-muted-foreground">库存状态</span>
                              <span className={
                                item.currentStock < item.safeStock * 0.5 ? 'text-red-600' :
                                item.currentStock < item.safeStock ? 'text-orange-600' : 'text-green-600'
                              }>
                                {((item.currentStock / item.safeStock) * 100).toFixed(0)}%
                              </span>
                            </div>
                            <Progress 
                              value={(item.currentStock / item.safeStock) * 100} 
                              className="h-2"
                            />
                          </div>

                          {/* 采购原因 */}
                          <div className="p-3 bg-blue-50 rounded text-sm">
                            <div className="flex items-start gap-2">
                              <Target className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                              <p className="text-blue-900">{item.reason}</p>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 金额信息 */}
                      <div className="text-right ml-4 min-w-[140px]">
                        <div className="mb-3">
                          <p className="text-xs text-muted-foreground mb-1">单价</p>
                          <div className="flex items-center justify-end gap-1">
                            <span className="text-sm text-muted-foreground">¥</span>
                            <Input
                              type="number"
                              min="0"
                              step="0.01"
                              className="w-20 h-7 text-sm px-2 text-right"
                              value={item.estimatedPrice}
                              onChange={(e) => {
                                const newPrice = Number(e.target.value) || 0;
                                const newAmount = item.suggestedQuantity * newPrice;
                                setSuggestedItems(suggestedItems.map(i =>
                                  i.id === item.id
                                    ? { ...i, estimatedPrice: newPrice, estimatedAmount: newAmount }
                                    : i
                                ));
                              }}
                            />
                            <span className="text-xs text-muted-foreground">/{item.unit}</span>
                          </div>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">预计金额</p>
                          <p className="mt-1 text-xl font-medium text-green-600">
                            ¥{item.estimatedAmount.toLocaleString()}
                          </p>
                        </div>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>

            {/* 创建计划表单 */}
            <Card className="p-4 bg-green-50 border-green-200">
              <h4 className="mb-4 flex items-center gap-2 text-green-900">
                <FileText className="w-5 h-5 text-green-600" />
                创建采购计划
              </h4>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>计划名称 <span className="text-destructive">*</span></label>
                    <Input 
                      placeholder="如：春季种植农资采购计划"
                      className="mt-2"
                      value={planFormData.planName}
                      onChange={(e) => setPlanFormData({ ...planFormData, planName: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>关联种植计划</label>
                    <Input 
                      placeholder="如：2024年春季水稻种植计划"
                      className="mt-2"
                      value={planFormData.plantingPlanRef}
                      onChange={(e) => setPlanFormData({ ...planFormData, plantingPlanRef: e.target.value })}
                    />
                  </div>
                </div>
                <div>
                  <label>采购原因</label>
                  <Textarea 
                    placeholder="请说明本次采购的原因和背景"
                    className="mt-2"
                    rows={2}
                    value={planFormData.reason}
                    onChange={(e) => setPlanFormData({ ...planFormData, reason: e.target.value })}
                  />
                </div>
                <div>
                  <label>备注</label>
                  <Textarea 
                    placeholder="其他备注信息"
                    className="mt-2"
                    rows={2}
                    value={planFormData.notes}
                    onChange={(e) => setPlanFormData({ ...planFormData, notes: e.target.value })}
                  />
                </div>
              </div>
            </Card>

            {/* 操作按钮 */}
            <div className="flex justify-between items-center pt-4 border-t">
              <div className="text-sm">
                <Package className="w-4 h-4 inline mr-1" />
                {selectedSuggestionIds.length > 0 ? (
                  <span className="text-green-600 font-medium">
                    已选择 {selectedSuggestionIds.length} 项物料，预计总金额 ¥
                    {suggestedItems
                      .filter(i => selectedSuggestionIds.includes(i.id))
                      .reduce((sum, i) => sum + i.estimatedAmount, 0)
                      .toLocaleString()}
                  </span>
                ) : (
                  <span className="text-muted-foreground">请勾选需要采购的物料</span>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => {
                  setShowSmartSuggestionDialog(false);
                  setSuggestedItems([]);
                  setSelectedSuggestionIds([]);
                  setPlanFormData({
                    planName: '',
                    plantingPlanRef: '',
                    reason: '',
                    notes: '',
                  });
                }}>
                  取消
                </Button>
                <Button 
                  className="bg-green-600 hover:bg-green-700" 
                  onClick={handleCreatePlanFromSuggestion}
                  disabled={selectedSuggestionIds.length === 0}
                >
                  <CheckCheck className="w-4 h-4 mr-2" />
                  创建采购计划 ({selectedSuggestionIds.length}项)
                </Button>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 查看计划详情对话框 */}
      <Dialog open={showViewPlanDialog} onOpenChange={setShowViewPlanDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>采购计划详情</DialogTitle>
            <DialogDescription>
              计划编号: {selectedPlan?.planNo}
            </DialogDescription>
          </DialogHeader>
          {selectedPlan && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-4 flex items-center gap-2 text-blue-900">
                  <FileText className="w-5 h-5 text-blue-600" />
                  基本信息
                </h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <label>计划名称</label>
                    <div className="field-value">{selectedPlan.planName}</div>
                  </div>
                  <div>
                    <label>计划编号</label>
                    <div className="field-value">{selectedPlan.planNo}</div>
                  </div>
                  <div>
                    <label>计划状态</label>
                    <div className="field-value">
                      <Badge className={getPlanStatusColor(selectedPlan.status)}>
                        {selectedPlan.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <label>关联种植计划</label>
                    <div className="field-value">{selectedPlan.plantingPlanRef || '无'}</div>
                  </div>
                  <div>
                    <label>创建人</label>
                    <div className="field-value">{selectedPlan.createdBy}</div>
                  </div>
                  <div>
                    <label>创建时间</label>
                    <div className="field-value">{selectedPlan.createdAt}</div>
                  </div>
                  {selectedPlan.approvedBy && (
                    <>
                      <div>
                        <label>审批人</label>
                        <div className="field-value">{selectedPlan.approvedBy}</div>
                      </div>
                      <div>
                        <label>审批时间</label>
                        <div className="field-value">{selectedPlan.approvedAt}</div>
                      </div>
                    </>
                  )}
                </div>
              </Card>

              {/* 采购原因 */}
              <Card className="p-4">
                <label>采购原因</label>
                <div className="field-value">{selectedPlan.reason}</div>
              </Card>

              {/* 市场分析 */}
              {selectedPlan.marketAnalysis && (
                <Card className="p-4 bg-yellow-50 border-yellow-200">
                  <label className="text-yellow-900">市场分析</label>
                  <div className="field-value bg-white whitespace-pre-line">
                    {selectedPlan.marketAnalysis}
                  </div>
                </Card>
              )}

              {/* 采购明细 */}
              <Card className="p-4">
                <h4 className="mb-4 flex items-center gap-2">
                  <Package className="w-5 h-5 text-green-600" />
                  采购物料清单 ({selectedPlan.items.length}项)
                </h4>
                <div className="overflow-x-auto">
                  <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-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-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>
                      {selectedPlan.items.map((item, index) => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{index + 1}</td>
                          <td className="p-2 font-medium">{item.materialName}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.materialType}
                            </Badge>
                          </td>
                          <td className="text-right p-2">
                            <span className={item.currentStock < item.safeStock ? 'text-red-600 font-medium' : ''}>
                              {item.currentStock} {item.unit}
                            </span>
                          </td>
                          <td className="text-right p-2">{item.safeStock} {item.unit}</td>
                          <td className="text-right p-2">{item.estimatedDemand} {item.unit}</td>
                          <td className="text-right p-2 font-medium text-blue-600">
                            {item.suggestedQuantity} {item.unit}
                          </td>
                          <td className="text-right p-2">¥{item.estimatedPrice}</td>
                          <td className="text-right p-2 font-medium text-green-600">
                            ¥{item.estimatedAmount.toLocaleString()}
                          </td>
                          <td className="p-2">
                            <Badge className={getPriorityColor(item.priority)}>
                              {item.priority}
                            </Badge>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot className="bg-green-50">
                      <tr>
                        <td colSpan={8} className="p-2 text-right font-medium">合计：</td>
                        <td className="text-right p-2 font-medium text-green-600">
                          ¥{selectedPlan.totalAmount.toLocaleString()}
                        </td>
                        <td></td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </Card>

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

              <div className="flex justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowViewPlanDialog(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 编辑计划对话框 */}
      <Dialog open={showEditPlanDialog} onOpenChange={setShowEditPlanDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>编辑采购计划</DialogTitle>
            <DialogDescription>
              计划编号: {selectedPlan?.planNo} | 当前状态: {selectedPlan?.status}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <FileText className="w-5 h-5 text-green-600" />
                基本信息
              </h4>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>计划名称 <span className="text-destructive">*</span></label>
                    <Input 
                      placeholder="请输入计划名称"
                      className="mt-2"
                      value={editPlanFormData.planName}
                      onChange={(e) => setEditPlanFormData({ ...editPlanFormData, planName: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>关联种植计划</label>
                    <Input 
                      placeholder="如：2024年春季水稻种植计划"
                      className="mt-2"
                      value={editPlanFormData.plantingPlanRef}
                      onChange={(e) => setEditPlanFormData({ ...editPlanFormData, plantingPlanRef: e.target.value })}
                    />
                  </div>
                </div>
                <div>
                  <label>采购原因</label>
                  <Textarea 
                    placeholder="请说明本次采购的原因和背景"
                    className="mt-2"
                    rows={2}
                    value={editPlanFormData.reason}
                    onChange={(e) => setEditPlanFormData({ ...editPlanFormData, reason: e.target.value })}
                  />
                </div>
                <div>
                  <label>备注</label>
                  <Textarea 
                    placeholder="其他备注信息"
                    className="mt-2"
                    rows={2}
                    value={editPlanFormData.notes}
                    onChange={(e) => setEditPlanFormData({ ...editPlanFormData, notes: e.target.value })}
                  />
                </div>
              </div>
            </Card>

            {/* 采购明细 */}
            {editPlanFormData.items.length > 0 && (
              <Card className="p-4">
                <h4 className="mb-4 flex items-center gap-2">
                  <Package className="w-5 h-5 text-green-600" />
                  采购物料清单 ({editPlanFormData.items.length}项)
                </h4>
                <div className="overflow-x-auto">
                  <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-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-center p-2">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {editPlanFormData.items.map((item, index) => (
                        <tr key={item.id} className="border-t">
                          <td className="p-2">{index + 1}</td>
                          <td className="p-2 font-medium">{item.materialName}</td>
                          <td className="p-2">
                            <Badge variant="outline" className="text-xs">
                              {item.materialType}
                            </Badge>
                          </td>
                          <td className="text-right p-2">
                            <div className="flex items-center justify-end gap-2">
                              <Input
                                type="number"
                                min="0"
                                step="1"
                                className="w-24 text-right"
                                value={item.suggestedQuantity}
                                onChange={(e) => {
                                  const newQuantity = Number(e.target.value) || 0;
                                  const newAmount = newQuantity * item.estimatedPrice;
                                  setEditPlanFormData({
                                    ...editPlanFormData,
                                    items: editPlanFormData.items.map(i =>
                                      i.id === item.id
                                        ? { ...i, suggestedQuantity: newQuantity, estimatedAmount: newAmount }
                                        : i
                                    ),
                                  });
                                }}
                              />
                              <span className="text-muted-foreground whitespace-nowrap">{item.unit}</span>
                            </div>
                          </td>
                          <td className="text-right p-2">
                            <div className="flex items-center justify-end gap-1">
                              <span className="text-muted-foreground">¥</span>
                              <Input
                                type="number"
                                min="0"
                                step="0.01"
                                className="w-24 text-right"
                                value={item.estimatedPrice}
                                onChange={(e) => {
                                  const newPrice = Number(e.target.value) || 0;
                                  const newAmount = item.suggestedQuantity * newPrice;
                                  setEditPlanFormData({
                                    ...editPlanFormData,
                                    items: editPlanFormData.items.map(i =>
                                      i.id === item.id
                                        ? { ...i, estimatedPrice: newPrice, estimatedAmount: newAmount }
                                        : i
                                    ),
                                  });
                                }}
                              />
                            </div>
                          </td>
                          <td className="text-right p-2 font-medium text-green-600">
                            ¥{item.estimatedAmount.toLocaleString()}
                          </td>
                          <td className="p-2">
                            <Badge className={getPriorityColor(item.priority)}>
                              {item.priority}
                            </Badge>
                          </td>
                          <td className="text-center p-2">
                            <Button 
                              size="sm" 
                              variant="ghost"
                              onClick={() => handleRemovePlanItem(item.id)}
                            >
                              <Trash2 className="w-4 h-4 text-red-600" />
                            </Button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot className="bg-green-50">
                      <tr>
                        <td colSpan={5} className="p-2 text-right font-medium">合计：</td>
                        <td className="text-right p-2 font-medium text-green-600">
                          ¥{editPlanFormData.items.reduce((sum, item) => sum + item.estimatedAmount, 0).toLocaleString()}
                        </td>
                        <td colSpan={2}></td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </Card>
            )}

            <div className="flex justify-between items-center pt-4 border-t">
              <div className="text-sm text-muted-foreground">
                {editPlanFormData.items.length > 0 ? (
                  <span>
                    共 {editPlanFormData.items.length} 项物料，合计 ¥
                    {editPlanFormData.items.reduce((sum, item) => sum + item.estimatedAmount, 0).toLocaleString()}
                  </span>
                ) : (
                  <span>暂无物料</span>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => {
                  setShowEditPlanDialog(false);
                  setEditPlanFormData({
                    planName: '',
                    plantingPlanRef: '',
                    reason: '',
                    notes: '',
                    items: [],
                  });
                }}>
                  取消
                </Button>
                <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveEditPlan}>
                  <Save className="w-4 h-4 mr-2" />
                  保存修改
                </Button>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 确认对话框 */}
      <AlertDialog open={confirmDialog.open} onOpenChange={(open) => {
        if (!open) {
          setConfirmDialog({ open: false, type: null, planId: null, planName: '' });
        }
      }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {confirmDialog.type === 'submit' && '确认提交审批'}
              {confirmDialog.type === 'approve' && '确认批准计划'}
              {confirmDialog.type === 'reject' && '确认驳回计划'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {confirmDialog.type === 'submit' && '您确定要提交以下采购计划到审批流程吗？'}
              {confirmDialog.type === 'approve' && '您确定要批准以下采购计划吗？'}
              {confirmDialog.type === 'reject' && '您确定要驳回以下采购计划吗？'}
            </AlertDialogDescription>
          </AlertDialogHeader>

          {/* 计划详情和提示信息 */}
          <div className="space-y-3 py-4">
            {confirmDialog.type === 'submit' && (
              <>
                <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
                  <p className="text-sm font-medium text-blue-900">计划名称：{confirmDialog.planName}</p>
                </div>
                <p className="text-sm text-muted-foreground">
                  提交后，计划将进入审批流程，需要相关人员审批通过后才能执行。
                </p>
              </>
            )}
            {confirmDialog.type === 'approve' && (
              <>
                <div className="p-3 bg-green-50 rounded-md border border-green-200">
                  <p className="text-sm font-medium text-green-900">计划名称：{confirmDialog.planName}</p>
                </div>
                <p className="text-sm text-muted-foreground">
                  批准后，该计划可以进入执行阶段，相关采购人员可以据此创建采购订单。
                </p>
              </>
            )}
            {confirmDialog.type === 'reject' && (
              <>
                <div className="p-3 bg-red-50 rounded-md border border-red-200">
                  <p className="text-sm font-medium text-red-900">计划名称：{confirmDialog.planName}</p>
                </div>
                <p className="text-sm text-muted-foreground">
                  驳回后，计划将返回草稿状态，创建人需要重新修改并提交审批。
                </p>
              </>
            )}
          </div>

          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmAction}
              className={
                confirmDialog.type === 'submit' ? 'bg-blue-600 hover:bg-blue-700' :
                confirmDialog.type === 'approve' ? 'bg-green-600 hover:bg-green-700' :
                'bg-red-600 hover:bg-red-700'
              }
            >
              {confirmDialog.type === 'submit' && '确认提交'}
              {confirmDialog.type === 'approve' && '确认批准'}
              {confirmDialog.type === 'reject' && '确认驳回'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 订单审批确认对话框 */}
      <AlertDialog open={orderConfirmDialog.open} onOpenChange={(open) => {
        if (!open) {
          setOrderConfirmDialog({ open: false, type: null, orderId: null, orderNo: '', step: 0 });
        }
      }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {orderConfirmDialog.type === 'first-approve' && '确认初审通过'}
              {orderConfirmDialog.type === 'second-approve' && '确认复审通过'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 1 && '确认初审驳回'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 2 && '确认复审驳回'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {orderConfirmDialog.type === 'first-approve' && '您确定要通过该采购订单的初审吗？'}
              {orderConfirmDialog.type === 'second-approve' && '您确定要通过该采购订单的复审吗？'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 1 && '您确定要驳回该采购订单的初审吗？'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 2 && '您确定要驳回该采购订单的复审吗？'}
            </AlertDialogDescription>
          </AlertDialogHeader>

          {/* 订单详情和提示信息 */}
          <div className="space-y-3 py-4">
            {orderConfirmDialog.type === 'first-approve' && (
              <>
                <div className="p-3 bg-green-50 rounded-md border border-green-200">
                  <p className="text-sm font-medium text-green-900">订单编号：{orderConfirmDialog.orderNo}</p>
                </div>
                <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
                  <p className="text-sm text-blue-900">
                    <strong>初审说明：</strong>作为部门负责人，请确认采购需求合理性和必要性。
                  </p>
                </div>
                <p className="text-sm text-muted-foreground">
                  初审通过后，订单将进入复审阶段，由财务部进行预算审核。
                </p>
              </>
            )}
            {orderConfirmDialog.type === 'second-approve' && (
              <>
                <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
                  <p className="text-sm font-medium text-blue-900">订单编号：{orderConfirmDialog.orderNo}</p>
                </div>
                <div className="p-3 bg-green-50 rounded-md border border-green-200">
                  <p className="text-sm text-green-900">
                    <strong>复审说明：</strong>作为财务部负责人，请确认预算充足并符合财务制度。
                  </p>
                </div>
                <p className="text-sm text-muted-foreground">
                  复审通过后，订单将正式生效并下单给供应商，请谨慎确认。
                </p>
              </>
            )}
            {orderConfirmDialog.type === 'reject' && (
              <>
                <div className="p-3 bg-red-50 rounded-md border border-red-200">
                  <p className="text-sm font-medium text-red-900">订单编号：{orderConfirmDialog.orderNo}</p>
                </div>
                <div className="p-3 bg-orange-50 rounded-md border border-orange-200">
                  <p className="text-sm text-orange-900">
                    <strong>驳回原因：</strong>
                    {orderConfirmDialog.step === 1 && '采购需求不合理或不符合部门规划。'}
                    {orderConfirmDialog.step === 2 && '预算不足或不符合财务审批制度。'}
                  </p>
                </div>
                <p className="text-sm text-muted-foreground">
                  驳回后，订单将被取消，创建人需要重新评估采购需求。
                </p>
              </>
            )}
          </div>

          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmOrderAction}
              className={
                orderConfirmDialog.type === 'reject' 
                  ? 'bg-red-600 hover:bg-red-700' 
                  : orderConfirmDialog.type === 'first-approve'
                  ? 'bg-green-600 hover:bg-green-700'
                  : 'bg-blue-600 hover:bg-blue-700'
              }
            >
              {orderConfirmDialog.type === 'first-approve' && '确认初审通过'}
              {orderConfirmDialog.type === 'second-approve' && '确认复审通过'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 1 && '确认初审驳回'}
              {orderConfirmDialog.type === 'reject' && orderConfirmDialog.step === 2 && '确认复审驳回'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
