import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Assets, AssetsParam } from './model';
import { MODULES_API_URL } from '@/config/setting';

export async function getCount() {
  const res = await request.get(MODULES_API_URL + '/oa/assets/data');
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 分页查询资产
 */
export async function pageAssets(params: AssetsParam) {
  const res = await request.get<ApiResult<PageResult<Assets>>>(
    MODULES_API_URL + '/oa/assets/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询资产列表
 */
export async function listAssets(params?: AssetsParam) {
  const res = await request.get<ApiResult<Assets[]>>(
    MODULES_API_URL + '/oa/assets',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询服务器
 */
export async function getAssets(id: number) {
  const res = await request.get<ApiResult<Assets>>(
    MODULES_API_URL + '/oa/assets/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加资产
 */
export async function addAssets(data: Assets) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/assets',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改资产
 */
export async function updateAssets(data: Assets) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/assets',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

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

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