import type { ShopOrder } from '@/api/shop/shopOrder/model';

const toNum = (value: unknown): number | undefined => {
  if (value === null || value === undefined || value === '') return undefined;
  const n = Number(value);
  return Number.isFinite(n) ? n : undefined;
};

export const isShopOrderCompleted = (order: Pick<ShopOrder, 'orderStatus'>): boolean =>
  toNum(order?.orderStatus) === 1;

export const getShopOrderStatusText = (order: ShopOrder): string => {
  const orderStatus = toNum(order?.orderStatus);
  const deliveryStatus = toNum(order?.deliveryStatus);
  const riderId = toNum(order?.riderId);

  if (orderStatus === 2) return '已取消';
  if (orderStatus === 3) return '取消中';
  if (orderStatus === 4) return '退款申请中';
  if (orderStatus === 5) return '退款被拒绝';
  if (orderStatus === 6) return '退款成功';
  if (orderStatus === 7) return '客户端申请退款';
  if (orderStatus === 1) return '已完成';

  if (!order?.payStatus) return '等待买家付款';

  if (deliveryStatus === 10) return '待发货';
  if (deliveryStatus === 20) {
    if (!riderId || riderId === 0) return '待收货';
    if (order?.sendEndTime) return '待确认收货';
    return '配送中';
  }
  if (deliveryStatus === 30) return '部分发货';

  if (orderStatus === 0) return '未使用';
  return '未知状态';
};

export const getShopOrderStatusColor = (order: ShopOrder): string => {
  const orderStatus = toNum(order?.orderStatus);
  const deliveryStatus = toNum(order?.deliveryStatus);
  const riderId = toNum(order?.riderId);

  if (orderStatus === 2) return 'text-gray-500'; // 已取消
  if (orderStatus === 3) return 'text-orange-500'; // 取消中
  if (orderStatus === 4) return 'text-orange-500'; // 退款申请中
  if (orderStatus === 5) return 'text-red-500'; // 退款被拒绝
  if (orderStatus === 6) return 'text-green-500'; // 退款成功
  if (orderStatus === 7) return 'text-orange-500'; // 客户端申请退款
  if (orderStatus === 1) return 'text-green-600'; // 已完成

  if (!order?.payStatus) return 'text-orange-500'; // 等待买家付款

  if (deliveryStatus === 10) return 'text-blue-500'; // 待发货
  if (deliveryStatus === 20) {
    if (!riderId || riderId === 0) return 'text-purple-500'; // 待收货
    if (order?.sendEndTime) return 'text-purple-500'; // 待确认收货
    return 'text-blue-500'; // 配送中
  }
  if (deliveryStatus === 30) return 'text-blue-500'; // 部分发货

  if (orderStatus === 0) return 'text-gray-500'; // 未使用
  return 'text-gray-600';
};

