import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { FileInfoVO, FileInfoForm, FileInfoQuery, TableDataInfo } from './types';

/**
 * 查询文件信息列表
 * @param query 查询参数
 * @returns Promise<TableDataInfo<FileInfoVO>>
 */
export const listFileInfo = (query?: FileInfoQuery): AxiosPromise<TableDataInfo<FileInfoVO>> => {
  // 移除空值
  const cleanQuery: Record<string, any> = {};
  if (query) {
    Object.keys(query).forEach((key) => {
      if (query[key as keyof FileInfoQuery] !== undefined && query[key as keyof FileInfoQuery] !== null && query[key as keyof FileInfoQuery] !== '') {
        cleanQuery[key] = query[key as keyof FileInfoQuery];
      }
    });
  }

  return request({
    url: '/resource/file/info/list',
    method: 'get',
    params: cleanQuery
  });
};

/**
 * 查询文件信息详细
 * @param id 文件ID
 * @returns Promise<FileInfoVO>
 */
export const getFileInfo = (id: number): AxiosPromise<FileInfoVO> => {
  return request({
    url: `/resource/file/info/${id}`,
    method: 'get'
  });
};

/**
 * 新增文件信息
 * @param data 文件数据
 * @returns Promise<any>
 */
export const addFileInfo = (data: FileInfoForm): AxiosPromise<any> => {
  return request({
    url: '/resource/file/info',
    method: 'post',
    data: data
  });
};

/**
 * 修改文件信息
 * @param data 文件数据
 * @returns Promise<any>
 */
export const updateFileInfo = (data: FileInfoForm): AxiosPromise<any> => {
  return request({
    url: '/resource/file/info',
    method: 'put',
    data: data
  });
};

/**
 * 删除文件信息
 * @param id 文件ID
 * @returns Promise<any>
 */
export const delFileInfo = (id: number | number[]): AxiosPromise<any> => {
  const ids = Array.isArray(id) ? id.join(',') : id;
  return request({
    url: `/resource/file/info/${ids}`,
    method: 'delete'
  });
};

/**
 * 根据分类ID查询文件列表
 * @param categoryId 分类ID
 * @returns Promise<FileInfoVO[]>
 */
export const listFileInfoByCategory = (categoryId: number): AxiosPromise<FileInfoVO[]> => {
  return request({
    url: `/resource/file/info/category/${categoryId}`,
    method: 'get'
  });
};

/**
 * 根据文件类型查询文件列表
 * @param type 文件类型
 * @returns Promise<FileInfoVO[]>
 */
export const listFileInfoByType = (type: string): AxiosPromise<FileInfoVO[]> => {
  return request({
    url: `/resource/file/info/type/${type}`,
    method: 'get'
  });
};

/**
 * 更新文件下载次数
 * @param id 文件ID
 * @returns Promise<any>
 */
export const updateDownloadCount = (id: number): AxiosPromise<any> => {
  return request({
    url: `/resource/file/info/download/${id}`,
    method: 'put'
  });
};

/**
 * 更新文件查看次数
 * @param id 文件ID
 * @returns Promise<any>
 */
export const updateViewCount = (id: number): AxiosPromise<any> => {
  return request({
    url: `/resource/file/info/view/${id}`,
    method: 'put'
  });
};
