import { post, get, put } from '@/utils/request';

export function createOrder(data: {
  roomId: number;
  checkInDate: string;
  checkOutDate: string;
  contactName: string;
  contactPhone: string;
  roomCount?: number;
  guestCount?: number;
  contactIdCard?: string;
  couponId?: number;
  remark?: string;
  paymentMethod?: string;
}) {
  return post('/api/app/orders', data);
}

export function getOrderList(params: { page?: number; pageSize?: number; status?: string }) {
  return get('/api/app/orders', params);
}

export function getOrderDetail(orderNo: string) {
  return get(`/api/app/orders/${orderNo}`);
}

export function cancelOrder(orderNo: string, reason: string) {
  return put(`/api/app/orders/${orderNo}/cancel`, { reason });
}

export function refundOrder(orderNo: string, reason: string) {
  return put(`/api/app/orders/${orderNo}/refund`, { reason });
}

export function payOrder(orderNo: string, paymentMethod: 'wechat' | 'alipay' | 'balance' = 'wechat') {
  return post('/api/app/orders/pay', { orderNo, paymentMethod });
}

/**
 * 调用微信支付
 */
export async function wxPay(orderNo: string) {
  try {
    // 1. 调用后端接口获取支付参数
    const res = await payOrder(orderNo, 'wechat');

    if (!res.data || !res.data.payParams) {
      throw new Error('获取支付参数失败');
    }

    const { payParams } = res.data;

    // 2. 调用微信支付
    return new Promise((resolve, reject) => {
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType || 'RSA',
        paySign: payParams.paySign,
        success: (res) => {
          console.log('支付成功', res);
          resolve(res);
        },
        fail: (err) => {
          console.error('支付失败', err);
          if (err.errMsg === 'requestPayment:fail cancel') {
            reject(new Error('用户取消支付'));
          } else {
            reject(new Error(err.errMsg || '支付失败'));
          }
        },
      });
    });
  } catch (error) {
    console.error('发起支付失败', error);
    throw error;
  }
}
