/**
 * 订单相关API
 */

import { post } from '../utils/request';
import { API_PATHS } from '../utils/config';

/**
 * 订单商品信息
 */
export interface OrderProduct {
  id: string;
  name: string;
  price: number;
  quantity: number; // 购买数量
  refundedQuantity?: number; // 已退款数量
  refundQuantity?: number; // 退款数量（用户选择）
  image?: string;
  subtotal?: number;
}

/**
 * 订单信息
 */
export interface OrderInfo {
  id: string;
  orderNo: string;
  orderName?: string; // 订单名称
  outTradeNo: string;
  hahaOrderNo: string;
  deviceId: string;
  
  /** 订单总金额（原价） */
  totalAmount: number;
  
  /** 订单优惠金额（营销活动优惠 + 优惠券优惠） */
  discountAmount?: number;
  
  /** 实付总金额 = totalAmount - discountAmount */
  paidAmount?: number;
  
  payStatus: string;
  payChannel?: string; // 支付渠道：wechat/alipay/balance/wechat_payscore
  payScoreOrderId?: string; // 微信支付分服务订单号
  payScoreValue?: number; // 微信支付分分数值
  refundStatus?: string; // 退款状态
  refundAmount?: number; // 累计退款金额
  currentRefundId?: string; // 当前退款记录ID
  status: number;
  statusText?: string;
  createTime: string;
  payTime?: string;
  storeName?: string; // 门店名称
  videoUrl?: string;
  confidence?: number;
  products: OrderProduct[];
  refunds?: RefundRecord[]; // 退款记录列表
}

/** 退款记录 */
export interface RefundRecord {
  id: string;
  refundNo: string;
  refundAmount: number;
  status: string; // PENDING / REFUNDED / REJECTED
  reason: string;
  remark?: string; // 审核备注（拒绝原因）
  createTime: string;
  reviewTime?: string;
  items?: RefundRecordItem[];
}

/** 退款商品明细 */
export interface RefundRecordItem {
  productName: string;
  quantity: number;
  price: number;
  refundAmount: number;
}

/**
 * 订单列表请求参数
 */
export interface OrderListRequest {
  status?: number; // 0-待支付，1-已完成，2-已取消
}

/**
 * 订单详情请求参数
 */
export interface OrderDetailRequest {
  orderId?: string;
  orderNo?: string;
  outTradeNo?: string;
}

/**
 * 取消订单请求参数
 */
export interface CancelOrderRequest {
  orderId: string;
}

/**
 * 获取订单列表
 * @param params 查询参数
 */
export const getOrderList = (params?: OrderListRequest): Promise<OrderInfo[]> => {
  return post<OrderInfo[]>(API_PATHS.getOrders, params || {});
};

/**
 * 获取订单详情
 * @param params 查询参数（必须包含orderId、orderNo或outTradeNo之一）
 */
export const getOrderDetail = (params: OrderDetailRequest): Promise<OrderInfo> => {
  return post<OrderInfo>(API_PATHS.getOrderDetail, params);
};

/**
 * 取消订单
 * @param orderId 订单ID
 */
export const cancelOrder = (orderId: string): Promise<void> => {
  return post<void>(API_PATHS.cancelOrder, { orderId });
};
