package com.ruoyi.llm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SnowFlake;
import com.ruoyi.llm.domain.CmcChat;
import com.ruoyi.llm.domain.CmcDocument;
import com.ruoyi.llm.mapper.CmcChatMapper;
import com.ruoyi.llm.mapper.CmcDocumentMapper;
import com.ruoyi.llm.service.ICmcChatService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.llm.mapper.CmcAgentMapper;
import com.ruoyi.llm.domain.CmcAgent;
import com.ruoyi.llm.service.ICmcAgentService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 智能体Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-17
 */
@Service
public class CmcAgentServiceImpl implements ICmcAgentService 
{
    @Autowired
    private CmcAgentMapper cmcAgentMapper;

    @Autowired
    private CmcDocumentMapper cmcDocumentMapper;

    @Autowired
    private CmcChatMapper cmcChatMapper;

    /**
     * 查询智能体
     * 
     * @param agentId 智能体主键
     * @return 智能体
     */
    @Override
    public CmcAgent selectCmcAgentByAgentId(Integer agentId)
    {
        return cmcAgentMapper.selectCmcAgentByAgentId(agentId);
    }

    /**
     * 查询智能体列表
     * 
     * @param cmcAgent 智能体
     * @return 智能体
     */
    @Override
    public List<CmcAgent> selectCmcAgentList(CmcAgent cmcAgent)
    {
        return cmcAgentMapper.selectCmcAgentList(cmcAgent);
    }

    /**
     * 获取开场白
     *
     * @param agentName 智能体名称
     * @return 结果
     */
    @Override
    public String getOpening(String agentName) {
        String content = "";
        if (agentName.contains("技术"))
            content = "我是投标文件写作助手，我将助您完成技术文件部分撰写。请上传招标询价文件，分析后将依招标服务要求，运用技术方案知识库，为您提供参考。";
        return content;
    }

    /**
     * 上传单文件
     *
     * @param file 文件
     * @return 结果
     */
    @Override
    public JSONObject uploadDocument(MultipartFile file, String agentName) throws IOException {
        File profilePath = new File( RuoYiConfig.getProfile() + "/upload/agent/" + agentName);
        if (!profilePath.exists())
            profilePath.mkdirs();
        File transferFile = new File(profilePath + "/" + file.getOriginalFilename());
        if (!transferFile.exists())
            file.transferTo(transferFile);
        String chatId = new SnowFlake().generateId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("chatId", chatId);
        String[] filenameSplit = file.getOriginalFilename().split("\\.");
        String outputFilename = "/upload/agent/" + agentName + "/" + file.getOriginalFilename().replace(filenameSplit[filenameSplit.length - 2], filenameSplit[filenameSplit.length - 2] + "_" + agentName);
        CmcDocument cmcDocument = new CmcDocument();
        cmcDocument.setDocumentId(new SnowFlake().generateId());
        cmcDocument.setChatId(chatId);
        cmcDocument.setPath(outputFilename);
        cmcDocumentMapper.insertCmcDocument(cmcDocument);
        String message = "";
        if (agentName.contains("技术")) {
            CmcChat cmcChat = new CmcChat();
            cmcChat.setChatId(jsonObject.getString("chatId"));
            cmcChat.setInputTime(new Date());
            cmcChat.setInput("招标文件地址：" + outputFilename);
            cmcChat.setUserId(SecurityUtils.getUserId());
            cmcChatMapper.insertCmcChat(cmcChat);
            XWPFDocument doc = new XWPFDocument(new FileInputStream(RuoYiConfig.getProfile() + "/upload/agent/template/technical.docx"));
            // 保存文档到本地文件系统
            FileOutputStream out = new FileOutputStream(RuoYiConfig.getProfile() + outputFilename);
            doc.write(out);
            // 关闭文档
            out.close();
            doc.close();
            
            message = "好的，我已经收到您上传的招标文件，我将给您提供技术文件模板，您可点击进行预览：" +
                    "【<a href='/profile" + outputFilename + "'> 模版 " + "</a>】\n\n" +
                    "技术文件涉及多个章节：\n" +
                    "1 项目条件及特性\n" +
                    "2 项目重点和难点的分析与对策\n" +
                    "3 项目策划、技术路线、工作方法、流程及措施\n" +
                    "4 资源配置\n" +
                    "5 进度计划及保证措施\n" +
                    "6 质量保证措施\n" +
                    "7 服务与技术支持\n" +
                    "8 职业健康、安全生产及环保水保措施\n\n" +
                    "请问您需要哪些章节撰写的帮助？";
        }
        jsonObject.put("assistantMessage", message);
        return jsonObject;
    }

    /**
     * 上传多文件
     *
     * @param fileList 文件
     * @return 结果
     */
    @Override
    public String uploadDocumentList(MultipartFile[] fileList, String agentName) throws IOException {
        File profilePath = new File( RuoYiConfig.getProfile() + "/upload/agent/" + agentName);
        if (!profilePath.exists())
            profilePath.mkdirs();
        for (MultipartFile file : fileList) {
            File transferFile = new File(profilePath + File.separator + file.getOriginalFilename());
            if (!transferFile.exists())
                file.transferTo(transferFile);
        }
        return "上传成功";
    }

    /**
     * 新增智能体
     * 
     * @param cmcAgent 智能体
     * @return 结果
     */
    @Override
    public int insertCmcAgent(CmcAgent cmcAgent)
    {
        cmcAgent.setCreateTime(DateUtils.getNowDate());
        return cmcAgentMapper.insertCmcAgent(cmcAgent);
    }

    /**
     * 修改智能体
     * 
     * @param cmcAgent 智能体
     * @return 结果
     */
    @Override
    public int updateCmcAgent(CmcAgent cmcAgent)
    {
        return cmcAgentMapper.updateCmcAgent(cmcAgent);
    }

    /**
     * 批量删除智能体
     * 
     * @param agentIds 需要删除的智能体主键
     * @return 结果
     */
    @Override
    public int deleteCmcAgentByAgentIds(Integer[] agentIds)
    {
        return cmcAgentMapper.deleteCmcAgentByAgentIds(agentIds);
    }

    /**
     * 删除智能体信息
     * 
     * @param agentId 智能体主键
     * @return 结果
     */
    @Override
    public int deleteCmcAgentByAgentId(Integer agentId)
    {
        return cmcAgentMapper.deleteCmcAgentByAgentId(agentId);
    }
}
