import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@d8d/shared-ui-components/components/ui/table';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@d8d/shared-ui-components/components/ui/card';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@d8d/shared-ui-components/components/ui/dropdown-menu';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@d8d/shared-ui-components/components/ui/select';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { toast } from 'sonner';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@d8d/shared-ui-components/components/ui/alert-dialog';
import {
  Plus,
  Search,
  MoreHorizontal,
  Edit,
  Trash2,
  Users,
  FileText,
  Play,
  CheckCircle,
  Eye,
} from 'lucide-react';
import { OrderStatus, WorkStatus, getOrderStatusLabel, getWorkStatusLabel } from '@d8d/allin-enums';
import { orderClientManager } from '../api/orderClient';
import OrderForm from './OrderForm';
import OrderAssetModal from './OrderAssetModal';
import OrderDetailModal from './OrderDetailModal';
import type { OrderListItem, OrderSearchParams, OrderDetail } from '../api/types';
import { PlatformSelector } from '@d8d/allin-platform-management-ui/components';
import { CompanySelector } from '@d8d/allin-company-management-ui/components';
import { ChannelSelector } from '@d8d/allin-channel-management-ui/components';

export const OrderManagement: React.FC = () => {
  const queryClient = useQueryClient();
  const [searchParams, setSearchParams] = useState<OrderSearchParams>({
    page: 1,
    pageSize: 10,
  });
  const [selectedOrder, setSelectedOrder] = useState<OrderDetail | undefined>();
  const [isOrderFormOpen, setIsOrderFormOpen] = useState(false);
  const [isAssetAssociationOpen, setIsAssetAssociationOpen] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null);
  const [selectedPersonId, setSelectedPersonId] = useState<number | null>(null);

  // 确认对话框状态
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [activateConfirmOpen, setActivateConfirmOpen] = useState(false);
  const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
  const [pendingOrderId, setPendingOrderId] = useState<number | null>(null);

  // 订单详情弹窗状态
  const [isOrderDetailOpen, setIsOrderDetailOpen] = useState(false);
  const [detailOrderId, setDetailOrderId] = useState<number | null>(null);

  // 查询订单列表
  const { data: ordersData, isLoading, error } = useQuery({
    queryKey: ['orders', searchParams],
    queryFn: async () => {
      // 转换searchParams中的orderStatus从number到OrderStatus枚举
      const apiParams = {
        ...searchParams,
        orderStatus: searchParams.orderStatus !== undefined ? searchParams.orderStatus as unknown as OrderStatus : undefined,
      };

      const response = await orderClientManager.get().list.$get({
        query: apiParams,
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '获取订单列表失败');
      }
      return response.json();
    },
  });

  // 查询订单详情（用于资产上传）
  const { data: orderDetailData } = useQuery({
    queryKey: ['order-detail-for-assets', selectedOrderId],
    queryFn: async () => {
      if (!selectedOrderId) return null;

      const response = await orderClientManager.get().detail[':id'].$get({
        param: { id: selectedOrderId },
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '获取订单详情失败');
      }
      return response.json();
    },
    enabled: !!selectedOrderId && isAssetAssociationOpen,
  });

  // 删除订单Mutation
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await orderClientManager.get().delete[':id'].$delete({
        param: { id },
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '删除订单失败');
      }
      return response.json();
    },
    onSuccess: () => {
      toast.success('订单删除成功');
      queryClient.invalidateQueries({ queryKey: ['orders'] });
    },
    onError: (error: Error) => {
      toast.error(`删除订单失败: ${error.message}`);
    },
  });

  // 激活订单Mutation
  const activateMutation = useMutation({
    mutationFn: async (orderId: number) => {
      const response = await orderClientManager.get().activate[':orderId'].$post({
        param: { orderId },
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '激活订单失败');
      }
      return response.json();
    },
    onSuccess: () => {
      toast.success('订单激活成功');
      queryClient.invalidateQueries({ queryKey: ['orders'] });
    },
    onError: (error: Error) => {
      toast.error(`激活订单失败: ${error.message}`);
    },
  });

  // 关闭订单Mutation
  const closeMutation = useMutation({
    mutationFn: async (orderId: number) => {
      const response = await orderClientManager.get().close[':orderId'].$post({
        param: { orderId },
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '关闭订单失败');
      }
      return response.json();
    },
    onSuccess: () => {
      toast.success('订单关闭成功');
      queryClient.invalidateQueries({ queryKey: ['orders'] });
    },
    onError: (error: Error) => {
      toast.error(`关闭订单失败: ${error.message}`);
    },
  });

  // 处理创建订单
  const handleCreateOrder = () => {
    setSelectedOrder(undefined);
    setIsOrderFormOpen(true);
  };

  // 获取订单详情Mutation
  const getOrderDetailMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await orderClientManager.get().detail[':id'].$get({
        param: { id },
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '获取订单详情失败');
      }
      return response.json();
    },
    onSuccess: (detail) => {
      setSelectedOrder(detail);
    },
    onError: (error: Error) => {
      console.error('获取订单详情失败:', error);
      toast.error(`获取订单详情失败: ${error.message}`);
    },
  });

  // 处理编辑订单
  const handleEditOrder = (order: OrderListItem) => {
    // 先设置列表项数据，让表单立即显示基本字段
    // 注意：OrderListItem 可能缺少 OrderDetail 的某些字段，但基本字段应该相同
    setSelectedOrder(order as OrderDetail);
    setIsOrderFormOpen(true);
    // 然后异步获取完整详情来更新表单
    getOrderDetailMutation.mutate(order.id);
  };

  // 处理删除订单
  const handleDeleteOrder = (id: number) => {
    setPendingOrderId(id);
    setDeleteConfirmOpen(true);
  };

  // 处理激活订单
  const handleActivateOrder = (orderId: number) => {
    setPendingOrderId(orderId);
    setActivateConfirmOpen(true);
  };

  // 处理关闭订单
  const handleCloseOrder = (orderId: number) => {
    setPendingOrderId(orderId);
    setCloseConfirmOpen(true);
  };

  // 确认删除订单
  const confirmDeleteOrder = () => {
    if (pendingOrderId) {
      deleteMutation.mutate(pendingOrderId);
      setDeleteConfirmOpen(false);
      setPendingOrderId(null);
    }
  };

  // 确认激活订单
  const confirmActivateOrder = () => {
    if (pendingOrderId) {
      activateMutation.mutate(pendingOrderId);
      setActivateConfirmOpen(false);
      setPendingOrderId(null);
    }
  };

  // 确认关闭订单
  const confirmCloseOrder = () => {
    if (pendingOrderId) {
      closeMutation.mutate(pendingOrderId);
      setCloseConfirmOpen(false);
      setPendingOrderId(null);
    }
  };

  // 处理添加资产
  const handleAddAsset = (orderId: number, personId?: number) => {
    setSelectedOrderId(orderId);
    setSelectedPersonId(personId || null);
    setIsAssetAssociationOpen(true);
  };

  // 处理查看订单详情
  const handleViewOrderDetail = (orderId: number) => {
    setDetailOrderId(orderId);
    setIsOrderDetailOpen(true);
  };

  // 处理搜索
  const handleSearch = (field: keyof OrderSearchParams, value: string | number | undefined) => {
    setSearchParams(prev => ({
      ...prev,
      [field]: value,
      page: 1, // 重置到第一页
    }));
  };

  // 重置筛选条件
  const handleResetFilters = () => {
    setSearchParams({
      page: 1,
      pageSize: 10,
    });
  };

  // 获取订单状态徽章样式
  const getOrderStatusBadge = (status: OrderStatus) => {
    const variants = {
      [OrderStatus.DRAFT]: 'secondary',
      [OrderStatus.CONFIRMED]: 'default',
      [OrderStatus.IN_PROGRESS]: 'default',
      [OrderStatus.COMPLETED]: 'outline',
      [OrderStatus.CANCELLED]: 'destructive',
    } as const;

    return (
      <Badge variant={variants[status]}>
        {getOrderStatusLabel(status)}
      </Badge>
    );
  };

  // 获取工作状态徽章样式
  const getWorkStatusBadge = (status: WorkStatus) => {
    const variants = {
      [WorkStatus.NOT_WORKING]: 'secondary',
      [WorkStatus.PRE_WORKING]: 'default',
      [WorkStatus.WORKING]: 'default',
      [WorkStatus.RESIGNED]: 'destructive',
    } as const;

    return (
      <Badge variant={variants[status]}>
        {getWorkStatusLabel(status)}
      </Badge>
    );
  };

  const orders = ordersData?.data || [];
  const total = ordersData?.total || 0;

  return (
    <div className="space-y-6">
      {/* 头部操作栏 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>订单管理</CardTitle>
              <CardDescription>
                管理用工订单，包括创建、编辑、删除、激活、关闭等操作
              </CardDescription>
            </div>
            <Button onClick={handleCreateOrder} data-testid="create-order-button">
              <Plus className="mr-2 h-4 w-4" />
              创建订单
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* 搜索和筛选 */}
          <div className="space-y-4 mb-6">
            {/* 第一行：基本搜索条件 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">订单名称</label>
                <Input
                  placeholder="搜索订单名称"
                  value={searchParams.orderName || ''}
                  onChange={(e) => handleSearch('orderName', e.target.value)}
                  data-testid="search-order-name-input"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">订单状态</label>
                <Select
                  value={searchParams.orderStatus?.toString() || 'all'}
                  onValueChange={(value) => handleSearch('orderStatus', value !== 'all' ? parseInt(value) : undefined)}
                >
                  <SelectTrigger data-testid="filter-order-status-select">
                    <SelectValue placeholder="全部状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all" data-testid="order-status-option-all">全部状态</SelectItem>
                    <SelectItem value={OrderStatus.DRAFT} data-testid="order-status-option-draft">草稿</SelectItem>
                    <SelectItem value={OrderStatus.CONFIRMED} data-testid="order-status-option-confirmed">已确认</SelectItem>
                    <SelectItem value={OrderStatus.IN_PROGRESS} data-testid="order-status-option-in-progress">进行中</SelectItem>
                    <SelectItem value={OrderStatus.COMPLETED} data-testid="order-status-option-completed">已完成</SelectItem>
                    <SelectItem value={OrderStatus.CANCELLED} data-testid="order-status-option-cancelled">已取消</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">工作状态</label>
                <Select
                  value={searchParams.workStatus?.toString() || 'all'}
                  onValueChange={(value) => handleSearch('workStatus', value !== 'all' ? parseInt(value) : undefined)}
                >
                  <SelectTrigger data-testid="filter-work-status-select">
                    <SelectValue placeholder="全部状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all" data-testid="work-status-option-all">全部状态</SelectItem>
                    <SelectItem value={WorkStatus.NOT_WORKING} data-testid="work-status-option-not-working">未就业</SelectItem>
                    <SelectItem value={WorkStatus.PRE_WORKING} data-testid="work-status-option-pre-working">待就业</SelectItem>
                    <SelectItem value={WorkStatus.WORKING} data-testid="work-status-option-working">已就业</SelectItem>
                    <SelectItem value={WorkStatus.RESIGNED} data-testid="work-status-option-resigned">已离职</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-end gap-2">
                <Button variant="outline" className="w-full" data-testid="search-button">
                  <Search className="mr-2 h-4 w-4" />
                  搜索
                </Button>
                <Button variant="outline" className="w-full" onClick={handleResetFilters} data-testid="reset-button">
                  重置
                </Button>
              </div>
            </div>

            {/* 第二行：新增的搜索条件 */}
            <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">平台</label>
                <PlatformSelector
                  value={searchParams.platformId}
                  onChange={(value) => handleSearch('platformId', value)}
                  placeholder="选择平台"
                  className="w-full"
                  data-testid="platform-search-select"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">公司</label>
                <CompanySelector
                  value={searchParams.companyId}
                  onChange={(value) => handleSearch('companyId', value)}
                  placeholder="选择公司"
                  className="w-full"
                  data-testid="company-search-select"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">渠道</label>
                <ChannelSelector
                  value={searchParams.channelId}
                  onChange={(value) => handleSearch('channelId', value)}
                  placeholder="选择渠道"
                  className="w-full"
                  data-testid="channel-search-select"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">开始日期</label>
                <Input
                  type="date"
                  value={searchParams.startDate || ''}
                  onChange={(e) => handleSearch('startDate', e.target.value || undefined)}
                  data-testid="start-date-input"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">结束日期</label>
                <Input
                  type="date"
                  value={searchParams.endDate || ''}
                  onChange={(e) => handleSearch('endDate', e.target.value || undefined)}
                  data-testid="end-date-input"
                />
              </div>
            </div>
          </div>

          {/* 订单表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>订单名称</TableHead>
                  <TableHead>平台</TableHead>
                  <TableHead>公司</TableHead>
                  <TableHead>渠道</TableHead>
                  <TableHead>预计开始日期</TableHead>
                  <TableHead>订单状态</TableHead>
                  <TableHead>工作状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow key="loading">
                    <TableCell colSpan={9} className="text-center py-8">
                      加载中...
                    </TableCell>
                  </TableRow>
                ) : error ? (
                  <TableRow key="error">
                    <TableCell colSpan={9} className="text-center py-8 text-destructive">
                      加载失败: {error.message}
                    </TableCell>
                  </TableRow>
                ) : orders.length === 0 ? (
                  <TableRow key="empty">
                    <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                      暂无订单数据
                    </TableCell>
                  </TableRow>
                ) : (
                  orders.map((order) => (
                    <TableRow key={order.id} data-testid={`order-row-${order.id}`}>
                      <TableCell className="font-medium">{order.orderName}</TableCell>
                      <TableCell>平台{order.platformId}</TableCell>
                      <TableCell>公司{order.companyId}</TableCell>
                      <TableCell>渠道{order.channelId}</TableCell>
                      <TableCell>
                        {order.expectedStartDate
                          ? new Date(order.expectedStartDate).toLocaleDateString()
                          : '-'}
                      </TableCell>
                      <TableCell>{getOrderStatusBadge(order.orderStatus)}</TableCell>
                      <TableCell>{getWorkStatusBadge(order.workStatus)}</TableCell>
                      <TableCell>
                        {order.createTime
                          ? new Date(order.createTime).toLocaleDateString()
                          : '-'}
                      </TableCell>
                      <TableCell className="text-right">
                        <DropdownMenu modal={false}>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              className="h-8 w-8 p-0"
                              data-testid={`order-menu-trigger-${order.id}`}
                            >
                              <span className="sr-only">打开菜单</span>
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuLabel>操作</DropdownMenuLabel>
                            <DropdownMenuItem
                              onClick={() => handleViewOrderDetail(order.id)}
                              data-testid={`view-order-detail-button-${order.id}`}
                            >
                              <Eye className="mr-2 h-4 w-4" />
                              查看详情
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleEditOrder(order)}
                              data-testid={`edit-order-button-${order.id}`}
                            >
                              <Edit className="mr-2 h-4 w-4" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleAddAsset(order.id)}
                              data-testid={`add-asset-button-${order.id}`}
                            >
                              <FileText className="mr-2 h-4 w-4" />
                              添加附件
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            {order.orderStatus === OrderStatus.DRAFT && (
                              <DropdownMenuItem
                                onClick={() => handleActivateOrder(order.id)}
                                data-testid={`activate-order-button-${order.id}`}
                              >
                                <Play className="mr-2 h-4 w-4" />
                                激活订单
                              </DropdownMenuItem>
                            )}
                            {(order.orderStatus === OrderStatus.CONFIRMED || order.orderStatus === OrderStatus.IN_PROGRESS) && (
                              <DropdownMenuItem
                                onClick={() => handleCloseOrder(order.id)}
                                data-testid={`close-order-button-${order.id}`}
                              >
                                <CheckCircle className="mr-2 h-4 w-4" />
                                关闭订单
                              </DropdownMenuItem>
                            )}
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={() => handleDeleteOrder(order.id)}
                              className="text-destructive"
                              data-testid={`delete-order-button-${order.id}`}
                            >
                              <Trash2 className="mr-2 h-4 w-4" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页信息 */}
          <div className="flex items-center justify-between mt-4">
            <div className="text-sm text-muted-foreground">
              共 {total} 条记录，当前显示第 {searchParams.page} 页
            </div>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setSearchParams(prev => ({ ...prev, page: Math.max(1, (prev.page || 1) - 1) }))}
                disabled={searchParams.page === 1}
              >
                上一页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setSearchParams(prev => ({ ...prev, page: (prev.page || 1) + 1 }))}
                disabled={!ordersData || orders.length < (searchParams.pageSize || 10)}
              >
                下一页
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 订单表单模态框 */}
      <OrderForm
        order={selectedOrder}
        open={isOrderFormOpen}
        onOpenChange={setIsOrderFormOpen}
        onSuccess={() => {
          setIsOrderFormOpen(false);
          setSelectedOrder(undefined);
        }}
      />

      {/* 资产上传模态框 */}
      {selectedOrderId && orderDetailData?.orderPersons && (
        <OrderAssetModal
          orderId={selectedOrderId}
          orderPersons={orderDetailData.orderPersons.map((op: any) => ({
            personId: op.personId,
            personName: op.person?.name || op.personName || '未知',
            disabilityId: op.person?.disabilityId,
            disabilityType: op.person?.disabilityType,
          }))}
          open={isAssetAssociationOpen}
          onOpenChange={setIsAssetAssociationOpen}
        />
      )}

      {/* 删除订单确认对话框 */}
      <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
        <AlertDialogContent data-testid="delete-confirm-dialog">
          <AlertDialogHeader>
            <AlertDialogTitle data-testid="delete-confirm-dialog-title">删除订单</AlertDialogTitle>
            <AlertDialogDescription data-testid="delete-confirm-dialog-description">
              确定要删除这个订单吗？此操作不可撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel data-testid="delete-confirm-dialog-cancel">取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteOrder}
              data-testid="delete-confirm-dialog-confirm"
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 激活订单确认对话框 */}
      <AlertDialog open={activateConfirmOpen} onOpenChange={setActivateConfirmOpen}>
        <AlertDialogContent data-testid="activate-confirm-dialog">
          <AlertDialogHeader>
            <AlertDialogTitle data-testid="activate-confirm-dialog-title">激活订单</AlertDialogTitle>
            <AlertDialogDescription data-testid="activate-confirm-dialog-description">
              确定要激活这个订单吗？订单激活后将进入进行中状态。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel data-testid="activate-confirm-dialog-cancel">取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmActivateOrder}
              data-testid="activate-confirm-dialog-confirm"
            >
              激活
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 关闭订单确认对话框 */}
      <AlertDialog open={closeConfirmOpen} onOpenChange={setCloseConfirmOpen}>
        <AlertDialogContent data-testid="close-confirm-dialog">
          <AlertDialogHeader>
            <AlertDialogTitle data-testid="close-confirm-dialog-title">关闭订单</AlertDialogTitle>
            <AlertDialogDescription data-testid="close-confirm-dialog-description">
              确定要关闭这个订单吗？订单关闭后将无法再添加人员或附件。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel data-testid="close-confirm-dialog-cancel">取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmCloseOrder}
              data-testid="close-confirm-dialog-confirm"
            >
              关闭
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 订单详情弹窗 */}
      <OrderDetailModal
        open={isOrderDetailOpen}
        onOpenChange={setIsOrderDetailOpen}
        orderId={detailOrderId}
        onSuccess={() => {
          queryClient.invalidateQueries({ queryKey: ['orders'] });
        }}
      />
    </div>
  );
};

export default OrderManagement;