package cn.iocoder.yudao.module.llm.service.prompttemplates;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.llm.controller.admin.prompttemplates.vo.*;
import cn.iocoder.yudao.module.llm.controller.admin.prompttemplatesbackup.vo.PromptTemplatesBackupSaveReqVO;
import cn.iocoder.yudao.module.llm.dal.dataobject.label.LabelDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.prompttemplates.PromptTemplatesDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.prompttemplatesapplications.PromptTemplatesApplicationsDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.prompttemplatesbackup.PromptTemplatesBackupDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.prompttemplatestags.PromptTemplatesTagsDO;
import cn.iocoder.yudao.module.llm.dal.mysql.prompttemplates.PromptTemplatesMapper;
import cn.iocoder.yudao.module.llm.dal.mysql.prompttemplatesapplications.PromptTemplatesApplicationsMapper;
import cn.iocoder.yudao.module.llm.dal.mysql.prompttemplatestags.PromptTemplatesTagsMapper;
import cn.iocoder.yudao.module.llm.framework.backend.config.LLMBackendProperties;
import cn.iocoder.yudao.module.llm.service.application.ApplicationService;
import cn.iocoder.yudao.module.llm.service.label.LabelService;
import cn.iocoder.yudao.module.llm.service.prompttemplatesbackup.PromptTemplatesBackupService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.llm.enums.ErrorCodeConstants.*;

@Slf4j
@Service
@Validated
public class PromptTemplatesServiceImpl implements PromptTemplatesService {
    @Resource
    private PromptTemplatesMapper promptTemplatesMapper;
    @Resource
    private PromptTemplatesTagsMapper promptTemplatesTagsMapper;
    @Resource
    private PromptTemplatesApplicationsMapper promptTemplatesApplicationsMapper;
    @Resource
    private DictDataApi dictDataApi;
    @Resource
    @Lazy
    private LabelService labelService;
    @Resource
    private PromptTemplatesBackupService promptTemplatesBackupService;
    @Resource
    private LLMBackendProperties llmBackendProperties;

    @Lazy
    @Resource
    private ApplicationService applicationService;

    @Override
    public Long createPromptTemplates (PromptTemplatesSaveReqVO createReqVO) {
        this.isNameDuplicate(createReqVO.getName());
        PromptTemplatesDO promptTemplates = BeanUtils.toBean(createReqVO, PromptTemplatesDO.class);

//        LoginUser user = SecurityFrameworkUtils.getLoginUser();
//        Integer userType = user.getUserType();
//        //不允许学生创建预制模板
//        if(promptTemplates.getTemplateType() == 1 && userType == 2){
//            throw exception(new ErrorCode(100200300, "不允许学生创建预制模板"));
//
//        }
//        promptTemplates.setTemplateType(2);

        String categoryName = this.dictDataApi.getDictDataLabel("llm_prompt_template_framework",Integer.valueOf(createReqVO.getTemplateFramework()));
        switch (categoryName) {
            case "简介框架":
                BriefFramework briefFramework = createReqVO.getBriefFramework();
                promptTemplates.setTemplateText(JSON.toJSONString(briefFramework));
                break;
            case "角色能力框架":
                AbilityFramework abilityFramework = createReqVO.getAbilityFramework();
                promptTemplates.setTemplateText(JSON.toJSONString(abilityFramework));
                break;
            case "样例提示框架":
                SampleFramework sampleFramework = createReqVO.getSampleFramework();
                promptTemplates.setTemplateText(JSON.toJSONString(sampleFramework));
                break;
            default:
                break;
        }
        promptTemplatesMapper.insert(promptTemplates);
        List<String> tagIds = createReqVO.getTagIds();
        if (tagIds != null && !tagIds.isEmpty()) {
            List<PromptTemplatesTagsDO> tagDOList = tagIds.stream()
                    .map(p -> PromptTemplatesTagsDO.builder()
                            .tagId(Long.valueOf(p))
                            .promptTemplateId(promptTemplates.getId())
                            .build())
                    .collect(Collectors.toList());
            this.promptTemplatesTagsMapper.insertBatch(tagDOList, 1);
        }
        List<String> applicationIds = createReqVO.getApplicationIds();
        if (applicationIds != null && !applicationIds.isEmpty()) {
            List<PromptTemplatesApplicationsDO> applicationDOList = applicationIds.stream()
                    .map(p -> PromptTemplatesApplicationsDO.builder()
                            .applicationId(Long.valueOf(p))
                            .promptTemplateId(promptTemplates.getId())
                            .build())
                    .collect(Collectors.toList());
            this.promptTemplatesApplicationsMapper.insertBatch(applicationDOList, 1);
        }
        return promptTemplates.getId();
    }

    @Override
    public void updatePromptTemplates (PromptTemplatesSaveReqVO updateReqVO) {
        PromptTemplatesDO templatesDo = this.promptTemplatesMapper.selectById(updateReqVO.getId());

        if (templatesDo == null) {
            throw exception(PROMPT_TEMPLATES_NOT_EXISTS);
        }

//        LoginUser user = SecurityFrameworkUtils.getLoginUser();
//        Integer userType = user.getUserType();
//        //不允许学生创建预制模板
//        if(templatesDo.getTemplateType() == 1 && userType == 2){
//            throw exception(new ErrorCode(100200300, "不允许学生修改预制模板"));
//
//        }

        if (!templatesDo.getName().equals(updateReqVO.getName())) {
            this.isNameDuplicate(updateReqVO.getName());
        }
        PromptTemplatesDO updateObj = BeanUtils.toBean(updateReqVO, PromptTemplatesDO.class);
                String categoryName = this.dictDataApi.getDictDataLabel("llm_prompt_template_framework",Integer.valueOf(updateReqVO
                        .getTemplateFramework()));
                switch (categoryName) {
                    case "简介框架":
                        BriefFramework briefFramework = updateReqVO.getBriefFramework();
                        updateObj.setTemplateText(JSON.toJSONString(briefFramework));
                        break;
                    case "角色能力框架":
                        AbilityFramework abilityFramework = updateReqVO.getAbilityFramework();
                        updateObj.setTemplateText(JSON.toJSONString(abilityFramework));
                        break;
                    case "样例提示框架":
                        SampleFramework sampleFramework = updateReqVO.getSampleFramework();
                        updateObj.setTemplateText(JSON.toJSONString(sampleFramework));
                        break;
                    default:
                        break;
                }
        promptTemplatesMapper.updateById(updateObj);
        Map<String, Object> deleteCondition = new HashMap<>(1);
        deleteCondition.put("prompt_template_id", updateReqVO.getId());
        this.promptTemplatesTagsMapper.deleteByMap(deleteCondition);
        List<String> tagIds = updateReqVO.getTagIds();
        if (tagIds != null && !tagIds.isEmpty()) {
            List<PromptTemplatesTagsDO> tagDOList = tagIds.stream()
                    .map(p -> PromptTemplatesTagsDO.builder()
                            .tagId(Long.valueOf(p))
                            .promptTemplateId(updateReqVO.getId())
                            .build())
                    .collect(Collectors.toList());
            this.promptTemplatesTagsMapper.insertBatch(tagDOList, 1);
        }
        this.promptTemplatesApplicationsMapper.deleteByMap(deleteCondition);
        List<String> applicationIds = updateReqVO.getApplicationIds();
        if (applicationIds != null && !applicationIds.isEmpty()) {
            List<PromptTemplatesApplicationsDO> applicationDOList = applicationIds.stream()
                    .map(p -> PromptTemplatesApplicationsDO.builder()
                            .applicationId(Long.valueOf(p))
                            .promptTemplateId(updateReqVO.getId())
                            .build())
                    .collect(Collectors.toList());
            this.promptTemplatesApplicationsMapper.insertBatch(applicationDOList, 1);
        }
    }

    /**
     * 删除 Prompt模板
     *
     * @param id id
     */
    @Override
    public void deletePromptTemplates (Long id) {
        PromptTemplatesDO promptTemplatesDO = validatePromptTemplatesExists(id);

//        LoginUser user = SecurityFrameworkUtils.getLoginUser();
//        Integer userType = user.getUserType();
//        //不允许学生删除预制模板
//        if(promptTemplatesDO.getTemplateType() == 1 && userType == 2){
//            throw exception(new ErrorCode(100200300, "不允许学生删除预制模板"));
//
//        }

        // 校验 Prompt模板 使用情况
//        validatePromptTemplatesUse(id);
        promptTemplatesMapper.deleteById(id);
        Map<String, Object> condition = new HashMap<>(1);
        condition.put("prompt_template_id", id);
        this.promptTemplatesTagsMapper.deleteByMap(condition);
        this.promptTemplatesApplicationsMapper.deleteByMap(condition);
    }

    /**
     * 校验 Prompt模板 使用情况
     *
     * @param id Prompt模板id
     */
    private void validatePromptTemplatesUse (Long id) {
        // 获取 Prompt模板，用来返回错误信息
        PromptTemplatesDO promptTemplatesDO = promptTemplatesMapper.selectById(id);
        String name = promptTemplatesDO.getName();

        // 检查 Prompt模版 是否在 应用 中有使用
        validatePromptTemplateUsesInApp(id, name);
    }

    /**
     * 检查 Prompt模版 是否在 应用 中有使用
     *
     * @param id   Prompt模版 id
     * @param name Prompt模版 名称
     */
    private void validatePromptTemplateUsesInApp (Long id, String name) {
        Map<Long, String> apps = applicationService.validatePromptTemplateUsesInApp(id);

        if (CollectionUtils.isNotEmpty(apps)) {
            String msg = String.format("Prompt模版【%s】在 应用 %s 有使用，请先删除应用中的Prompt模版", name, apps.values());
            throw exception(new ErrorCode(100_1000_1, msg));
        }
    }

    private PromptTemplatesDO validatePromptTemplatesExists (Long id) {
        PromptTemplatesDO promptTemplatesDO = promptTemplatesMapper.selectById(id);
        if (promptTemplatesDO == null) {
            throw exception(PROMPT_TEMPLATES_NOT_EXISTS);
        }
        return promptTemplatesDO;
    }

    private void isNameDuplicate (String name) {
        List<PromptTemplatesDO> templateDOList = this.promptTemplatesMapper.selectList("name", name);
        if (templateDOList != null && !templateDOList.isEmpty()) {
            throw exception(PROMPT_TEMPLATES_EXISTS);
        }
    }

    @Override
    public PromptTemplatesRespVO getPromptTemplates (Long id) {
        PromptTemplatesDO templatesDO = this.promptTemplatesMapper.selectById(id);

        if (templatesDO == null) {
            throw exception(PROMPT_TEMPLATES_NOT_EXISTS);
        }
        PromptTemplatesRespVO promptTemplates = BeanUtils.toBean(templatesDO, PromptTemplatesRespVO.class);

        String templateText = templatesDO.getTemplateText();

        String append = "";
        String categoryName = this.dictDataApi.getDictDataLabel("llm_prompt_template_framework",Integer.valueOf(templatesDO
                .getTemplateFramework()));
        switch (categoryName) {
            case "简介框架":
                BriefFramework briefFramework = JSONObject.parseObject(templateText, BriefFramework.class);
                promptTemplates.setBriefFramework(briefFramework);
                append = "指令:" + briefFramework.getOrderInfo() + "/n" +
                         "背景信息" + briefFramework.getBgInfo() + "/n" +
                         "补充数据" + briefFramework.getPlusInfo() + "/n" +
                         "输出格式" + briefFramework.getOutputFormat() + "/n";
                break;
            case "角色能力框架":
                AbilityFramework abilityFramework = JSONObject.parseObject(templateText, AbilityFramework.class);
                promptTemplates.setAbilityFramework(abilityFramework);
                append = "指令:" + abilityFramework.getOrderInfo() + "/n" +
                        "背景信息" + abilityFramework.getBgInfo() + "/n" +
                        "能力与角色" + abilityFramework.getAbilityInfo() + "/n" +
                        "输出格式" + abilityFramework.getOutputFormat() + "/n";
                break;
            case "样例提示框架":
                SampleFramework sampleFramework = JSONObject.parseObject(templateText, SampleFramework.class);
                promptTemplates.setSampleFramework(sampleFramework);
                append = "背景信息" + sampleFramework.getBgInfo() + "/n" +
                        "样例列表:" + "/n";
                List<SampleFrameworkItem> itemList = sampleFramework.getItemList();
                if(itemList != null && itemList.size() > 0){
                    for (SampleFrameworkItem sampleFrameworkItem : itemList) {
                        append += "输入:" + sampleFrameworkItem.getInput() + "," + "输出:" + sampleFrameworkItem.getOutput() + "/n";
                    }
                }
                break;
            default:
                append = templateText;
                break;
        }
        promptTemplates.setTemplateText(append);

        // 标签
        getPromptTemplatesLabelResult(id, promptTemplates);

        // 应用
        getPromptTemplatesApplicationsResult(id, promptTemplates);

        return promptTemplates;
    }

    /**
     * 标签
     *
     * @param id              模版ID
     * @param promptTemplates 模版
     */
    private void getPromptTemplatesLabelResult (Long id, PromptTemplatesRespVO promptTemplates) {
        // 标签
        List<PromptTemplatesTagsDO> tagDOList = this.promptTemplatesTagsMapper
                .selectList("prompt_template_id", id);

        Map<Long, String> labelMap = labelService.getLabelMap(false);


        if (CollectionUtils.isNotEmpty(tagDOList)) {
            // 过滤 tagDOList 在 labelMap 中不存在的 tagIds，只保留存在的
            List<String> tagIds = tagDOList.stream()
                    .filter(tagsDO -> labelMap.containsKey(tagsDO.getTagId()))
                    .map(p -> String.valueOf(p.getTagId()))
                    .collect(Collectors.toList());
            promptTemplates.setTagIds(tagIds);

            // 获取对应的标签名称
            List<String> labelNameList = tagIds.stream()
                    .map(tagId -> labelMap.computeIfAbsent(Long.parseLong(tagId), k -> null))
                    .collect(Collectors.toList());
            promptTemplates.setTagNames(labelNameList);
        }

    }

    /**
     * 应用
     *
     * @param id              模版ID
     * @param promptTemplates 模版
     */
    private void getPromptTemplatesApplicationsResult (Long id, PromptTemplatesRespVO promptTemplates) {
        // 获取当前模版的应用
        List<PromptTemplatesApplicationsDO> applicationDOList = this.promptTemplatesApplicationsMapper
                .selectList("prompt_template_id", id);

        Map<Long, String> appMap = applicationService.getApplicatioMap();


        if (CollectionUtils.isNotEmpty(applicationDOList)) {
            // 过滤 applicationDOList 在 appMap 中不存在的 applicationIds，只保留存在的
            List<String> applicationIds = applicationDOList.stream()
                    .filter(applicationDO -> appMap.containsKey(applicationDO.getApplicationId()))
                    .map(p -> p.getApplicationId().toString())
                    .collect(Collectors.toList());
            promptTemplates.setApplicationIds(applicationIds);

            // 获取对应的应用名称
            List<String> appNameList = applicationIds.stream()
                    .map(appId -> appMap.computeIfAbsent(Long.parseLong(appId), k -> null))
                    .collect(Collectors.toList());
            promptTemplates.setApplicationNames(appNameList);
        }
    }

    @Override
    public PageResult<PromptTemplatesRespVO> getPromptTemplatesPage (PromptTemplatesPageReqVO pageReqVO) {
        if(pageReqVO.getTemplateType() != null && pageReqVO.getTemplateType() == 2){
            LoginUser user = SecurityFrameworkUtils.getLoginUser();
            pageReqVO.setCreator(user.getId());
        }
        PageResult<PromptTemplatesDO> pageDoList = this.promptTemplatesMapper.selectPage(pageReqVO);
        PageResult<PromptTemplatesRespVO> pageRespList = BeanUtils.toBean(pageDoList, PromptTemplatesRespVO.class);
        List<PromptTemplatesRespVO> templatesRespList = pageRespList.getList();

        if (CollectionUtils.isEmpty(templatesRespList)){
            return pageRespList;
        }
        for (PromptTemplatesRespVO respVO : templatesRespList) {
            try {
                // 标签
                List<PromptTemplatesTagsDO> tagDOList = this.promptTemplatesTagsMapper
                        .selectList("prompt_template_id", respVO.getId());

                Map<Long, String> labelMap = labelService.getLabelMap(false);

                if (CollectionUtils.isNotEmpty(tagDOList)) {
                    // 过滤 tagDOList 在 labelMap 中不存在的 tagIds，只保留存在的
                    List<String> tagIds = tagDOList.stream()
                            .filter(tagsDO -> labelMap.containsKey(tagsDO.getTagId()))
                            .map(p -> String.valueOf(p.getTagId()))
                            .collect(Collectors.toList());
                    respVO.setTagIds(tagIds);

                    // 获取对应的标签名称
                    List<String> labelNameList = tagIds.stream()
                            .map(tagId -> labelMap.computeIfAbsent(Long.parseLong(tagId), k -> null))
                            .collect(Collectors.toList());
                    respVO.setTagNames(labelNameList);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                // 获取当前模版的应用
                List<PromptTemplatesApplicationsDO> applicationDOList = this.promptTemplatesApplicationsMapper
                        .selectList("prompt_template_id", respVO.getId());

                Map<Long, String> appMap = applicationService.getApplicatioMap();

                if (CollectionUtils.isNotEmpty(applicationDOList)) {
                    // 过滤 applicationDOList 在 appMap 中不存在的 applicationIds，只保留存在的
                    List<String> applicationIds = applicationDOList.stream()
                            .filter(applicationDO -> appMap.containsKey(applicationDO.getApplicationId()))
                            .map(p -> p.getApplicationId().toString())
                            .collect(Collectors.toList());
                    respVO.setApplicationIds(applicationIds);

                    // 获取对应的应用名称
                    List<String> appNameList = applicationIds.stream()
                            .map(appId -> appMap.computeIfAbsent(Long.parseLong(appId), k -> null))
                            .collect(Collectors.toList());
                    respVO.setApplicationNames(appNameList);

                    respVO.setApplicationCount(applicationIds.size());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                PromptTemplatesBackupDO backupDO = this.promptTemplatesBackupService.getPromptTemplatesBackupBySrcId(respVO.getId());
                if (backupDO == null) {
                    respVO.setIsBackup(false);
                } else {
                    respVO.setIsBackup(true);
                    respVO.setBackupId(backupDO.getId());
                }
            } catch (Exception e) {
                respVO.setIsBackup(false);
            }

            StringBuilder append = new StringBuilder();
            String categoryName = this.dictDataApi.getDictDataLabel("llm_prompt_template_framework",Integer.valueOf(respVO
                    .getTemplateFramework()));
            switch (categoryName) {
                case "简介框架":
                    BriefFramework briefFramework = JSONObject.parseObject(respVO.getTemplateText(), BriefFramework.class);
                    respVO.setBriefFramework(briefFramework);
                    StringBuilder stringBuilder = new StringBuilder();
                    if(StringUtils.isNotBlank(briefFramework.getOrderInfo())){
                        stringBuilder.append("指令:").append(briefFramework.getOrderInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(briefFramework.getBgInfo())){
                        stringBuilder.append("背景信息:").append(briefFramework.getBgInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(briefFramework.getPlusInfo())){
                        stringBuilder.append("补充数据:").append(briefFramework.getPlusInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(briefFramework.getOutputFormat())){
                        stringBuilder.append("输出格式:").append(briefFramework.getOutputFormat()).append("/n");
                    }

                    append = new StringBuilder(stringBuilder.toString());
                    break;
                case "角色能力框架":
                    AbilityFramework abilityFramework = JSONObject.parseObject(respVO.getTemplateText(), AbilityFramework.class);
                    respVO.setAbilityFramework(abilityFramework);
                    StringBuilder stringBuilder1 = new StringBuilder();
                    if(StringUtils.isNotBlank(abilityFramework.getOrderInfo())){
                        stringBuilder1.append("指令:").append(abilityFramework.getOrderInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(abilityFramework.getBgInfo())){
                        stringBuilder1.append("背景信息:").append(abilityFramework.getBgInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(abilityFramework.getAbilityInfo())){
                        stringBuilder1.append("能力与角色:").append(abilityFramework.getAbilityInfo()).append("/n");
                    }

                    if(StringUtils.isNotBlank(abilityFramework.getOutputFormat())){
                        stringBuilder1.append("输出格式:").append(abilityFramework.getOutputFormat()).append("/n");
                    }

                    append = new StringBuilder(stringBuilder1.toString());

                    break;
                case "样例提示框架":
                    SampleFramework sampleFramework = JSONObject.parseObject(respVO.getTemplateText(), SampleFramework.class);
                    respVO.setSampleFramework(sampleFramework);

                    if(StringUtils.isNotBlank(sampleFramework.getBgInfo())){
                        append = new StringBuilder("背景信息" + sampleFramework.getBgInfo() + "/n" +
                                                   "样例列表:" + "/n");
                    }

                    if(sampleFramework.getItemList() != null && !sampleFramework.getItemList().isEmpty()){
                        for (SampleFrameworkItem sampleFrameworkItem : sampleFramework.getItemList()) {
                            append.append("输入:").append(sampleFrameworkItem.getInput()).append(",").append("输出:").append(sampleFrameworkItem.getOutput()).append("/n");
                        }
                    }

                    break;
                default:
                    append = new StringBuilder(respVO.getTemplateText());
                    break;
            }
            respVO.setTemplateText(append.toString());
        }
        return pageRespList;
    }

    @Override
    public void exportPromptTemplatesExcel (PromptTemplatesPageReqVO pageReqVO,
                                            HttpServletResponse response) throws Exception {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PromptTemplatesRespVO> list = this.getPromptTemplatesPage(pageReqVO).getList();
        List<PromptTemplatesExcelVO> excelList = BeanUtils.toBean(list, PromptTemplatesExcelVO.class);
        for (PromptTemplatesExcelVO excelVO : excelList) {
            try {
                excelVO.setTemplateCategoryDisplay(this.dictDataApi
                        .getDictDataLabel(Long.valueOf(excelVO.getTemplateCategory().toString())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                List<PromptTemplatesTagsDO> tagDOList = this.promptTemplatesTagsMapper
                        .selectList("prompt_template_id", excelVO.getId());
                if (tagDOList != null && !tagDOList.isEmpty()) {
                    excelVO.setTag(tagDOList.stream()
                            .map(p -> this.labelService.getLabel(p.getTagId()))
                            .filter(Objects::nonNull)
                            .map(LabelDO::getLabelName)
                            .collect(Collectors.joining(";")));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ExcelUtils.write(response, "Prompt模板信息.xls", "数据",
                PromptTemplatesExcelVO.class, excelList);
    }

    @Override
    public void backupPromptTemplates (PromptTemplatesSaveReqVO updateReqVO) {
        PromptTemplatesDO templatesDo = this.promptTemplatesMapper.selectById(updateReqVO.getId());
        if (templatesDo == null) {
            throw exception(PROMPT_TEMPLATES_NOT_EXISTS);
        }
        if (templatesDo.getBackupId() != null && templatesDo.getBackupId() != 0) {
            throw exception(new ErrorCode(500, "已存在备份，不能再备份"));
        }
        this.promptTemplatesBackupService.isBackup(updateReqVO.getId());
        PromptTemplatesBackupSaveReqVO templatesBackupDo = BeanUtils.toBean(templatesDo, PromptTemplatesBackupSaveReqVO.class);
        templatesBackupDo.setId(null);
        templatesBackupDo.setSrcId(updateReqVO.getId());
        Long promptTemplatesBackup = this.promptTemplatesBackupService.createPromptTemplatesBackup(templatesBackupDo);
        PromptTemplatesDO promptTemplatesDO = new PromptTemplatesDO();
        promptTemplatesDO.setBackupId(promptTemplatesBackup);
        promptTemplatesDO.setId(updateReqVO.getId());
        promptTemplatesMapper.updateById(promptTemplatesDO);
    }

    @Override
    public void unbackupPromptTemplates (PromptTemplatesSaveReqVO updateReqVO) {
        PromptTemplatesDO templatesDo = this.promptTemplatesMapper.selectById(updateReqVO.getId());
        Long backupId = templatesDo.getBackupId();
        promptTemplatesBackupService.deletePromptTemplatesBackup(backupId);
        PromptTemplatesDO promptTemplatesDO = new PromptTemplatesDO();
        promptTemplatesDO.setBackupId(0l);
        promptTemplatesDO.setId(updateReqVO.getId());
        promptTemplatesMapper.updateById(promptTemplatesDO);
    }

    @Override
    public void updatePromptTemplatesById (PromptTemplatesDO promptTemplatesDO) {
        promptTemplatesMapper.updateById(promptTemplatesDO);
    }

    /**
     * Prompt优化
     *
     * @param reqVO reqVO
     * @return 优化后的内容
     */
    @Override
    public String optimizePrompt (OptimizePromptReqVO reqVO) {
        String resultData = HttpUtils.post(llmBackendProperties.getOptimizePrompt(), null, JSON.toJSONString(reqVO));
        if (StringUtils.isBlank(resultData)) {
            log.error("prompt优化失败:{}", OPTIMIZE_PROMPT_NOT_EXISTS.getMsg());
            throw exception(OPTIMIZE_PROMPT_NOT_EXISTS);
        }

        JSONObject jsonData = JSONObject.parseObject(resultData);
        JSONObject optimizedPrompt = jsonData.getJSONObject("optimized_prompt");

        if (optimizedPrompt == null) {
            log.error("prompt优化失败:{}", OPTIMIZE_PROMPT_NOT_EXISTS.getMsg());
            throw exception(OPTIMIZE_PROMPT_NOT_EXISTS);
        }

        String content = optimizedPrompt.getString("content");
        if (StringUtils.isBlank(content)) {
            log.error("prompt优化失败:{}", OPTIMIZE_PROMPT_NOT_EXISTS.getMsg());
            throw exception(OPTIMIZE_PROMPT_NOT_EXISTS);
        }

        return content;
    }

    /**
     * 根据 标签id 获取 模版
     *
     * @param labelId 标签id
     * @return 模版
     */
    @Override
    public Map<Long, String> getPromptTemplateByLabelId (Long labelId) {
        if (labelId == null) {
            return Collections.emptyMap();
        }

        List<PromptTemplatesDO> templatesDO = this.promptTemplatesMapper.getPromptTemplateByLabelId(labelId);
        if (CollectionUtils.isEmpty(templatesDO)) {
            return Collections.emptyMap();
        }

        return templatesDO.stream().collect(Collectors.toMap(PromptTemplatesDO::getId, PromptTemplatesDO::getName));
    }

    /**
     * 根据 应用id 获取 模版
     *
     * @param applicationId 应用id
     * @return 模版
     */
    @Override
    public Map<Long, String> getPromptTemplateByAppId (Long applicationId) {
        if (applicationId == null) {
            return Collections.emptyMap();
        }

        List<PromptTemplatesDO> templatesDO = this.promptTemplatesMapper.getPromptTemplateByAppId(applicationId);
        if (CollectionUtils.isEmpty(templatesDO)) {
            return Collections.emptyMap();
        }

        return templatesDO.stream().collect(Collectors.toMap(PromptTemplatesDO::getId, PromptTemplatesDO::getName));
    }
}
