import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { format } from 'date-fns';
import { toast } from 'sonner';
import { Search, Edit, Eye, Package, Truck } from 'lucide-react';
 

// 使用共享UI组件包的具体路径导入
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';

// 简单分页组件
const DataTablePagination = ({
  currentPage,
  pageSize,
  totalCount,
  onPageChange
}: {
  currentPage: number;
  pageSize: number;
  totalCount: number;
  onPageChange: (page: number, limit: number) => void;
}) => {
  const totalPages = Math.ceil(totalCount / pageSize);

  return (
    <div className="flex items-center justify-between px-2 py-4">
      <div className="text-sm text-muted-foreground">
        共 {totalCount} 条记录
      </div>
      <div className="flex items-center space-x-2">
        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(Math.max(1, currentPage - 1), pageSize)}
          disabled={currentPage <= 1}
        >
          上一页
        </Button>
        <div className="text-sm">
          第 {currentPage} 页，共 {totalPages} 页
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(Math.min(totalPages, currentPage + 1), pageSize)}
          disabled={currentPage >= totalPages}
        >
          下一页
        </Button>
      </div>
    </div>
  );
};
import { adminOrderClient, orderClientManager } from '../api';
import type { InferResponseType } from 'hono/client';
import { UpdateOrderDto } from '@d8d/orders-module-mt/schemas';


// 类型定义
type OrderResponse = InferResponseType<typeof adminOrderClient.index.$get, 200>['data'][0] & {
  user?: {
    id: number;
    username: string;
    phone: string | null;
    openid?: string | null; // 添加openid字段
    hasSubscribedDeliveryNotice?: boolean; // 添加订阅状态字段
  } | null;
  tenantId?: number; // 添加tenantId字段
};
type UpdateRequest = any;
// 发货请求类型 - 使用UpdateOrderDto的类型
type DeliveryRequest = {
  deliveryType: number;
  deliveryCompany?: string | null;
  deliveryNo?: string | null;
  deliveryRemark?: string | null;
  deliveryTime?: string | null;
};
type DeliveryResponse = any;

// 微信服务消息通知配置类型 - 参考useShareAppMessage的设计模式
interface WechatServiceMessageConfig {
  openid: string;
  templateId: string;
  page?: string;
  data: Record<string, { value: string }>;
  miniprogramState?: 'developer' | 'trial' | 'formal';
  tenantId?: number; // 添加tenantId参数
}

// 微信服务消息通知结果类型
interface WechatServiceMessageResult {
  success: boolean;
  message: string;
  data?: any;
  error?: any;
}

// 微信服务消息通知函数 - 参考useShareAppMessage的简洁设计模式
const sendWechatServiceMessage = async (config: WechatServiceMessageConfig): Promise<WechatServiceMessageResult> => {
  try {
    console.debug('准备发送微信服务消息:', config);

    // 调用后端微信API
    const response = await fetch('/api/v1/auth/send-template-message', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        openid: config.openid,
        templateId: config.templateId,
        data: config.data,
        page: config.page || 'pages/index/index',
        miniprogramState: config.miniprogramState || 'formal',
        tenantId: config.tenantId
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('微信服务消息API调用失败:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText
      });
      return {
        success: false,
        message: `微信服务消息发送失败: ${response.status}`,
        error: errorText
      };
    }

    const result = await response.json();

    
    console.debug('微信服务消息发送成功:', result);

    return {
      success: true,
      message: '微信服务消息发送成功',
      data: result
    };

  } catch (error) {
    console.error('发送微信服务消息时出错:', error);
    return {
      success: false,
      message: '微信服务消息发送失败',
      error
    };
  }
};

// 格式化微信日期时间
const formatWechatDate = (isoDateString: string | null | undefined): string => {
  try {
    // 如果日期字符串为空，使用当前时间
    const date = isoDateString ? new Date(isoDateString) : new Date();
    // 微信date类型格式：YYYY年MM月DD日 HH:mm
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
  } catch (error) {
    console.error('格式化微信日期失败:', error, isoDateString);
    // 返回当前时间的格式化版本作为备用
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
  }
};

// 获取微信小店快递公司列表
const getWechatDeliveryCompanies = async (tenantId?: number): Promise<{ success: boolean; message: string; data?: any }> => {
  try {
    console.debug('准备获取微信小店快递公司列表:', { tenantId });

    // 调用后端获取快递公司列表API
    const response = await fetch('/api/v1/auth/get-delivery-companies', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        tenantId
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('获取快递公司列表API调用失败:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText
      });

      let errorMessage = `获取快递公司列表失败: ${response.status}`;
      try {
        const errorData = JSON.parse(errorText);
        if (errorData.message) {
          errorMessage = errorData.message;
        }
        if (errorData.error?.message) {
          errorMessage = errorData.error.message;
        }
      } catch (e) {
        // 如果无法解析为JSON，使用原始文本
        if (errorText) {
          errorMessage = errorText.substring(0, 200);
        }
      }

      return {
        success: false,
        message: errorMessage,
        error: errorText
      };
    }

    const result = await response.json();
    console.debug('获取快递公司列表成功:', result);

    return {
      success: true,
      message: '获取快递公司列表成功',
      data: result
    };

  } catch (error) {
    console.error('调用获取快递公司列表API时出错:', error);
    return {
      success: false,
      message: '获取快递公司列表失败',
      error
    };
  }
};

// 调用微信小店发货API
const sendWechatShopDelivery = async (order: OrderResponse, deliveryData: DeliveryRequest): Promise<{ success: boolean; message: string; data?: any }> => {
  try {
    console.debug('准备调用微信小店发货API:', {
      orderId: order.id,
      orderNo: order.orderNo,
      deliveryType: deliveryData.deliveryType,
      deliveryCompany: deliveryData.deliveryCompany,
      deliveryNo: deliveryData.deliveryNo,
      tenantId: order.tenantId
    });

    // 调用后端微信小店发货API
    const response = await fetch('/api/v1/auth/send-wechat-shop-delivery', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        orderId: order.id,
        orderNo: order.orderNo,
        deliveryType: deliveryData.deliveryType,
        deliveryCompany: deliveryData.deliveryCompany || null,
        deliveryNo: deliveryData.deliveryNo || null,
        tenantId: order.tenantId
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('微信小店发货API调用失败:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText
      });
      return {
        success: false,
        message: `微信小店发货失败: ${response.status}`,
        error: errorText
      };
    }

    const result = await response.json();
    console.debug('微信小店发货成功:', result);

    return {
      success: true,
      message: '微信小店发货成功',
      data: result
    };

  } catch (error) {
    console.error('调用微信小店发货API时出错:', error);
    return {
      success: false,
      message: '微信小店发货失败',
      error
    };
  }
};

// 调用微信小程序发货信息录入API
const uploadShippingInfoToWechat = async (order: OrderResponse, deliveryData: DeliveryRequest, tenantId?: number): Promise<{ success: boolean; message: string; data?: any }> => {
  try {
    console.debug('准备调用微信小程序发货信息录入API:', {
      orderId: order.id,
      orderNo: order.orderNo,
      deliveryType: deliveryData.deliveryType,
      deliveryCompany: deliveryData.deliveryCompany,
      deliveryNo: deliveryData.deliveryNo,
      tenantId: tenantId || order.tenantId
    });

    // 根据发货类型准备参数
    let expressInfo = undefined;
    let localDeliveryInfo = undefined;

    switch (deliveryData.deliveryType) {
      case 1: // 物流快递
        if (deliveryData.deliveryCompany && deliveryData.deliveryNo) {
          // 注意：这里需要将快递公司名称转换为微信小店支持的delivery_id
          // 实际项目中需要维护一个快递公司映射表，这里暂时使用快递公司名称
          expressInfo = {
            deliveryId: deliveryData.deliveryCompany, // 临时使用公司名称，实际应该用ID
            waybillId: deliveryData.deliveryNo
          };
        }
        break;
      case 2: // 同城配送
        // 同城配送需要配送员信息，这里使用默认值
        // localDeliveryInfo = {
        //   deliveryName: '配送员',
        //   deliveryPhone: '13800138000'
        // };
        // break;
      case 3: // 虚拟发货
      case 4: // 用户自提
        // 无需物流，不需要额外信息
        break;
    }

    // 调用后端发货信息录入API
    const response = await fetch('/api/v1/auth/upload-shipping-info', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        orderId: order.orderNo, // 使用订单号作为微信小程序订单ID
        deliveryType: deliveryData.deliveryType, // 直接使用前端的deliveryType值
        expressInfo,
        localDeliveryInfo,
        isAllDelivered: true,
        tenantId: tenantId || order.tenantId
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('发货信息录入API调用失败:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText
      });
      return {
        success: false,
        message: `发货信息录入失败: ${response.status}`,
        error: errorText
      };
    }

    const result = await response.json();
    console.debug('发货信息录入成功:', result);

    return {
      success: true,
      message: '发货信息录入成功',
      data: result
    };

  } catch (error) {
    console.error('调用发货信息录入API时出错:', error);
    return {
      success: false,
      message: '发货信息录入失败',
      error
    };
  }
};

// 发货成功微信通知函数 - 使用新的配置化设计
const sendDeliverySuccessNotification = async (order: OrderResponse, deliveryData: DeliveryRequest): Promise<WechatServiceMessageResult> => {
  // 检查是否有用户信息和openid
  if (!order.user || !order.user.id) {
    console.warn('订单没有用户信息，无法发送微信通知');
    return { success: false, message: '订单没有用户信息，无法发送微信通知' };
  }

  // 检查用户是否有openid（微信小程序用户）
  if (!order.user.openid) {
    console.warn('用户没有绑定微信小程序，无法发送微信通知', {
      userId: order.user.id,
      username: order.user.username
    });
    return { success: false, message: '用户没有绑定微信小程序，无法发送微信通知' };
  }

  // 检查用户是否已订阅发货通知
  if (order.user.hasSubscribedDeliveryNotice !== true) {
    console.debug('用户未订阅发货通知，跳过发送微信通知', {
      userId: order.user.id,
      username: order.user.username,
      hasSubscribedDeliveryNotice: order.user.hasSubscribedDeliveryNotice
    });
    return {
      success: false,
      message: '用户未订阅发货通知，跳过发送微信通知',
      data: { skipped: true, reason: 'user_not_subscribed' }
    };
  }

  console.debug('用户已订阅发货通知，准备发送微信通知', {
    userId: order.user.id,
    username: order.user.username,
    openid: order.user.openid?.substring(0, 10) + '...' // 部分隐藏openid
  });

  // 构建微信服务消息配置 - 参考useShareAppMessage的配置对象模式
  const config: WechatServiceMessageConfig = {
    openid: order.user.openid,
    templateId: 'T00N0Wq3ECjksXSvPWUBgOUukl1TCE7PhxqeDnFPfso', // 发货成功通知模板ID
    page: 'pages/order/detail/index', // 点击跳转到订单详情页
    data: {
      // 根据实际微信模板字段配置
      character_string7: {
        value: `${order.orderNo}`
      },
      date6: {
        value: formatWechatDate(deliveryData.deliveryTime)
      },
      amount9: {
        value: `¥${order.payAmount.toFixed(2)}`
      },
      phrase12: {
        value: deliveryTypeMap[deliveryData.deliveryType as keyof typeof deliveryTypeMap]?.label || '未知'
      },
      thing4: {
        value: (deliveryData.deliveryRemark || '请收到货/提货后及时确认收货，2天后将自动确认收货，如有异常请及时进行交易投诉。').substring(0, 20)
      }
    },
    miniprogramState: 'formal',
    tenantId: order.tenantId // 从订单数据中获取tenantId
  };

  // 调用微信服务消息函数
  return await sendWechatServiceMessage(config);
};

// 状态映射
const orderStatusMap = {
  0: { label: '未发货', color: 'warning' },
  1: { label: '已发货', color: 'info' },
  2: { label: '收货成功', color: 'success' },
  3: { label: '已退货', color: 'destructive' },
} as const;

const payStatusMap = {
  0: { label: '未支付', color: 'warning' },
  1: { label: '支付中', color: 'info' },
  2: { label: '支付成功', color: 'success' },
  3: { label: '已退款', color: 'secondary' },
  4: { label: '支付失败', color: 'destructive' },
  5: { label: '订单关闭', color: 'destructive' },
} as const;

const orderTypeMap = {
  1: { label: '实物订单', color: 'default' },
  2: { label: '虚拟订单', color: 'secondary' },
} as const;

const deliveryTypeMap = {
  0: { label: '未发货', color: 'warning' },
  1: { label: '物流快递', color: 'info' },
  2: { label: '同城配送', color: 'info' },
  3: { label: '虚拟发货', color: 'info' },
  4: { label: '用户自提', color: 'info' },
} as const;

export const OrderManagement = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: '',
    status: 'all',
    payStatus: 'all',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingOrder, setEditingOrder] = useState<OrderResponse | null>(null);
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<OrderResponse | null>(null);
  const [deliveryModalOpen, setDeliveryModalOpen] = useState(false);
  const [deliveringOrder, setDeliveringOrder] = useState<OrderResponse | null>(null);
  const [deliveryCompanies, setDeliveryCompanies] = useState<Array<{ delivery_id: string; delivery_name: string }>>([]);
  const [loadingCompanies, setLoadingCompanies] = useState(false);


  // 表单实例
  const updateForm = useForm<UpdateRequest>({
    resolver: zodResolver(UpdateOrderDto),
    defaultValues: {},
  });

  // 发货表单实例
  const deliveryForm = useForm<DeliveryRequest>({
    defaultValues: {
      deliveryType: 2, // 2表示同城配送
      deliveryCompany: '__select__',
      deliveryNo: '',
      deliveryRemark: '',
    },
  });

 
  // 数据查询 - 60秒自动刷新
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['orders', searchParams],
    queryFn: async () => {
      const filters: any = {};

      if (searchParams.status !== 'all') {
        filters.state = parseInt(searchParams.status);
      }

      if (searchParams.payStatus !== 'all') {
        filters.payState = parseInt(searchParams.payStatus);
      }

      const res = await orderClientManager.getAdminOrderClient().index.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search,
          ...(Object.keys(filters).length > 0 && { filters: JSON.stringify(filters) }),
        }
      });
      if (res.status !== 200) throw new Error('获取订单列表失败');
      return await res.json();
    },
    refetchInterval: 60000, // 60秒自动刷新
    refetchIntervalInBackground: false, // 只在页面可见时刷新
    staleTime: 30000, // 30秒后数据视为过期
  });

  // 处理搜索
  const handleSearch = () => {
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 检查交易管理状态
  const handleCheckTradeManaged = async () => {
    try {
      console.debug('开始检查交易管理状态');

      // 这里需要获取当前租户ID，可以从订单数据中获取第一个订单的tenantId
      // 或者使用默认值，这里先使用默认值
      const tenantId = data?.data?.[0]?.tenantId || undefined;

      const response = await fetch('/api/v1/auth/get-is-trade-managed', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          tenantId
        }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('检查交易管理状态失败:', {
          status: response.status,
          statusText: response.statusText,
          error: errorText
        });

        let errorMessage = `检查交易管理状态失败: ${response.status}`;
        try {
          const errorData = JSON.parse(errorText);
          if (errorData.message) {
            errorMessage = errorData.message;
          }
        } catch (e) {
          // 如果无法解析为JSON，使用原始文本
          if (errorText) {
            errorMessage = errorText.substring(0, 200);
          }
        }

        toast.error(errorMessage);
        return;
      }

      const result = await response.json();
      console.debug('交易管理状态检查结果:', result);

      if (result.success) {
        const isTradeManaged = result.data?.is_trade_managed;
        const statusText = isTradeManaged ? '已开启' : '未开启';
        toast.success(`交易管理状态: ${statusText}`);
      } else {
        toast.error(result.message || '检查交易管理状态失败');
      }

    } catch (error) {
      console.error('检查交易管理状态时出错:', error);
      toast.error('检查交易管理状态失败，请重试');
    }
  };

  // 处理编辑订单
  const handleEditOrder = (order: OrderResponse) => {
    setEditingOrder(order);
    updateForm.reset({
      state: order.state,
      payState: order.payState,
      remark: order.remark || '',
    });
    setIsModalOpen(true);
  };

  // 处理查看详情
  const handleViewDetails = (order: OrderResponse) => {
    setSelectedOrder(order);
    setDetailModalOpen(true);
  };

  // 处理发货
  const handleDeliveryOrder = async (order: OrderResponse) => {
    setDeliveringOrder(order);
    deliveryForm.reset({
      deliveryType: 2, // 2表示同城配送
      deliveryCompany: '__select__',
      deliveryNo: '',
      deliveryRemark: '',
    });

    // // 获取快递公司列表
    // setLoadingCompanies(true);
    // try {
    //   const result = await getWechatDeliveryCompanies(order.tenantId);
    //   console.log("result:",result);
    //   const resdata = result.data;
    //   if (result.success && resdata.data?.company_list) {
    //     const companyList = resdata.data.company_list;
    //     setDeliveryCompanies(companyList);

    //     // 如果有快递公司列表，自动选中第一个
    //     if (companyList.length > 0) {
    //       // 延迟设置，确保组件已经渲染
    //       setTimeout(() => {
    //         deliveryForm.setValue('deliveryCompany', companyList[0].delivery_name);
    //       }, 0);
    //     }
    //   } else {
    //     console.warn('获取快递公司列表失败或为空:', result);
    //     setDeliveryCompanies([]);
    //     // 如果获取失败，显示提示信息
    //     if (resdata.message && !resdata.message.includes('获取快递公司列表成功')) {
    //       toast.warning(`获取快递公司列表失败: ${resdata.message}，请手动输入快递公司名称`);
    //     }
    //   }
    // } catch (error) {
    //   console.error('获取快递公司列表时出错:', error);
    //   setDeliveryCompanies([]);
    //   toast.warning('获取快递公司列表失败，请手动输入快递公司名称');
    // } finally {
    //   setLoadingCompanies(false);
    // }

    setDeliveryModalOpen(true);
  };

  // 处理发货提交
  // const handleDeliverySubmit = async (data: DeliveryRequest) => {
  //   if (!deliveringOrder || !deliveringOrder.id) return;

  //   try {
  //     const res = await (orderClientManager.getAdminDeliveryClient() as any)[':id']['delivery']['$post']({
  //       param: { id: deliveringOrder.id },
  //       json: data,
  //     });

  //     if (res.status === 200) {
  //       const result = await res.json() as DeliveryResponse;
  //       toast.success(result.message || '发货成功');
  //       setDeliveryModalOpen(false);
  //       refetch();
  //     } else {
  //       const error = await res.json();
  //       toast.error(error.message || '发货失败');
  //     }
  //   } catch (error) {
  //     console.error('发货失败:', error);
  //     toast.error('发货失败，请重试');
  //   }
  // };



  const handleDeliverySubmit = async (data: DeliveryRequest) => {
    if (!deliveringOrder || !deliveringOrder.id) {
      console.error('发货失败: deliveringOrder或id为空', { deliveringOrder });
      return;
    }

    // 处理快递公司选择值
    if (data.deliveryCompany === '__select__' || data.deliveryCompany === '__manual__') {
      data.deliveryCompany = null;
    }

    // 验证：如果选择物流快递方式，必须填写快递公司
    if (data.deliveryType === 1 && !data.deliveryCompany) {
      toast.error('请选择或输入快递公司');
      return;
    }

    try {
      // console.debug('发货请求数据:', {
      //   orderId: deliveringOrder.id,
      //   orderNo: deliveringOrder.orderNo,
      //   data,
      //   orderState: deliveringOrder.state,
      //   payState: deliveringOrder.payState
      // });

      // 使用adminOrderClient的$put接口来更新订单发货信息
      // 因为adminDeliveryRoutes没有被挂载到服务器，而adminOrderRoutes已经被正确挂载

      data.deliveryTime = new Date().toISOString();

      const updateData = {
        state: 1, // 已发货状态
        deliveryType: data.deliveryType,
        deliveryCompany: data.deliveryCompany || null,
        deliveryNo: data.deliveryNo || null,
        deliveryTime: data.deliveryTime,
        deliveryRemark: data.deliveryRemark || null,
      };

     // console.debug('更新订单数据:', updateData);

      // 调用adminOrderClient的$put接口
      const res = await (orderClientManager.getAdminOrderClient() as any)[':id']['$put']({
        param: { id: deliveringOrder.id },
        json: updateData,
      });

      // console.debug('发货响应详情:', {
      //   status: res.status,
      //   statusText: res.statusText,
      //   headers: Object.fromEntries(res.headers.entries()),
      //   url: res.url
      // });
      
      if (res.status === 200) {
        let result: DeliveryResponse;

        try {
          const responseText = await res.text();
          if (responseText.trim()) {
            try {
              result = JSON.parse(responseText) as DeliveryResponse;
            } catch (parseError) {
              console.error('成功响应JSON解析失败:', parseError);
              result = { success: true, message: '发货成功' } as DeliveryResponse;
            }
          } else {
            result = { success: true, message: '发货成功' } as DeliveryResponse;
          }
        } catch (error) {
          console.error('处理成功响应失败:', error);
          result = { success: true, message: '发货成功' } as DeliveryResponse;
        }

        console.debug('发货成功:', result);
        toast.success(result.message || '发货成功');
        setDeliveryModalOpen(false);
        refetch();
        // 发货成功后调用微信小程序发货信息录入API
        try {
          const uploadResult = await uploadShippingInfoToWechat(deliveringOrder, data, deliveringOrder?.tenantId);

          if (uploadResult.success) {
            console.debug("微信小程序发货信息录入成功:", uploadResult);
            // 可以在这里添加额外的成功处理，比如记录日志
          } else {
            // 微信小程序发货信息录入失败，记录警告但不影响主流程
            console.warn("微信小程序发货信息录入失败，但系统发货成功:", uploadResult);
            // 可以在这里添加额外的处理，比如记录到日志系统或发送告警
          }
        } catch (uploadError) {
          console.error("调用微信小程序发货信息录入API时发生异常:", uploadError);
          // 不阻止发货成功，只记录错误
        }


        


        // 发货成功后调用微信小店发货API
        // try {
        //   const wechatDeliveryResult = await sendWechatShopDelivery(deliveringOrder, data);

        //   if (wechatDeliveryResult.success) {
        //     console.debug('微信小店发货成功:', wechatDeliveryResult);
        //     // 可以在这里添加额外的成功处理，比如记录日志
        //   } else {
        //     // 微信小店发货失败，记录警告但不影响主流程
        //     console.warn('微信小店发货失败，但系统发货成功:', wechatDeliveryResult);
        //     // 可以在这里添加额外的处理，比如记录到日志系统或发送告警
        //   }
        // } catch (wechatDeliveryError) {
        //   console.error('调用微信小店发货API时发生异常:', wechatDeliveryError);
        //   // 不阻止发货成功，只记录错误
        // }





        // 发货成功后发送微信服务消息通知 - 使用新的配置化设计
        // try {
        //   const notificationResult = await sendDeliverySuccessNotification(deliveringOrder, data);

        //   // 根据通知结果记录不同的日志
        //   if (notificationResult.success) {
        //     console.debug('微信发货通知发送成功:', notificationResult);
        //   } else if (notificationResult.data?.skipped) {
        //     // 用户未订阅，这是正常情况，记录为debug级别
        //     console.debug('用户未订阅发货通知，跳过发送:', {
        //       userId: deliveringOrder.user?.id,
        //       username: deliveringOrder.user?.username,
        //       reason: notificationResult.data.reason
        //     });
        //   } else {
        //     // 其他原因导致的失败，记录为warn级别
        //     console.warn('微信发货通知发送失败，但发货成功:', notificationResult);
        //     // 可以在这里添加额外的处理，比如记录到日志系统
        //   }
        // } catch (notificationError) {
        //   console.error('发送微信发货通知时发生异常:', notificationError);
        //   // 不阻止发货成功，只记录错误
        // }

      } else {
        // 先尝试获取响应文本，避免JSON解析错误
        let errorText = '';
        let errorData: any = null;

        try {
          errorText = await res.text();
          console.debug('发货失败响应文本:', errorText);

          // 尝试解析为JSON
          if (errorText.trim()) {
            try {
              errorData = JSON.parse(errorText);
            } catch (parseError) {
              console.warn('响应不是有效的JSON:', parseError);
              errorData = { message: errorText.substring(0, 100) + '...' };
            }
          }
        } catch (textError) {
          console.error('获取响应文本失败:', textError);
          errorData = { message: `请求失败，状态码: ${res.status}` };
        }

        console.error('发货失败响应:', {
          status: res.status,
          statusText: res.statusText,
          errorData,
          errorText: errorText.substring(0, 200),
          orderId: deliveringOrder.id
        });

        // 显示错误消息
        const errorMessage = errorData?.message ||
                           errorData?.error?.message ||
                           res.statusText ||
                           `发货失败 (${res.status})`;
        toast.error(errorMessage);
      }
    } catch (error) {
      console.error('发货请求异常:', error);
      toast.error('发货失败，请重试');
    }
  };


  // 处理更新订单
  const handleUpdateSubmit = async (data: UpdateRequest) => {
    if (!editingOrder || !editingOrder.id) return;

    try {
      const res = await (orderClientManager.getAdminOrderClient() as any)[':id']['$put']({
        param: { id: editingOrder.id },
        json: data,
      });

      if (res.status === 200) {
        toast.success('订单更新成功');
        setIsModalOpen(false);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '更新失败');
      }
    } catch (error) {
      console.error('更新订单失败:', error);
      toast.error('更新失败，请重试');
    }
  };

  // 格式化金额
  const formatAmount = (amount: number) => {
    return `¥${amount.toFixed(2)}`;
  };

  // 获取状态颜色
  const getStatusBadge = (status: number, type: 'order' | 'pay' | 'delivery') => {
    const map = type === 'order' ? orderStatusMap : type === 'pay' ? payStatusMap : deliveryTypeMap;
    const config = map[status as keyof typeof map] || { label: '未知', color: 'default' };

    return <Badge variant={config.color as any}>{config.label}</Badge>;
  };

  // 骨架屏 - 只覆盖表格区域，搜索区域保持可用
  if (isLoading) {
    return (
      <div className="space-y-4">
        {/* 页面标题 */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold">订单管理</h1>
            <p className="text-muted-foreground">管理所有订单信息</p>
          </div>
        </div>

        {/* 搜索区域 - 保持可用 */}
        <Card>
          <CardHeader>
            <CardTitle>订单列表</CardTitle>
            <CardDescription>查看和管理所有订单</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex gap-4 mb-4">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索订单号、手机号、收货人姓名..."
                  value={searchParams.search}
                  onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                  className="pl-8"
                  data-testid="order-search-input"
                />
              </div>
              <Select
                value={searchParams.status}
                onValueChange={(value) => setSearchParams(prev => ({ ...prev, status: value, page: 1 }))}
              >
                <SelectTrigger className="w-32" data-testid="order-status-select">
                  <SelectValue placeholder="订单状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="0">未发货</SelectItem>
                  <SelectItem value="1">已发货</SelectItem>
                  <SelectItem value="2">收货成功</SelectItem>
                  <SelectItem value="3">已退货</SelectItem>
                </SelectContent>
              </Select>
              <Select
                value={searchParams.payStatus}
                onValueChange={(value) => setSearchParams(prev => ({ ...prev, payStatus: value, page: 1 }))}
              >
                <SelectTrigger className="w-32" data-testid="order-pay-status-select">
                  <SelectValue placeholder="支付状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="0">未支付</SelectItem>
                  <SelectItem value="1">支付中</SelectItem>
                  <SelectItem value="2">支付成功</SelectItem>
                  <SelectItem value="3">已退款</SelectItem>
                  <SelectItem value="4">支付失败</SelectItem>
                  <SelectItem value="5">订单关闭</SelectItem>
                </SelectContent>
              </Select>
              <Button onClick={handleSearch} data-testid="order-search-button">
                <Search className="h-4 w-4 mr-2" />
                搜索
              </Button>
            </div>

            {/* 表格骨架屏 */}
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>订单号</TableHead>
                    <TableHead>用户信息</TableHead>
                    <TableHead>收货人</TableHead>
                    <TableHead>金额</TableHead>
                    <TableHead>订单状态</TableHead>
                    <TableHead>支付状态</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {[...Array(5)].map((_, i) => (
                    <TableRow key={i}>
                      <TableCell>
                        <Skeleton className="h-4 w-32" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-4 w-24" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-4 w-20" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-4 w-16" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-6 w-16" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-6 w-16" />
                      </TableCell>
                      <TableCell>
                        <Skeleton className="h-4 w-24" />
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Skeleton className="h-8 w-8" />
                          <Skeleton className="h-8 w-8" />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            {/* 分页骨架屏 */}
            <div className="flex items-center justify-between px-2 py-4">
              <Skeleton className="h-4 w-32" />
              <div className="flex items-center space-x-2">
                <Skeleton className="h-8 w-16" />
                <Skeleton className="h-4 w-24" />
                <Skeleton className="h-8 w-16" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">订单管理</h1>
          <p className="text-muted-foreground">管理所有订单信息</p>
        </div>
        {/* <Button
          variant="outline"
          onClick={() => handleCheckTradeManaged()}
          data-testid="check-trade-managed-button"
        >
          检查交易管理状态
        </Button> */}
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>订单列表</CardTitle>
          <CardDescription>查看和管理所有订单</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4 mb-4">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="搜索订单号、手机号、收货人姓名..."
                value={searchParams.search}
                onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                className="pl-8"
                data-testid="order-search-input"
              />
            </div>
            <Select
              value={searchParams.status}
              onValueChange={(value) => setSearchParams(prev => ({ ...prev, status: value, page: 1 }))}
            >
              <SelectTrigger className="w-32" data-testid="order-status-select">
                <SelectValue placeholder="订单状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部</SelectItem>
                <SelectItem value="0">未发货</SelectItem>
                <SelectItem value="1">已发货</SelectItem>
                <SelectItem value="2">收货成功</SelectItem>
                <SelectItem value="3">已退货</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={searchParams.payStatus}
              onValueChange={(value) => setSearchParams(prev => ({ ...prev, payStatus: value, page: 1 }))}
            >
              <SelectTrigger className="w-32" data-testid="order-pay-status-select">
                <SelectValue placeholder="支付状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部</SelectItem>
                <SelectItem value="0">未支付</SelectItem>
                <SelectItem value="1">支付中</SelectItem>
                <SelectItem value="2">支付成功</SelectItem>
                <SelectItem value="3">已退款</SelectItem>
                <SelectItem value="4">支付失败</SelectItem>
                <SelectItem value="5">订单关闭</SelectItem>
              </SelectContent>
            </Select>
            <Button onClick={handleSearch} data-testid="order-search-button">
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
          </div>

          {/* 数据表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>订单号</TableHead>
                  <TableHead>用户信息</TableHead>
                  <TableHead>收货人</TableHead>
                  <TableHead>金额</TableHead>
                  <TableHead>订单状态</TableHead>
                  <TableHead>支付状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data?.data.map((order) => (
                  <TableRow key={order.id}>
                    <TableCell>
                      <div>
                        <p className="font-medium">{order.orderNo}</p>
                        <p className="text-sm text-muted-foreground">
                          {orderTypeMap[order.orderType as keyof typeof orderTypeMap]?.label}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p>{order.user?.username || '-'}</p>
                        <p className="text-sm text-muted-foreground">{order.userPhone}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p>{order.recevierName || '-'}</p>
                        <p className="text-sm text-muted-foreground">{order.receiverMobile}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p className="font-medium">{formatAmount(order.payAmount)}</p>
                        <p className="text-sm text-muted-foreground">{formatAmount(order.amount)}</p>
                      </div>
                    </TableCell>
                    <TableCell>{getStatusBadge(order.state, 'order')}</TableCell>
                    <TableCell>{getStatusBadge(order.payState, 'pay')}</TableCell>
                    <TableCell>
                      {format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm')}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleViewDetails(order)}
                          data-testid="order-view-button"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        {order.state === 0 && order.payState === 2 && (
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleDeliveryOrder(order)}
                            data-testid="order-delivery-button"
                          >
                            <Truck className="h-4 w-4" />
                          </Button>
                        )}
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditOrder(order)}
                          data-testid="order-edit-button"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {data?.data.length === 0 && !isLoading && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">暂无订单数据</p>
            </div>
          )}

          <DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={data?.pagination.total || 0}
            onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
          />
        </CardContent>
      </Card>

      {/* 编辑订单模态框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>编辑订单</DialogTitle>
            <DialogDescription>更新订单状态和备注信息</DialogDescription>
          </DialogHeader>

          <Form {...updateForm}>
            <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
              <FormField
                control={updateForm.control}
                name="state"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>订单状态</FormLabel>
                    <Select onValueChange={(value) => field.onChange(parseInt(value))} value={field.value?.toString()}>
                      <FormControl>
                        <SelectTrigger data-testid="edit-order-status-select">
                          <SelectValue placeholder="选择订单状态" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="0">未发货</SelectItem>
                        <SelectItem value="1">已发货</SelectItem>
                        <SelectItem value="2">收货成功</SelectItem>
                        <SelectItem value="3">已退货</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={updateForm.control}
                name="payState"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>支付状态</FormLabel>
                    <Select onValueChange={(value) => field.onChange(parseInt(value))} value={field.value?.toString()}>
                      <FormControl>
                        <SelectTrigger data-testid="edit-pay-status-select">
                          <SelectValue placeholder="选择支付状态" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="0">未支付</SelectItem>
                        <SelectItem value="1">支付中</SelectItem>
                        <SelectItem value="2">支付成功</SelectItem>
                        <SelectItem value="3">已退款</SelectItem>
                        <SelectItem value="4">支付失败</SelectItem>
                        <SelectItem value="5">订单关闭</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={updateForm.control}
                name="remark"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>客户备注</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="输入客户备注信息..."
                        className="resize-none"
                        data-testid="edit-remark-textarea"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                  取消
                </Button>
                <Button type="submit" data-testid="order-save-button">保存</Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* 订单详情模态框 */}
      <Dialog open={detailModalOpen} onOpenChange={setDetailModalOpen}>
        <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>订单详情</DialogTitle>
            <DialogDescription>查看订单的详细信息</DialogDescription>
          </DialogHeader>

          {selectedOrder && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="font-medium mb-2">订单信息</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">订单号:</span>
                      <span>{selectedOrder.orderNo}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">订单类型:</span>
                      <span>{orderTypeMap[selectedOrder.orderType as keyof typeof orderTypeMap]?.label}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">订单金额:</span>
                      <span>{formatAmount(selectedOrder.amount)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">实付金额:</span>
                      <span>{formatAmount(selectedOrder.payAmount)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">运费:</span>
                      <span>{formatAmount(selectedOrder.freightAmount)}</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h4 className="font-medium mb-2">状态信息</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">订单状态:</span>
                      <span>{getStatusBadge(selectedOrder.state, 'order')}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">支付状态:</span>
                      <span>{getStatusBadge(selectedOrder.payState, 'pay')}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">支付方式:</span>
                      <span>{selectedOrder.payType === 1 ? '积分' : selectedOrder.payType === 2 ? '礼券' : '未选择'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">创建时间:</span>
                      <span>{format(new Date(selectedOrder.createdAt), 'yyyy-MM-dd HH:mm')}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="font-medium mb-2">用户信息</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">用户名:</span>
                      <span>{selectedOrder.user?.username || '-'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">手机号:</span>
                      <span>{selectedOrder.userPhone || '-'}</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h4 className="font-medium mb-2">收货信息</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">收货人:</span>
                      <span>{selectedOrder.recevierName || '-'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">手机号:</span>
                      <span>{selectedOrder.receiverMobile || '-'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">地址:</span>
                      <span>{selectedOrder.address || '-'}</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 订单商品信息 */}
              <div>
                <h4 className="font-medium mb-3 flex items-center gap-2">
                  <Package className="h-4 w-4" />
                  订单商品
                </h4>
                <div className="border rounded-md overflow-hidden">
                  <div className="bg-muted px-4 py-2 border-b">
                    <div className="grid grid-cols-12 gap-4 text-sm font-medium">
                      <div className="col-span-5">商品信息</div>
                      <div className="col-span-2 text-center">单价</div>
                      <div className="col-span-2 text-center">数量</div>
                      <div className="col-span-3 text-right">小计</div>
                    </div>
                  </div>
                  <div className="divide-y">
                    {selectedOrder.orderGoods?.map((item, index) => (
                      <div key={item.id || index} className="px-4 py-3">
                        <div className="grid grid-cols-12 gap-4 items-center">
                          <div className="col-span-5 flex items-center gap-3">
                            {item.imageFile && (
                              <img
                                src={item.imageFile.fullUrl}
                                alt={item.goodsName}
                                className="w-12 h-12 rounded-md object-cover"
                              />
                            )}
                            <div>
                              <p className="font-medium text-sm">{item.goodsName}</p>
                            </div>
                          </div>
                          <div className="col-span-2 text-center text-sm">
                            {formatAmount(item.price)}
                          </div>
                          <div className="col-span-2 text-center text-sm">
                            {item.num}
                          </div>
                          <div className="col-span-3 text-right text-sm font-medium">
                            {formatAmount(item.price * item.num)}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  {selectedOrder.orderGoods?.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      暂无商品信息
                    </div>
                  )}
                </div>
              </div>

              {selectedOrder.remark && (
                <div>
                  <h4 className="font-medium mb-2">客户备注</h4>
                  <p className="text-sm bg-muted p-3 rounded-md">{selectedOrder.remark}</p>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 发货模态框 */}
      <Dialog open={deliveryModalOpen} onOpenChange={setDeliveryModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>订单发货</DialogTitle>
            <DialogDescription>选择发货方式并填写发货信息</DialogDescription>
          </DialogHeader>

          {deliveringOrder && (
            <div className="space-y-4">
              <div className="bg-muted p-3 rounded-md">
                <h4 className="font-medium mb-2">订单信息</h4>
                <div className="text-sm space-y-1">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">订单号:</span>
                    <span>{deliveringOrder.orderNo}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">收货人:</span>
                    <span>{deliveringOrder.recevierName || '-'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">手机号:</span>
                    <span>{deliveringOrder.receiverMobile || '-'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">地址:</span>
                    <span>{deliveringOrder.address || '-'}</span>
                  </div>
                </div>
              </div>

              <Form {...deliveryForm}>
                <form onSubmit={deliveryForm.handleSubmit(handleDeliverySubmit)} className="space-y-4">
                  <FormField
                    control={deliveryForm.control}
                    name="deliveryType"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>发货方式</FormLabel>
                        <Select onValueChange={(value) => field.onChange(parseInt(value))} value={field.value?.toString()}>
                          <FormControl>
                            <SelectTrigger data-testid="delivery-type-select">
                              <SelectValue placeholder="选择发货方式" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {/* <SelectItem value="1">物流快递</SelectItem> */}
                            <SelectItem value="2">同城配送</SelectItem>
                            <SelectItem value="3">用户自提</SelectItem>
                            <SelectItem value="4">虚拟发货</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {deliveryForm.watch('deliveryType') === 1 && (
                    <>
                      <FormField
                        control={deliveryForm.control}
                        name="deliveryCompany"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>快递公司</FormLabel>
                            {deliveryForm.watch('deliveryCompany') === '__manual__' ? (
                              <>
                                <div className="flex gap-2 mb-2">
                                  <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    onClick={() => field.onChange('__select__')}
                                  >
                                    ← 返回选择列表
                                  </Button>
                                </div>
                                <FormControl>
                                  <Input
                                    placeholder="请输入快递公司名称"
                                    data-testid="delivery-company-manual-input"
                                    value={field.value === '__manual__' ? '' : field.value}
                                    onChange={(e) => field.onChange(e.target.value)}
                                  />
                                </FormControl>
                              </>
                            ) : (
                              <Select
                                onValueChange={field.onChange}
                                value={field.value || ''}
                                disabled={loadingCompanies}
                              >
                                <FormControl>
                                  <SelectTrigger data-testid="delivery-company-select">
                                    <SelectValue placeholder={
                                      loadingCompanies ? "加载中..." : "选择快递公司"
                                    } />
                                  </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  <SelectItem value="__select__">请选择快递公司</SelectItem>
                                  {deliveryCompanies.map((company) => (
                                    <SelectItem
                                      key={company.delivery_id}
                                      value={company.delivery_name}
                                    >
                                      {company.delivery_name}
                                    </SelectItem>
                                  ))}
                                  {deliveryCompanies.length === 0 && !loadingCompanies && (
                                    <>
                                      <SelectItem value="no_data" disabled>
                                        暂无快递公司数据（API未授权）
                                      </SelectItem>
                                      <SelectItem value="__manual__">手动输入快递公司</SelectItem>
                                    </>
                                  )}
                                </SelectContent>
                              </Select>
                            )}
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={deliveryForm.control}
                        name="deliveryNo"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>快递单号</FormLabel>
                            <FormControl>
                              <Input
                                placeholder="输入快递单号"
                                data-testid="delivery-no-input"
                                {...field}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </>
                  )}

                  <FormField
                    control={deliveryForm.control}
                    name="deliveryRemark"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>发货备注</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="输入发货备注信息..."
                            className="resize-none"
                            data-testid="delivery-remark-textarea"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <DialogFooter>
                    <Button type="button" variant="outline" onClick={() => setDeliveryModalOpen(false)}>
                      取消
                    </Button>
                    <Button type="submit" data-testid="delivery-submit-button">确认发货</Button>
                  </DialogFooter>
                </form>
              </Form>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
};