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

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coze.openapi.client.dataset.document.CreateDocumentReq;
import com.coze.openapi.client.dataset.document.CreateDocumentResp;
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.service.service.CozeAPI;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.service.domain.aichat.BotConversationChat;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.mapper.aichat.BotConversationChatMapper;
import com.easyproject.service.service.ICozeJwtService;
import com.easyproject.system.domain.vo.BotConversationChatVo;
import com.easyproject.system.service.aichat.IBotConversationChatService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 对话列表Service业务层处理
 *
 * @author easyproject
 * @date 2025-04-10
 */
@Service
public class BotConversationChatServiceImpl implements IBotConversationChatService {
    @Resource
    private BotConversationChatMapper botConversationChatMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 查询对话列表
     *
     * @param id 对话列表主键
     * @return 对话列表
     */
    @Override
    public BotConversationChat selectBotConversationChatById(Long id) {
        return botConversationChatMapper.selectBotConversationChatById(id);
    }

    /**
     * 查询对话列表列表
     *
     * @param botConversationChat 对话列表
     * @return 对话列表
     */
    @Override
    public List<BotConversationChat> selectBotConversationChatList(BotConversationChat botConversationChat) {
        return botConversationChatMapper.selectBotConversationChatList(botConversationChat);
    }

    /**
     * 方法说明: 详情
     * @param
     * @return
     * @author java-101
     * @date 2025-04-10 18:33:47
     */
    @Override
    public AjaxResult getConversationChatMsg(Long id) {
        BotConversationChat botConversationChat = botConversationChatMapper.selectById(id);
        if(ObjectUtil.isEmpty(botConversationChat)){
            return AjaxResult.error("对话不存在");
        }

        List<BotConversationChatVo> chatVoList = new ArrayList<>();
        BotConversationChatVo chatVo = null;
        //处理用户发的数据
        chatVo = new BotConversationChatVo();
        chatVo.setContent(botConversationChat.getMsgContent());
        chatVo.setRole("user");
        chatVoList.add(chatVo);

        //处理智能体发的数据
        chatVo = new BotConversationChatVo();
        chatVo.setContent(botConversationChat.getBackMsgContent());
        chatVo.setRole("assistant");
        chatVoList.add(chatVo);

        return AjaxResult.success(chatVoList);
    }

    /**
     * 方法说明: 设为知识库文件
     * @param
     * @return
     * @author java-101
     * @date 2025-04-10 19:08:19
     */
    @Override
    public AjaxResult setknowledgeFile(BotConversationChat botConversationChat) {
        if(ObjectUtil.isEmpty(botConversationChat.getMsgContent())){
            return AjaxResult.error("文件名称不能为空");
        }
        if(ObjectUtil.isEmpty(botConversationChat.getBackMsgContent())){
            return AjaxResult.error("文件内容不能为空");
        }
        if (ObjectUtil.isEmpty(botConversationChat.getKnowledgeId())){
            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 fileName = botConversationChat.getMsgContent();
        String fileContent = botConversationChat.getBackMsgContent();
        String fileSuffix = "txt";
        DocumentBase documentBase = DocumentBase.buildLocalFile(fileName, fileContent, fileSuffix);

        List<DocumentBase> documentBaseList = new ArrayList<>();
        documentBaseList.add(documentBase);

        CreateDocumentReq createReq =
                CreateDocumentReq.builder()
                        .datasetID(Long.valueOf(botConversationChat.getKnowledgeId()))
                        .documentBases(documentBaseList)
                        .formatType(DocumentFormatType.DOCUMENT)
                        .chunkStrategy(DocumentChunkStrategy.buildAuto())
                        .build();
        CreateDocumentResp creatResp = coze.datasets().documents().create(createReq);

        if(ObjectUtil.isNotEmpty(creatResp) && ObjectUtil.isNotEmpty(creatResp.getDocumentInfos())){
            //设置成功后，标记本地数据库
            LambdaUpdateWrapper<BotConversationChat> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(BotConversationChat::getIsUpload, 2);
            updateWrapper.set(BotConversationChat::getRemark, botConversationChat.getRemark());
            updateWrapper.set(BotConversationChat::getUpdateTime, DateUtil.date());
            updateWrapper.eq(BotConversationChat::getId, botConversationChat.getId());
            botConversationChatMapper.update(null, updateWrapper);
            return AjaxResult.success("设置成功");
        }else{
            return AjaxResult.error("设置失败");
        }
    }

}
