import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
// @ts-ignore
import type { HualalaCard, HualalaCardParam } from './model';
/**
 * 分页查询会员卡
 */
export async function pageHualalaCard(params: HualalaCardParam) {
  const res = await request.get<ApiResult<PageResult<HualalaCard>>>(
    '/apps/hualala-card/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询会员卡列表
 */
export async function listHualalaCard(params?: HualalaCardParam) {
  const res = await request.get<ApiResult<HualalaCard[]>>(
    '/apps/hualala-card',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加会员卡
 */
export async function addHualalaCard(data: HualalaCard) {
  const merchantCode = localStorage.getItem('merchantCode');
  if (merchantCode !== 'null') {
    data.merchantCode = String(merchantCode);
  }
  const res = await request.post<ApiResult<unknown>>(
    '/apps/hualala-card',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改会员卡
 */
export async function updateHualalaCard(data: HualalaCard) {
  const res = await request.put<ApiResult<unknown>>('/apps/hualala-card', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除会员卡
 */
export async function removeHualalaCard(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    '/apps/hualala-card/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除会员卡
 */
export async function removeBatchHualalaCard(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    '/apps/hualala-card/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>>(
    '/apps/hualala-card/existence',
    {
      params: { field, value, id }
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
