import api from './api';
import request, { post } from '@/utils/request';
import type { AxiosRequestConfig } from 'axios';
import type {
  IFetchKnowledgeListRequestBody,
  IFetchKnowledgeListRequestParams,
  IFetchDocumentListRequestBody,
  ITestRetrievalRequestBody,
  IFetchChunkListRequestBody,
} from '@/interfaces/request/knowledge';
import type {
  IKnowledge,
  IKnowledgeFile,
  IChunk,
  IRenameTag,
  IParserConfig,
  IKnowledgeFileParserConfig,
} from '@/interfaces/database/knowledge';
import type { GridRowSelectionModel } from '@mui/x-data-grid';
import type { IRunDocumentRequestBody } from '@/interfaces/request/document';

// 知识库相关API服务
const knowledgeService = {
  // ===== 知识库管理 =====

  // 获取知识库列表
  getKnowledgeList: (
    params?: IFetchKnowledgeListRequestParams,
    body?: IFetchKnowledgeListRequestBody
  ) => {
    return request.post(api.kb_list, body || {}, { params });
  },

  // 创建知识库
  createKnowledge: (data: Partial<IKnowledge>) => {
    return post(api.create_kb, data);
  },

  // 更新知识库
  updateKnowledge: (data: Partial<IKnowledge>) => {
    return post(api.update_kb, data);
  },

  // 删除知识库
  removeKnowledge: (data: { kb_id: string }) => {
    return post(api.rm_kb, data);
  },

  // 获取知识库详情
  getKnowledgeDetail: (params: { kb_id: string }) => {
    return request.get(api.get_kb_detail, { params });
  },

  // 获取知识库基本信息
  getKnowledgeBasicInfo: (params: { kb_id: string }) => {
    return request.get(api.getKnowledgeBasicInfo, { params });
  },

  // 获取知识库元数据
  getKnowledgeMeta: (params: { kb_id: string }) => {
    return request.get(api.getMeta, { params });
  },

  // ===== 文档管理 =====

  // 获取文档列表
  getDocumentList: (
    params?: IFetchKnowledgeListRequestParams,
    body?: IFetchDocumentListRequestBody
  ) => {
    return request.post(api.get_document_list, body || {}, { params });
  },

  // 创建文档
  createDocument: (data: any) => {
    return post(api.document_create, data);
  },

  // 上传文档
  uploadDocument: (data: FormData) => {
    // 设置请求头为 multipart/form-data
    const headers = {
      'Content-Type': 'multipart/form-data',
    };
    return post(api.document_upload, data, { headers });
  },

  // 上传并解析文档
  uploadAndParseDocument: (data: FormData) => {
    // 设置请求头为 multipart/form-data
    const headers = {
      'Content-Type': 'multipart/form-data',
    };
    return post(api.upload_and_parse, data, { headers });
  },

  // 解析文档
  parseDocument: (data: any) => {
    return post(api.parse, data);
  },

  // 重命名文档
  renameDocument: (data: { doc_id: string; name: string }) => {
    return post(api.document_rename, data);
  },

  // 删除文档
  removeDocument: (data: { doc_id: string | Array<string | number> }) => {
    return post(api.document_rm, data);
  },

  // 删除文档（DELETE方法）
  deleteDocument: (doc_id: string) => {
    return request.delete(`${api.document_delete}/${doc_id}`);
  },

  /**
   * 更改文档状态
   * @param data 文档ID列表和状态 status 0 禁用 1 启用
   */
  changeDocumentStatus: (data: { doc_ids: Array<string | number>; status: string | number }) => {
    return post(api.document_change_status, data);
  },

  // 运行文档处理
  runDocument: (data: IRunDocumentRequestBody) => {
    return post(api.document_run, data);
  },

  // 更改文档解析器配置
  changeDocumentParser: (data: { doc_id: string; parser_config: IKnowledgeFileParserConfig }) => {
    return post(api.document_change_parser, data);
  },

  // 获取文档缩略图
  getDocumentThumbnails: (params: { doc_id: string }) => {
    return request.get(api.document_thumbnails, { params });
  },

  // 获取文档文件
  getDocumentFile: (params: { doc_id: string }, config?: AxiosRequestConfig) => {
    return request.get(`${api.get_document_file}/${params.doc_id}`, {
      responseType: 'blob',
      ...config
    });
  },

  // 获取文档信息
  getDocumentInfos: (data: { doc_ids: string | Array<string | number> }) => {
    return post(api.document_infos, data);
  },

  // 设置文档元数据
  setDocumentMeta: (data: any) => {
    return post(api.setMeta, data);
  },

  // 网页爬取
  webCrawl: (data: { url: string; kb_id: string }) => {
    return post(api.web_crawl, data);
  },

  // 获取文档过滤器
  getDocumentFilter: (data: { kb_id: string }) => {
    return post(api.get_dataset_filter, data);
  },

  // ===== 分块管理 =====

  // 获取分块列表
  getChunkList: (data: IFetchChunkListRequestBody) => {
    return post(api.chunk_list, data);
  },

  // 创建分块
  createChunk: (data: Partial<IChunk>) => {
    return post(api.create_chunk, data);
  },

  // 更新分块
  updateChunk: (data: Partial<IChunk>) => {
    return post(api.set_chunk, data);
  },

  // 获取分块详情
  getChunk: (params: { chunk_id: string }) => {
    return request.get(api.get_chunk, { params });
  },

  // 切换分块状态 available_int 是否启用，0：未启用，1：启用
  switchChunk: (data: { chunk_ids: string[]; available_int: number, doc_id: string }) => {
    return post(api.switch_chunk, data);
  },

  // 删除分块
  removeChunk: (data: { chunk_ids: string[] }) => {
    return post(api.rm_chunk, data);
  },

  // ===== 检索测试 =====

  // 检索测试
  retrievalTest: (data: ITestRetrievalRequestBody) => {
    return post(api.retrieval_test, data);
  },

  // 外部检索测试
  retrievalTestShare: (data: ITestRetrievalRequestBody) => {
    return post(api.retrievalTestShare, data);
  },

  // ===== 知识图谱 =====

  // 获取知识图谱
  getKnowledgeGraph: (knowledgeId: string) => {
    return request.get(api.getKnowledgeGraph(knowledgeId));
  },

  // 删除知识图谱
  deleteKnowledgeGraph: (knowledgeId: string) => {
    return request.delete(api.getKnowledgeGraph(knowledgeId));
  },

  // 获取分块知识图谱
  getChunkKnowledgeGraph: (params: { chunk_id: string }) => {
    return request.get(api.knowledge_graph, { params });
  },

  // ===== 标签管理 =====

  // 获取标签列表
  getTagList: (knowledgeId: string) => {
    return request.get(api.listTag(knowledgeId));
  },

  // 根据知识库ID获取标签
  getTagsByKnowledgeIds: (params: { kb_ids: string[] }) => {
    return request.get(api.listTagByKnowledgeIds, { params });
  },

  // 删除标签
  removeTag: (knowledgeId: string, tags: string[]) => {
    return post(api.removeTag(knowledgeId), { tags });
  },

  // 重命名标签
  renameTag: (knowledgeId: string, { fromTag, toTag }: IRenameTag) => {
    return post(api.renameTag(knowledgeId), { fromTag, toTag });
  },

  // ===== 数据管道 =====

  // 获取数据管道日志
  getDataPipelineLogs: (
    params?: IFetchKnowledgeListRequestParams,
    body?: IFetchDocumentListRequestBody
  ) => {
    return request.post(api.fetchDataPipelineLogs, body || {}, { params });
  },

  // 获取管道详情
  getPipelineDetail: (params: { task_id: string }) => {
    return request.get(api.get_pipeline_detail, { params });
  },

  // 获取管道数据集日志
  getPipelineDatasetLogs: (
    params?: IFetchKnowledgeListRequestParams,
    body?: IFetchDocumentListRequestBody
  ) => {
    return request.post(api.fetchPipelineDatasetLogs, body || {}, { params });
  },

  // 运行GraphRAG
  runGraphRag: (data: { kb_id: string }) => {
    return post(api.runGraphRag, data);
  },

  // 跟踪GraphRAG
  traceGraphRag: (params: { kb_id: string }) => {
    return request.get(api.traceGraphRag, { params });
  },

  // 运行Raptor
  runRaptor: (data: { kb_id: string }) => {
    return post(api.runRaptor, data);
  },

  // 跟踪Raptor
  traceRaptor: (params: { kb_id: string }) => {
    return request.get(api.traceRaptor, { params });
  },

  // 解绑管道任务
  unbindPipelineTask: (params: { kb_id: string; type: string }) => {
    return request.delete(api.unbindPipelineTask(params));
  },

  // 重新运行管道
  pipelineRerun: (data: any) => {
    return post(api.pipelineRerun, data);
  },
};

export default knowledgeService;