import request, { ErrorType, RequestError } 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',
    { ids: data.filter(Boolean) }
  );
  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 interface OrderPrepayRequest {
  orderId: number;
  payType: number;
}

export async function prepayShopOrder(data: OrderPrepayRequest) {
  const urls = [
    '/shop/shop-order/pay',
    '/shop/shop-order/prepay',
    '/shop/shop-order/repay'
  ];

  let lastError: unknown;
  let businessError: unknown;
  for (const url of urls) {
    try {
      const res = await request.post<ApiResult<WxPayResult>>(url, data, { showError: false });
      // request.ts 在 code!=0 时会直接 throw；走到这里通常都是 code===0
      if (res.code === 0) return res.data;
    } catch (e) {
      // 若已命中"业务错误"（例如订单已取消/已支付），优先保留该错误用于向上提示；
      // 不要被后续的 404/网络错误覆盖掉，避免调用方误判为"不支持该接口"而降级走创建订单。
      if (!businessError && e instanceof RequestError && e.type === ErrorType.BUSINESS_ERROR) {
        businessError = e;
      } else {
        lastError = e;
      }
    }
  }

  return Promise.reject(businessError || lastError || new Error('发起支付失败'));
}

/**
 * 创建订单
 */
export async function createOrder(data: OrderCreateRequest) {
  // Java 后端期望 camelCase 字段，直接传
  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));
}


/**
 * 申请|同意退款
 */
export async function refundShopOrder(data: ShopOrder) {
  const res = await request.put<ApiResult<unknown>>(
    '/shop/shop-order/refund',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
