import { request } from '@/utils/request'
import type { PageParams, PageResult } from '@/types/api'

/**
 * 订单管理（管理端）
 *
 * 后端契约：com.snack.server.module.order.controller.OrderAdminController
 *   GET    /api/admin/order/page              → Page<OrderDetailVO>
 *   GET    /api/admin/order/{id}              → OrderDetailVO
 *   POST   /api/admin/order/{id}/deliver?company=&trackingNo= → Void
 *   POST   /api/admin/order/{id}/cancel?reason=             → Void
 */

/** 订单详情（与后端 OrderDetailVO 一一对应） */
export interface OrderDetail {
  id: number
  orderNo: string
  userId: number
  username?: string
  totalAmount: number
  freightAmount: number
  discountAmount: number
  couponAmount: number
  payAmount: number
  status: 0 | 1 | 2 | 3 | 4
  statusText: string
  statusTagType: string
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  remark?: string
  trackingCompany?: string
  trackingNo?: string
  payTime?: string
  deliverTime?: string
  receiveTime?: string
  cancelTime?: string
  createTime: string
  payChannel?: string
  payChannelText?: string
  payTradeNo?: string
  refundTradeNo?: string
  refundTime?: string
  refundReason?: string
  items: OrderItem[]
  totalQuantity: number
}

export interface OrderItem {
  id: number
  productId: number
  productName: string
  productImage: string
  skuId: number
  skuName: string
  price: number
  quantity: number
  totalAmount: number
}

export interface OrderPageQuery extends PageParams {
  status?: 0 | 1 | 2 | 3 | 4
  keyword?: string
  username?: string
}

export function getOrderPageApi(params: OrderPageQuery) {
  return request<PageResult<OrderDetail>>({
    url: '/api/admin/order/page',
    method: 'GET',
    params
  })
}

export function getOrderDetailApi(id: number) {
  return request<OrderDetail>({
    url: `/api/admin/order/${id}`,
    method: 'GET'
  })
}

export function deliverOrderApi(id: number, data: { company: string; trackingNo: string }) {
  return request<void>({
    url: `/api/admin/order/${id}/deliver`,
    method: 'POST',
    params: data
  })
}

export function cancelOrderApi(id: number, reason?: string) {
  return request<void>({
    url: `/api/admin/order/${id}/cancel`,
    method: 'POST',
    params: { reason }
  })
}
