import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Payment, PaymentParam } from './model';

/**
 * 分页查询商户
 */
export async function pagePayment(params: PaymentParam) {
  const res = await request.get<ApiResult<PageResult<Payment>>>(
    '/shop/payment/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询商户列表
 */
export async function listPayment(params?: PaymentParam) {
  const res = await request.get<ApiResult<Payment[]>>('/shop/payment', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加商户
 */
export async function addPayment(data: Payment) {
  const res = await request.post<ApiResult<unknown>>('/shop/payment', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改商户
 */
export async function updatePayment(data: Payment) {
  const res = await request.put<ApiResult<unknown>>('/shop/payment', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除商户
 */
export async function removePayment(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/shop/payment/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

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

/**
 * 检查IP是否存在
 */
export async function checkExistence(
  field: string,
  value: string,
  id?: number
) {
  const res = await request.get<ApiResult<unknown>>('/shop/payment/existence', {
    params: { field, value, id }
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 拉起支付
 */
export async function alipay(data: PaymentParam) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/payment/alipay',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询商户列表
 */
export async function alipayQuery(orderId) {
  const res = await request.get<ApiResult<unknown>>(
    '/shop/payment/mp-alipay/query/' + orderId
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}
