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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coze.openapi.client.common.pagination.PageResp;
import com.coze.openapi.client.dataset.*;
import com.coze.openapi.client.dataset.document.model.DocumentFormatType;
import com.coze.openapi.client.dataset.model.Dataset;
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.constant.HttpStatus;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.core.page.TableDataInfo;
import com.easyproject.common.utils.StringUtils;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.common.utils.file.FileUtils;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.domain.coze.CozeWorkspacesSet;
import com.easyproject.service.mapper.coze.CozeTokenSetMapper;
import com.easyproject.service.mapper.coze.CozeWorkspacesSetMapper;
import com.easyproject.service.service.ICozeJwtService;
import com.easyproject.system.domain.dto.EditKnowledgeDto;
import com.easyproject.system.domain.dto.KnowledgeListDto;
import com.easyproject.system.domain.vo.KnowledgeListVo;
import com.easyproject.system.service.aiModel.IKnowledgeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 方法说明: 知识库
 * @param
 * @return
 * @author java-101
 * @date 2025-03-25 23:05:05
 */
@Slf4j
@Service
public class KnowledgeServiceImpl implements IKnowledgeService {
    @Resource
    private CozeWorkspacesSetMapper cozeWorkspacesSetMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 方法说明: 查询知识库列表
     * @param
     * @return
     * @author java-101
     * @date 2025-03-25 23:15:42
     */
    @Override
    public TableDataInfo selKnowledgeList(KnowledgeListDto dto) {

        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();

        //查询有效空间
        CozeWorkspacesSet workspacesSet = cozeWorkspacesSetMapper.selectOne(Wrappers.<CozeWorkspacesSet>lambdaQuery().eq(CozeWorkspacesSet::getStatus,1).orderByDesc(CozeWorkspacesSet::getId).last("limit 1"));
        if(ObjectUtil.isEmpty(workspacesSet)){
            log.error("系统错误，请稍后重试");
            return null;
        }

        //自定义分页信息
        TableDataInfo rspData = new TableDataInfo();

        List<KnowledgeListVo> voList = null;
        if(ObjectUtil.isNotEmpty(tokenSet) && ObjectUtil.isNotEmpty(workspacesSet)){

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

            String spaceID = workspacesSet.getSpacesId();

            ListDatasetReq req = ListDatasetReq.builder().spaceID(spaceID).name(dto.getName()).formatType(DocumentFormatType.fromValue(dto.getFormat_type())).pageSize(dto.getPageSize()).pageNum(dto.getPageNum()).build();

            // 使用迭代器自动获取下一页
            PageResp<Dataset> datasets = coze.datasets().list(req);

            // 页面结果会返回以下信息
            System.out.println("total: " + datasets.getTotal());
            System.out.println("has_more: " + datasets.getHasMore());
            System.out.println("logID: " + datasets.getLogID());

            voList = new ArrayList<>();
            KnowledgeListVo vo = null;
            for (Dataset item : datasets.getItems()) {
                System.out.println(item);
                vo = BeanUtil.copyProperties(item, KnowledgeListVo.class);
                vo.setDocCount(item.getFileList().size());
                voList.add(vo);
            }

            //自定义分页信息
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(voList);
            rspData.setTotal(datasets.getTotal());
        }

        return rspData;
    }

    /**
     * 方法说明: 添加知识库
     * @param
     * @return
     * @author java-101
     * @date 2025-03-30 15:26:15
     */
    @Override
    public AjaxResult addKnowledge(EditKnowledgeDto dto) {
        if(ObjectUtil.isEmpty(dto.getFormatType())){
            return AjaxResult.error("请选择知识库类型");
        }
        if(ObjectUtil.isEmpty(dto.getName())){
            return AjaxResult.error("请输入知识库名称");
        }
        if(ObjectUtil.isEmpty(dto.getDescription())){
            return AjaxResult.error("请输入知识库描述");
        }
        if(ObjectUtil.isEmpty(dto.getIcon_url())){
            return AjaxResult.error("请上传知识库图标");
        }
        if(dto.getFormatType()!=0 && dto.getFormatType()!=2){
            return AjaxResult.error("知识库类型错误");
        }
        // 本地资源路径
        String localPath = ProjectConfig.getProfile();
        //图标的绝对路径
        String iconFilePath = localPath + StringUtils.substringAfter(dto.getIcon_url(), Constants.RESOURCE_PREFIX);

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

        //查询有效空间
        CozeWorkspacesSet workspacesSet = cozeWorkspacesSetMapper.selectOne(Wrappers.<CozeWorkspacesSet>lambdaQuery().eq(CozeWorkspacesSet::getStatus,1).orderByDesc(CozeWorkspacesSet::getId).last("limit 1"));
        if(ObjectUtil.isEmpty(workspacesSet)){
            log.error("系统错误，请稍后重试");
            return AjaxResult.error("系统错误，请稍后重试");
        }

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

        //上传图标到coze平台
        UploadFileResp imageInfo = coze.files().upload(UploadFileReq.of(iconFilePath));
        if(ObjectUtil.isEmpty(imageInfo)){
            return AjaxResult.error("添加失败，图标上传失败");
        }

        //创建知识库
        CreateDatasetReq createReq = CreateDatasetReq.builder()
                        .name(dto.getName())
                        .spaceID(spaceID)
                        .formatType(DocumentFormatType.fromValue(dto.getFormatType()))
                        .description(dto.getDescription())
                        .fileID(imageInfo.getFileInfo().getID())
                        .build();
        CreateDatasetResp createResp = coze.datasets().create(createReq);
        System.out.println("Created dataset ID: " + createResp.getDatasetID());
        if(ObjectUtil.isNotEmpty(createResp.getDatasetID())){
            //删除本地图片
            FileUtils.deleteFile(iconFilePath);
            return AjaxResult.success("添加成功");
        }else {
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 方法说明: 修改知识库
     * @param
     * @return
     * @author java-101
     * @date 2025-03-31 11:55:07
     */
    @Override
    public AjaxResult updateKnowledge(EditKnowledgeDto dto) {
        if(ObjectUtil.isEmpty(dto.getDatasetId())){
            return AjaxResult.error("知识库ID错误");
        }
        if(ObjectUtil.isEmpty(dto.getName())){
            return AjaxResult.error("请输入知识库名称");
        }
        if(ObjectUtil.isEmpty(dto.getDescription())){
            return AjaxResult.error("请输入知识库描述");
        }
        if(ObjectUtil.isEmpty(dto.getIcon_url())){
            return AjaxResult.error("请上传知识库图标");
        }

        String datasetID = dto.getDatasetId();//知识库ID

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

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

        boolean isUpdateIcon = false;//是否更新图标
        String fileID = null;
        if(!dto.getIcon_url().contains("http://") && !dto.getIcon_url().contains("https://")){
            //说明有修改图标，则需要上传
            // 本地资源路径
            String localPath = ProjectConfig.getProfile();
            //图标的绝对路径
            String iconFilePath = localPath + StringUtils.substringAfter(dto.getIcon_url(), Constants.RESOURCE_PREFIX);

            //上传图标到coze平台
            UploadFileResp imageInfo = coze.files().upload(UploadFileReq.of(iconFilePath));
            if(ObjectUtil.isEmpty(imageInfo)){
                return AjaxResult.error("添加失败，图标上传失败");
            }
            fileID = imageInfo.getFileInfo().getID();
            isUpdateIcon = true;
        }

        UpdateDatasetReq updateReq = null;

        if(isUpdateIcon){//有修改图标
            updateReq = UpdateDatasetReq.builder()
                    .datasetID(datasetID)
                    .name(dto.getName())
                    .description(dto.getDescription())
                    .fileID(fileID)
                    .build();
        }else{
            updateReq = UpdateDatasetReq.builder()
                    .datasetID(datasetID)
                    .name(dto.getName())
                    .description(dto.getDescription())
                    .build();
        }

        UpdateDatasetResp updateResp = coze.datasets().update(updateReq);
        System.out.println("Update dataset response: " + updateResp);
        if(ObjectUtil.isNotEmpty(updateResp.getLogID())){
            return AjaxResult.success("修改成功");
        }else {
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 方法说明: 删除知识库
     * @param
     * @return
     * @author java-101
     * @date 2025-03-31 19:09:11
     */
    @Override
    public AjaxResult deleteKnowledge(EditKnowledgeDto dto) {
        if(ObjectUtil.isEmpty(dto.getDatasetId())){
            return AjaxResult.error("知识库ID错误");
        }

        //知识库ID
        String datasetID = dto.getDatasetId();

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

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

        DeleteDatasetReq deleteReq = DeleteDatasetReq.builder().datasetID(datasetID).build();
        DeleteDatasetResp deleteResp = coze.datasets().delete(deleteReq);
        System.out.println("Delete dataset response: " + deleteResp);

        if(ObjectUtil.isNotEmpty(deleteResp.getLogID())){
            return AjaxResult.success("删除成功");
        }else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 方法说明: 查询知识库列表-全部
     * @param
     * @return
     * @author java-101
     * @date 2025-03-31 21:07:39
     */
    @Override
    public AjaxResult selKnowledgeAllList(EditKnowledgeDto dto) {
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }

        //查询有效空间
        CozeWorkspacesSet workspacesSet = cozeWorkspacesSetMapper.selectOne(Wrappers.<CozeWorkspacesSet>lambdaQuery().eq(CozeWorkspacesSet::getStatus,1).orderByDesc(CozeWorkspacesSet::getId).last("limit 1"));
        if(ObjectUtil.isEmpty(workspacesSet)){
            return AjaxResult.error("系统错误，请稍后重试");
        }
        String spaceID = workspacesSet.getSpacesId();

        List<KnowledgeListVo> voList = null;

        DocumentFormatType formatType = null;
        if(ObjectUtil.isNotEmpty(dto.getFormatType())){
            formatType = DocumentFormatType.fromValue(dto.getFormatType());
        }

        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());
        ListDatasetReq req = ListDatasetReq.builder()
                .spaceID(spaceID)
                .name(null)
                .formatType(formatType)
                .pageSize(300)
                .pageNum(1)
                .build();

        // 使用迭代器自动获取下一页
        PageResp<Dataset> datasets = coze.datasets().list(req);

        voList = new ArrayList<>();
        KnowledgeListVo vo = null;
        for (Dataset item : datasets.getItems()) {
            System.out.println(item);
            vo = BeanUtil.copyProperties(item, KnowledgeListVo.class);
            vo.setDocCount(item.getFileList().size());
            voList.add(vo);
        }
        return AjaxResult.success(voList);
    }
}
