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

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

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

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

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

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

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