import { api } from '@/api/index'
import type { ResultDomain, PageRequest } from '@/types'
import type { TbKnowledge, TbKnowledgeFile, KnowledgeFileVO, SegmentRequestBody, DocumentStatusRequestBody } from '@/types/ai'

/**
 * @description    AI知识库相关接口
 * @filename    aiKnowledge.ts
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
export const aiKnowledgeAPI = {
    baseUrl: '/urban-lifeline/ai/knowledge',

    // ====================== 知识库管理 ======================

    /**
     * 创建知识库
     * @param knowledge 知识库信息
     */
    async createKnowledge(knowledge: TbKnowledge): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.post<TbKnowledge>(`${this.baseUrl}`, knowledge)
        return response.data
    },

    /**
     * 更新知识库
     * @param knowledge 知识库信息
     */
    async updateKnowledge(knowledge: TbKnowledge): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.put<TbKnowledge>(`${this.baseUrl}`, knowledge)
        return response.data
    },

    /**
     * 删除知识库
     * @param knowledgeId 知识库ID
     */
    async deleteKnowledge(knowledgeId: string): Promise<ResultDomain<boolean>> {
        const response = await api.delete<boolean>(`${this.baseUrl}/${knowledgeId}`)
        return response.data
    },

    /**
     * 获取知识库详情
     * @param knowledgeId 知识库ID
     */
    async getKnowledge(knowledgeId: string): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.get<TbKnowledge>(`${this.baseUrl}/${knowledgeId}`)
        return response.data
    },

    /**
     * 查询知识库列表
     * @param filter 筛选条件
     */
    async listKnowledges(filter?: TbKnowledge): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.post<TbKnowledge>(`${this.baseUrl}/list`, filter || {})
        return response.data
    },

    /**
     * 分页查询知识库
     * @param pageRequest 分页请求
     */
    async pageKnowledges(pageRequest: PageRequest<TbKnowledge>): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.post<TbKnowledge>(`${this.baseUrl}/page`, pageRequest)
        return response.data
    },

    /**
     * 获取知识库统计信息
     * @param knowledgeId 知识库ID
     */
    async getKnowledgeStats(knowledgeId: string): Promise<ResultDomain<TbKnowledge>> {
        const response = await api.get<TbKnowledge>(`${this.baseUrl}/${knowledgeId}/stats`)
        return response.data
    },

    // ====================== 文件管理 ======================

    /**
     * 获取知识库文档列表（查询本地数据库文件）
     * @param knowledgeId 知识库ID
     * @param page 页码
     * @param pageSize 每页条数
     */
    async getDocumentList(knowledgeId: string, page = 1, pageSize = 20): Promise<ResultDomain<any>> {
        const response = await api.post<any>(`${this.baseUrl}/${knowledgeId}/documents`, {
            filter: { knowledgeId },
            pageParam: {
                page,
                pageSize,
                total: 0
            }
        })
        return response.data
    },

    /**
     * 上传文件到知识库
     * @param file 文件
     * @param knowledgeId 知识库ID
     * @param indexingTechnique 索引方式
     */
    async uploadToKnowledge(
        file: File,
        knowledgeId: string,
        indexingTechnique?: string
    ): Promise<ResultDomain<TbKnowledgeFile>> {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('knowledgeId', knowledgeId)
        if (indexingTechnique) {
            formData.append('indexingTechnique', indexingTechnique)
        }
        const response = await api.upload<TbKnowledgeFile>(`${this.baseUrl}/file/upload`, formData)
        return response.data
    },

    /**
     * 批量上传文件到知识库
     * @param files 文件数组
     * @param knowledgeId 知识库ID
     * @param indexingTechnique 索引方式
     */
    async batchUploadToKnowledge(
        files: File[],
        knowledgeId: string,
        indexingTechnique?: string
    ): Promise<ResultDomain<TbKnowledgeFile>> {
        const formData = new FormData()
        files.forEach(file => formData.append('files', file))
        formData.append('knowledgeId', knowledgeId)
        if (indexingTechnique) {
            formData.append('indexingTechnique', indexingTechnique)
        }
        const response = await api.upload<TbKnowledgeFile>(`${this.baseUrl}/file/batch-upload`, formData)
        return response.data
    },

    /**
     * 更新知识库文件（上传新版本）
     * @param file 文件
     * @param knowledgeId 知识库ID
     * @param fileRootId 文件根ID
     */
    async updateFile(
        file: File,
        knowledgeId: string,
        fileRootId: string
    ): Promise<ResultDomain<TbKnowledgeFile>> {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('knowledgeId', knowledgeId)
        formData.append('fileRootId', fileRootId)
        const response = await api.uploadPut<TbKnowledgeFile>(`${this.baseUrl}/file/upload`, formData)
        return response.data
    },

    /**
     * 删除知识库文件
     * @param fileId 文件ID
     */
    async deleteFile(fileRootId: string): Promise<ResultDomain<boolean>> {
        const response = await api.delete<boolean>(`${this.baseUrl}/file/${fileRootId}`)
        return response.data
    },

    /**
     * 获取文件历史版本
     * @param fileRootId 文件根ID
     */
    async getFileHistory(fileRootId: string): Promise<ResultDomain<KnowledgeFileVO[]>> {
        const response = await api.get<KnowledgeFileVO[]>(`${this.baseUrl}/file/${fileRootId}/history`)
        return response.data
    },

    // ====================== 文档分段管理 ======================

    /**
     * 获取文档分段列表
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     */
    async getDocumentSegments(datasetId: string, documentId: string): Promise<ResultDomain<Record<string, any>>> {
        const response = await api.get<Record<string, any>>(
            `${this.baseUrl}/datasets/${datasetId}/documents/${documentId}/segments`
        )
        return response.data
    },

    /**
     * 创建文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param requestBody 分段内容
     */
    async createSegment(
        datasetId: string,
        documentId: string,
        requestBody: SegmentRequestBody
    ): Promise<ResultDomain<string>> {
        const response = await api.post<string>(
            `${this.baseUrl}/datasets/${datasetId}/documents/${documentId}/segments`,
            requestBody
        )
        return response.data
    },

    /**
     * 更新文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @param requestBody 分段内容
     */
    async updateSegment(
        datasetId: string,
        documentId: string,
        segmentId: string,
        requestBody: SegmentRequestBody
    ): Promise<ResultDomain<string>> {
        const response = await api.patch<string>(
            `${this.baseUrl}/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}`,
            requestBody
        )
        return response.data
    },

    /**
     * 删除文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     */
    async deleteSegment(
        datasetId: string,
        documentId: string,
        segmentId: string
    ): Promise<ResultDomain<string>> {
        const response = await api.delete<string>(
            `${this.baseUrl}/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}`
        )
        return response.data
    },

    // ====================== 文档状态管理 ======================

    /**
     * 更新文档状态（启用/禁用/归档）
     * @param datasetId Dify数据集ID
     * @param action 操作类型: enable/disable/archive/un_archive
     * @param requestBody 请求体
     */
    async updateDocumentStatus(
        datasetId: string,
        action: 'enable' | 'disable' | 'archive' | 'un_archive',
        requestBody: DocumentStatusRequestBody
    ): Promise<ResultDomain<string>> {
        const response = await api.patch<string>(
            `${this.baseUrl}/datasets/${datasetId}/documents/${action}/status`,
            requestBody
        )
        return response.data
    }
}