package com.cy.guoyan.admin.module.ai.controller.admin.chatdocument;

import com.alibaba.fastjson.JSONObject;
import com.cy.guoyan.admin.module.ai.controller.admin.chatdocument.vo.ChatDocumentPageReqVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatdocument.vo.ChatDocumentRespVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatdocument.vo.ChatDocumentSaveReqVO;
import com.cy.guoyan.admin.module.ai.service.aiservice.AiSelectionService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import com.cy.guoyan.admin.framework.common.pojo.PageParam;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.pojo.CommonResult;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;
import static com.cy.guoyan.admin.framework.common.pojo.CommonResult.success;
import com.cy.guoyan.admin.framework.excel.core.util.ExcelUtils;
import com.cy.guoyan.admin.framework.apilog.core.annotation.ApiAccessLog;
import static com.cy.guoyan.admin.framework.apilog.core.enums.OperateTypeEnum.*;
import com.cy.guoyan.admin.module.ai.dal.dataobject.chatdocument.ChatDocumentDO;
import com.cy.guoyan.admin.module.ai.service.chatdocument.ChatDocumentService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 知识库文档")
@RestController
@RequestMapping("/chatAi/chat-document")
@Validated
public class ChatDocumentController {
    @Resource
    private ChatDocumentService chatDocumentService;

    @Resource
    private AiSelectionService delegatingDatasetService;
    
    @GetMapping(value = "/file")
    @Operation(summary = "查询知识库文档列表")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<JSONObject> listDocuments(
            String datasetId, String keyword, Integer page, Integer limit    ) throws IOException {
        JSONObject documentByFile = chatDocumentService.listDocuments(datasetId, keyword, page, limit);
        return success(documentByFile);
    }

    @GetMapping(value = "/status")
    @Operation(summary = "查询知识库文档状态")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<JSONObject> getDocumentIndexingStatus(
            @RequestParam(value = "datasetId") String datasetId,
            @RequestParam(value = "batch") String batch
    ) throws IOException {
        JSONObject documentByFile = chatDocumentService.getDocumentIndexingStatus(datasetId,batch);
        return success(documentByFile);
    }

    @DeleteMapping(value = "/file")
    @Operation(summary = "删除知识库文档")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<Boolean> deleteDocument(
            @RequestParam(value = "datasetId") String datasetId,
            @RequestParam(value = "documentId") String documentId
    ) throws IOException {
        chatDocumentService.deleteDocument(datasetId,documentId);
        return success(true);
    }



    @PostMapping(value = "/document/segments")
    @Operation(summary = "新增知识库文档分段")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<JSONObject> addDocumentSegments(
            String datasetId,
            String documentId
//            @RequestBody List<Map<String, Object>> segments
    ) throws IOException {
        JSONObject documentByFile = chatDocumentService.addDocumentSegments(datasetId,documentId,null);
        return success(documentByFile);
    }

//    @PutMapping(value = "/document/segments")
//    @Operation(summary = "更新知识库文档分段")
//    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
//    public CommonResult<JSONObject> updateDocumentSegment(
//            String datasetId,
//            String documentId,
//            String segmentId,
//            String content,
//            String answer,
//            List<String> keywords,
//            Boolean enabled
//    ) throws IOException {
//        JSONObject documentByFile = chatDocumentService.updateDocumentSegment(datasetId,documentId,segmentId,content,answer,keywords,enabled);
//        return success(documentByFile);
//    }

    @GetMapping(value = "/document/segments")
    @Operation(summary = "查询知识库文档分段")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<JSONObject> listDocumentSegments(
            String datasetId,
            String documentId,
//            String keyword,
            String status
    ) throws IOException {
        JSONObject documentByFile = chatDocumentService.listDocumentSegments(datasetId,documentId,null,status);
        return success(documentByFile);
    }

    @GetMapping(value = "/document")
    @Operation(summary = "获取上传文件")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<JSONObject> getUploadedFileInfo(
            String datasetId,
            String documentId
    ) throws IOException {
        JSONObject documentByFile = chatDocumentService.getUploadedFileInfo(datasetId,documentId);
        return success(documentByFile);
    }


    @DeleteMapping(value = "/document/segments")
    @Operation(summary = "删除知识库文档分段")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-knowledge-dataset:create')")
    public CommonResult<Boolean> deleteDocumentSegment(
            String datasetId,
            String documentId,
            String segmentId
    ) throws IOException {
        chatDocumentService.deleteDocumentSegment(datasetId,documentId,segmentId);
        return success(true);
    }
    
    

    @PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "创建知识库文档")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:create')")
    public CommonResult<JSONObject> createChatDocument(
            @RequestParam("dataJson") String dataJson,
            @RequestPart(value = "file", required = false) MultipartFile file) throws IOException {
        ChatDocumentSaveReqVO createReqVO = JSONObject.parseObject(dataJson, ChatDocumentSaveReqVO.class);
        JSONObject documentByFile = delegatingDatasetService.createDocumentByFile(file, createReqVO, null);
//        JSONObject result = chatDocumentService.createChatDocument(createReqVO, file);
//        return success(result);
        return success(documentByFile);
    }


    @PutMapping("/update")
    @Operation(summary = "更新知识库文档")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:update')")
    public CommonResult<Boolean> updateChatDocument(@Valid @RequestBody ChatDocumentSaveReqVO updateReqVO) {
        chatDocumentService.updateChatDocument(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除知识库文档")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:delete')")
    public CommonResult<Boolean> deleteChatDocument(@RequestParam("id") Long id) throws IOException {
        delegatingDatasetService.deleteDocument(null,String.valueOf(id));
//        chatDocumentService.deleteChatDocument(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得知识库文档")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:query')")
    public CommonResult<ChatDocumentRespVO> getChatDocument(@RequestParam("id") Long id) {
        ChatDocumentDO chatDocument = chatDocumentService.getChatDocument(id);
        return success(BeanUtils.toBean(chatDocument, ChatDocumentRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得知识库文档分页")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:query')")
    public CommonResult<PageResult<ChatDocumentRespVO>> getChatDocumentPage(@Valid ChatDocumentPageReqVO pageReqVO) {
        PageResult<ChatDocumentDO> pageResult = chatDocumentService.getChatDocumentPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChatDocumentRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出知识库文档 Excel")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-document:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportChatDocumentExcel(@Valid ChatDocumentPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ChatDocumentDO> list = chatDocumentService.getChatDocumentPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "知识库文档.xls", "数据", ChatDocumentRespVO.class,
                        BeanUtils.toBean(list, ChatDocumentRespVO.class));
    }
    
    
    
    
    
    

}