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

/**
 * 分页查询文档
 */
export async function pageDocsContent(params: DocsContentParam) {
  const res = await request.get<ApiResult<PageResult<DocsContent>>>(
    '/cms/docs-content/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询文档列表
 */
export async function listDocsContent(params?: DocsContentParam) {
  const res = await request.get<ApiResult<DocsContent[]>>('/cms/docs-content', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加文档
 */
export async function addDocsContent(data: DocsContent) {
  const res = await request.post<ApiResult<unknown>>('/cms/docs-content', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改文档
 */
export async function updateDocsContent(data: DocsContent) {
  const res = await request.put<ApiResult<unknown>>(
    '/cms/docs-content',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除文档
 */
export async function removeDocsContent(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    '/cms/docs-content/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除文档
 */
export async function removeBatchDocsContent(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    '/cms/docs-content/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

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

/**
 * 根据id查询文档
 */
export async function getDocsContent(id: number) {
  const res = await request.get<ApiResult<DocsContent>>(
    '/cms/docs-content/' + 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>>(
    '/cms/docs-content/existence',
    {
      params: { field, value, id }
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
