package com.easyproject.system.service.aiModel.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.coze.openapi.client.common.pagination.PageResp;
import com.coze.openapi.client.dataset.document.*;
import com.coze.openapi.client.dataset.document.model.DocumentBase;
import com.coze.openapi.client.dataset.document.model.DocumentChunkStrategy;
import com.coze.openapi.client.dataset.document.model.DocumentFormatType;
import com.coze.openapi.client.dataset.image.ListImageReq;
import com.coze.openapi.client.dataset.image.UpdateImageReq;
import com.coze.openapi.client.dataset.image.UpdateImageResp;
import com.coze.openapi.client.dataset.image.model.Image;
import com.coze.openapi.client.files.UploadFileReq;
import com.coze.openapi.client.files.UploadFileResp;
import com.coze.openapi.service.service.CozeAPI;
import com.easyproject.common.config.ProjectConfig;
import com.easyproject.common.constant.Constants;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.utils.StringUtils;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.common.utils.file.FileContentReader;
import com.easyproject.common.utils.file.FileUtils;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.mapper.coze.CozeWorkspacesSetMapper;
import com.easyproject.service.service.ICozeJwtService;
import com.easyproject.system.domain.dto.AddKnowledgeDocumentDto;
import com.easyproject.system.domain.dto.KnowledgeDocListDto;
import com.easyproject.system.domain.dto.KnowledgeDocumentDto;
import com.easyproject.system.domain.dto.KnowledgeImageDto;
import com.easyproject.system.domain.vo.knowledgeDoc.ApiResponse;
import com.easyproject.system.service.aiModel.IKnowledgeDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 方法说明: 知识库文件
 * @param
 * @return
 * @author java-101
 * @date 2025-04-01 13:14:07
 */
@Slf4j
@Service
public class KnowledgeDocumentServiceImpl implements IKnowledgeDocumentService {

    @Resource
    private CozeWorkspacesSetMapper cozeWorkspacesSetMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 方法说明: 查询知识库文件列表
     * @param
     * @return
     * @author java-101
     * @date 2025-04-01 13:30:03
     */
    @Override
    public AjaxResult getKnowledgeDocList(KnowledgeDocListDto dto) {

        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }

        String url = ChatAiForCozeUtils.getKnowledgeDocumenList();
        // 创建 JSON 请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("dataset_id", dto.getDataset_id());
        jsonBody.put("page", 1);
        jsonBody.put("size", 300);

        // 发送 POST 请求
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + tokenSet.getPersonToken())
                .header("Content-Type", "application/json")
                .header("Agw-Js-Conv", "str")
                .body(jsonBody.toString())
                .execute();

        String result = response.body();
        ApiResponse vo = null;
        if(ObjectUtil.isNotEmpty(result)){
            vo = JSONUtil.toBean(result, ApiResponse.class);
        }

        if(ObjectUtil.isNotEmpty(vo)){
            return AjaxResult.success(vo.getDocument_infos());
        }else {
            return AjaxResult.error("系统错误，请稍后重试");
        }
    }

    /**
     * 方法说明: 查询知识库图片列表
     * @param
     * @return
     * @author java-101
     * @date 2025-04-03 23:09:39
     */
    @Override
    public AjaxResult datasetsImages(KnowledgeDocListDto dto) {

        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }

        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        Long dataset_id = dto.getDataset_id();
        ListImageReq req = ListImageReq.builder().datasetID(String.valueOf(dataset_id)).pageSize(299).pageNum(1).build();

        // 使用迭代器自动获取下一页
        PageResp<Image> images = coze.datasets().images().list(req);
        return AjaxResult.success(images.getItems());
    }

    /**
     * 方法说明: 知识库文件-修改名称
     * @param
     * @return
     * @author java-101
     * @date 2025-04-04 19:20:16
     */
    @Override
    public AjaxResult updateDocumentName(KnowledgeDocumentDto dto) {
        if(ObjectUtil.isEmpty(dto.getDocument_id()) || ObjectUtil.isEmpty(dto.getName())){
            return AjaxResult.error("名称不能为空");
        }
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        UpdateDocumentReq updateReq = UpdateDocumentReq.builder().documentID(dto.getDocument_id()).documentName(dto.getName()).build();
        UpdateDocumentResp uploadFileResp = coze.datasets().documents().update(updateReq);
        if (ObjectUtil.isNotEmpty(uploadFileResp) && ObjectUtil.isNotEmpty(uploadFileResp.getLogID())){
            return AjaxResult.success("修改成功");
        }else {
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 方法说明: 知识库文件-添加文件
     * @param
     * @return
     * @author java-101
     * @date 2025-04-05 20:28:42
     */
    @Override
    public AjaxResult addDocument(AddKnowledgeDocumentDto dto) {
        if(ObjectUtil.isEmpty(dto.getDataset_id()) || ObjectUtil.isEmpty(dto.getDocument_list())){
            return AjaxResult.error("知识库ID或文件列表不能为空");
        }
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        // 本地资源路径
        String localPath = ProjectConfig.getProfile();
        String[] fileUrls = dto.getDocument_list().split(",");
        List<DocumentBase> documentBaseList = null;
        DocumentBase documentBase = null;
        for (String url : fileUrls) {
            if(ObjectUtil.isEmpty(documentBaseList)){
                documentBaseList = new ArrayList<>();
            }
            //文件的绝对路径
            String filePath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
            File localFile = new File(filePath);
            if (!localFile.exists()) {
                return AjaxResult.error("文件不存在");
            }
            //获取文件名称以及后缀 "aaa. jpg"
            String fileName = FileNameUtil.getName(localFile);
            String fileSuffix = FileNameUtil.extName(localFile);
            //读取文件内容
            String fileContent = FileContentReader.readFileContent(localFile);

            documentBase = DocumentBase.buildLocalFile(fileName, fileContent, fileSuffix);
            documentBaseList.add(documentBase);
        }

        CreateDocumentReq createReq =
                CreateDocumentReq.builder()
                        .datasetID(dto.getDataset_id())
                        .documentBases(documentBaseList)
                        .formatType(DocumentFormatType.DOCUMENT)
                        .chunkStrategy(DocumentChunkStrategy.buildAuto())
                        .build();
        CreateDocumentResp creatResp = coze.datasets().documents().create(createReq);
        System.out.println(creatResp);
        if(ObjectUtil.isNotEmpty(creatResp) && ObjectUtil.isNotEmpty(creatResp.getDocumentInfos())){
            return AjaxResult.success("添加成功");
        }else{
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 方法说明: 知识库文件-删除文件
     * @param
     * @return
     * @author java-101
     * @date 2025-04-05 23:47:08
     */
    @Override
    public AjaxResult deleteDocument(KnowledgeDocumentDto dto) {
        if(ObjectUtil.isEmpty(dto.getDocument_id())){
            return AjaxResult.error("知识库文件ID不能为空");
        }
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        DeleteDocumentResp deletedResp =
                coze.datasets()
                        .documents()
                        .delete(
                                DeleteDocumentReq.builder()
                                        .documentIDs(Collections.singletonList(dto.getDocument_id()))
                                        .build());
        if(ObjectUtil.isNotEmpty(deletedResp) && ObjectUtil.isNotEmpty(deletedResp.getLogID())){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 方法说明: 知识库文件-添加图片
     * @param
     * @return
     * @author java-101
     * @date 2025-04-06 00:12:44
     */
    @Override
    public AjaxResult addImage(AddKnowledgeDocumentDto dto) {
        if(ObjectUtil.isEmpty(dto.getDataset_id()) || ObjectUtil.isEmpty(dto.getDocument_list())){
            return AjaxResult.error("知识库ID或图片列表不能为空");
        }
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        // 本地资源路径
        String localPath = ProjectConfig.getProfile();
        String[] fileUrls = dto.getDocument_list().split(",");
        List<DocumentBase> documentBaseList = null;
        DocumentBase documentBase = null;
        for (String url : fileUrls) {
            if(ObjectUtil.isEmpty(documentBaseList)){
                documentBaseList = new ArrayList<>();
            }
            //图片的绝对路径
            String filePath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
            File localFile = new File(filePath);
            if (!localFile.exists()) {
                return AjaxResult.error("文件不存在");
            }

            //上传图标到coze平台
            UploadFileResp imageInfo = coze.files().upload(UploadFileReq.of(filePath));
            if(ObjectUtil.isEmpty(imageInfo)){
                return AjaxResult.error("添加失败，图标上传失败");
            }
            //删除本地图片
            FileUtils.deleteFile(filePath);

            String imageFileName = imageInfo.getFileInfo().getFileName();
            String imageFileID = imageInfo.getFileInfo().getID();

            documentBase = DocumentBase.buildImage(imageFileName, Long.parseLong(imageFileID));
            documentBaseList.add(documentBase);
        }

        CreateDocumentReq createReq =
                CreateDocumentReq.builder()
                        .datasetID(dto.getDataset_id())
                        .documentBases(documentBaseList)
                        .formatType(DocumentFormatType.IMAGE)
                        .chunkStrategy(DocumentChunkStrategy.buildAuto())
                        .build();
        CreateDocumentResp creatResp = coze.datasets().documents().create(createReq);

        System.out.println(creatResp);
        if(ObjectUtil.isNotEmpty(creatResp) && ObjectUtil.isNotEmpty(creatResp.getDocumentInfos())){
            return AjaxResult.success("添加成功");
        }else{
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 方法说明: 知识库文件-修改图片描述
     * @param
     * @return
     * @author java-101
     * @date 2025-04-06 01:03:52
     */
    @Override
    public AjaxResult updateImageCaption(KnowledgeImageDto dto) {
        if(ObjectUtil.isEmpty(dto.getDocument_id()) || ObjectUtil.isEmpty(dto.getCaption()) || ObjectUtil.isEmpty(dto.getDataset_id())){
            return AjaxResult.error("参数错误");
        }
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        UpdateImageReq updateReq =
                UpdateImageReq.builder()
                        .datasetID(dto.getDataset_id())
                        .documentID(String.valueOf(dto.getDocument_id()))
                        .caption(dto.getCaption())
                        .build();
        UpdateImageResp updateResp = coze.datasets().images().update(updateReq);
        if (ObjectUtil.isNotEmpty(updateResp) && ObjectUtil.isNotEmpty(updateResp.getLogID())){
            return AjaxResult.success("修改成功");
        }else {
            return AjaxResult.error("修改失败");
        }
    }

}
