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

/**
 * 分页查询产品
 */
export async function pageProduct(params: ProductParam) {
  const res = await request.get<ApiResult<PageResult<Product>>>(
    '/oa/product/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询产品列表
 */
export async function listProduct(params?: ProductParam) {
  const res = await request.get<ApiResult<Product[]>>('/oa/product', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加产品
 */
export async function addProduct(data: Product) {
  const res = await request.post<ApiResult<unknown>>('/oa/product', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改产品
 */
export async function updateProduct(data: Product) {
  const res = await request.put<ApiResult<unknown>>('/oa/product', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除产品
 */
export async function removeProduct(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/oa/product/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

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

/**
 * 修改用户状态
 */
export async function updateProductStatus(productId?: number, status?: number) {
  const res = await request.put<ApiResult<unknown>>('/oa/product/status', {
    productId,
    status
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询产品
 */
export async function getProduct(id: number) {
  const res = await request.get<ApiResult<Product>>('/oa/product/' + id);
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  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>>('/oa/product/existence', {
    params: { field, value, id }
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
