import request from '@/utils/request';
import { withCreditUserScope } from '@/api/credit/utils/data-scope';
import type { ApiResult, PageResult } from '@/api/index';
import type { CreditMpCustomer, CreditMpCustomerParam } from './model';

/**
 * 分页查询小程序端客户
 */
export async function pageCreditMpCustomer(params: CreditMpCustomerParam) {
  const res = await request.get<ApiResult<PageResult<CreditMpCustomer>>>(
    '/credit/credit-mp-customer/page',
    withCreditUserScope(params)
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询小程序端客户列表
 */
export async function listCreditMpCustomer(params?: CreditMpCustomerParam) {
  const res = await request.get<ApiResult<CreditMpCustomer[]>>(
    '/credit/credit-mp-customer',
    withCreditUserScope(params)
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加小程序端客户
 */
export async function addCreditMpCustomer(data: CreditMpCustomer) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-mp-customer',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改小程序端客户
 */
export async function updateCreditMpCustomer(data: CreditMpCustomer) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-mp-customer',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除小程序端客户
 */
export async function removeCreditMpCustomer(id?: number) {
  if (id == null) {
    return Promise.reject(new Error('缺少id'));
  }
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-mp-customer/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除小程序端客户
 */
export async function removeBatchCreditMpCustomer(data: (number | undefined)[]) {
  const ids = (data || []).filter((v): v is number => typeof v === 'number');
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-mp-customer/batch',
    ids
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询小程序端客户
 */
export async function getCreditMpCustomer(id: number) {
  const res = await request.get<ApiResult<CreditMpCustomer>>(
    '/credit/credit-mp-customer/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}
