/**
 * 订单相关工具函数
 * 抽离 orders.vue 和 orderDetail.vue 中的重复逻辑
 */

import type { OrderInfo } from '../api/order';

/**
 * 获取订单状态文本
 */
export const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '待支付',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

/**
 * 判断订单是否可以申请退款
 * - 只有已完成的订单可以退款
 * - 订单完成时间不能超过7天
 * - 累计退款金额小于实付金额（未全额退款）
 */
export const canRefund = (order: OrderInfo): boolean => {
  if (order.status !== 1) {
    return false;
  }

  // 累计退款已达实付金额，不允许继续退款
  const paidAmount = order.paidAmount || order.totalAmount || 0;
  const refundedAmount = order.refundAmount || 0;
  if (refundedAmount >= paidAmount) {
    return false;
  }

  if (order.payTime) {
    const payTime = new Date(order.payTime);
    const now = new Date();
    const diffTime = now.getTime() - payTime.getTime();
    const diffDays = diffTime / (1000 * 60 * 60 * 24);

    if (diffDays > 7) {
      return false;
    }
  }

  return true;
};

/**
 * 判断订单是否超过退款期限（7天）
 */
export const isRefundExpired = (order: OrderInfo): boolean => {
  if (order.status !== 1 || !order.payTime) {
    return false;
  }
  
  const payTime = new Date(order.payTime);
  const now = new Date();
  const diffTime = now.getTime() - payTime.getTime();
  const diffDays = diffTime / (1000 * 60 * 60 * 24);
  
  return diffDays > 7;
};

/**
 * 获取退款期限提示文本
 */
export const getRefundExpireText = (order: OrderInfo): string => {
  if (!order.payTime) return '';
  
  const payTime = new Date(order.payTime);
  const now = new Date();
  const diffTime = now.getTime() - payTime.getTime();
  const diffDays = diffTime / (1000 * 60 * 60 * 24);
  
  if (diffDays > 7) {
    return '已超过退款期限（7天）';
  } else {
    const remainingDays = Math.ceil(7 - diffDays);
    return `剩余 ${remainingDays} 天可申请退款`;
  }
};
