package com.storlead.knowledge.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.storlead.framework.common.result.Result;
import com.storlead.knowledge.config.DifyProperties;
import com.storlead.knowledge.pojo.dto.DocumentDTO;
import com.storlead.knowledge.pojo.dto.KnowledgeDTO;
import com.storlead.knowledge.utils.HttpService;
import com.storlead.knowledge.utils.JacksonHolder;
import com.storlead.knowledge.pojo.dto.QueryPageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;


@RestController
@RequestMapping("/knowledge/document/")
@Api(tags = "知识库: 知识库管理")
public class DocumentController {
    @Resource
    private HttpService httpService;

    @Resource
    private DifyProperties difyProperties;


    @GetMapping("{dataset_id}/documents")
    @ApiOperation("获取知识库文档")
    public Result<Object> listDocuments(@PathVariable String dataset_id , QueryPageDTO page) {
        String url = difyProperties.getBaseUrl() +"datasets/"+ dataset_id + "/documents";
        return httpService.get(
                url,
                page.getKeyword()==null?Map.of("page", page.getPageIndex(), "size", page.getPageSize()):Map.of("page", page.getPageIndex(), "size", page.getPageSize(), "keyword", page.getKeyword()),
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {}
        );
    }

    @GetMapping("{dataset_id}/documents/{document_id}")
    @ApiOperation("获取指定ID的知识库的指定文档")
    public Result<Object> getDocument(@PathVariable String dataset_id , @PathVariable String document_id) {
        String url = difyProperties.getBaseUrl() +"datasets/"+ dataset_id + "/documents/"+document_id;
        return httpService.get(
                url,
                null,
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {});
    }

    @DeleteMapping("{dataset_id}/documents/{document_id}")
    @ApiOperation("删除指定ID的文档")
    public Result<Object> deleteDocument(@PathVariable String dataset_id , @PathVariable String document_id) {
        String url = difyProperties.getBaseUrl() + "datasets/"+dataset_id + "/documents/"+document_id;
        return httpService.delete(
                url,
                null,
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {}) ;
    }

    @PostMapping("{dataset_id}/document/create_by_text")
    @ApiOperation("以文本创建文档")
    public Result<Object> createDocumentByText(@RequestBody DocumentDTO documentDTO, @PathVariable String dataset_id) throws JsonProcessingException {
        String url = difyProperties.getBaseUrl() + "datasets/"+dataset_id + "/document/create-by-text";
        String body = JacksonHolder.OBJECT_MAPPER.writeValueAsString(documentDTO);
        return httpService.post(url, null, "Bearer "+difyProperties.getDatasetApiKey(), body, new TypeReference<>() {});
    }

    @PostMapping("{dataset_id}/document/create_by_file")
    @ApiOperation("以文件创建文档")
    public Result<Object> createDocumentByFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("data") String data,
            @PathVariable String dataset_id
    ) {
        String url = difyProperties.getBaseUrl() +"datasets/"+ dataset_id + "/document/create-by-file";
        return httpService.uploadWithJson(
                url,
                file,
                data,
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {}
        );
    }

    @PostMapping("{dataset_id}/documents/{document_id}/update-by-text")
    @ApiOperation("以文本更新文档")
    public Result<Object> updateDocumentByText(
            @RequestBody KnowledgeDTO knowledgeDTO,
            @PathVariable String dataset_id,
            @PathVariable String document_id
    ) throws JsonProcessingException {
        String url = difyProperties.getBaseUrl() +"datasets/"+dataset_id + "/documents/"+document_id+"/update-by-text";
        String body = JacksonHolder.OBJECT_MAPPER.writeValueAsString(knowledgeDTO);
        return httpService.patch(url, null, "Bearer "+difyProperties.getDatasetApiKey(), body, new TypeReference<>() {});
    }



    @PostMapping("{dataset_id}/documents/{document_id}/update-by-file")
    @ApiOperation("以文件更新文档")
    public Result<Object> updateDocumentByFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("data") String data,  //格式 {"indexing_technique":"high_quality","doc_form":"text_model","doc_language":"English","process_rule":{"mode":"automatic"}}
            @PathVariable String dataset_id,
            @PathVariable String document_id
    ) {
        String url = difyProperties.getBaseUrl() + "datasets/"+dataset_id + "/documents/"+ document_id+"/create-by-file";
        return httpService.uploadWithJson(
                url,
                file,
                data,
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {}
        );
    }

    @GetMapping("{dataset_id}/documents/{batch}/indexing-status")
    @ApiOperation("查看刚上传文件的索引状态")
    public Result<Object> getIndexingStstus(
            @RequestParam("file") MultipartFile file,
            @RequestParam("data") String data,
            @PathVariable String dataset_id,
            @PathVariable String batch  //上传文件返回的batch
    ) {
        String url = difyProperties.getBaseUrl() + "datasets/"+dataset_id + "/documents/"+ batch+"/indexing-status";
        return httpService.uploadWithJson(
                url,
                file,
                data,
                "Bearer "+difyProperties.getDatasetApiKey(),
                new TypeReference<>() {}
        );
    }

}
