import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { ShopOrder, ShopOrderParam, OrderCreateRequest } from './model';

/**
 * 分页查询订单
 */
export async function pageShopOrder(params: ShopOrderParam) {
  const res = await request.get<ApiResult<PageResult<ShopOrder>>>(
    '/shop/shop-order/page',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询订单列表
 */
export async function listShopOrder(params?: ShopOrderParam) {
  const res = await request.get<ApiResult<ShopOrder[]>>(
    '/shop/shop-order',
    params
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加订单
 */
export async function addShopOrder(data: ShopOrder) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-order',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改订单
 */
export async function updateShopOrder(data: ShopOrder) {
  const res = await request.put<ApiResult<unknown>>(
    '/shop/shop-order',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除订单
 */
export async function removeShopOrder(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/shop/shop-order/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除订单
 */
export async function removeBatchShopOrder(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    '/shop/shop-order/batch',
    {
      data
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询订单
 */
export async function getShopOrder(id: number) {
  const res = await request.get<ApiResult<ShopOrder>>(
    '/shop/shop-order/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 微信支付返回数据
 */
export interface WxPayResult {
  prepayId: string;
  orderNo: string;
  timeStamp: string;
  nonceStr: string;
  package: string;
  signType: string;
  paySign: string;
}

/**
 * 创建订单
 */
export async function createOrder(data: OrderCreateRequest) {
  const res = await request.post<ApiResult<WxPayResult>>(
    '/shop/shop-order',
    data
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修复订单支付状态
 */
export async function repairOrder(data: ShopOrder) {
  const res = await request.put<ApiResult<unknown>>(
    '/shop/shop-order/repair',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
