package cn.com.poc.law.extractEntityStrategy.extractEntityType;
import cn.com.poc.thirdparty.resource.demand.ai.entity.legal.Item;
import com.google.common.collect.Lists;
import cn.com.poc.law.entity.BizAiLawyerWritingTemplateDownloadEntity;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.PlaintiffOrg;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.FactsAndReasons;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.Preservation;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.ThirdPartyOrg;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.ThirdParty;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.Plaintiff;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.Claim;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.DefendantOrg;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.Defendant;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.UnderstandsMediationBenefit;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.Agent;

import cn.com.poc.law.extractEntityStrategy.TestEntity;
import cn.com.poc.law.extractEntityStrategy.download.MotorVehicleDrivingComplaintItem;

import cn.com.poc.agent_application.entity.BizAgentApplicationGcConfigEntity;
import cn.com.poc.agent_application.service.BizAgentApplicationGcConfigService;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.law.entity.motorVehicleDrivingComplaint.*;
import cn.com.poc.law.extractEntityStrategy.ExtractEntityStrategy;
import cn.com.poc.law.dto.LegalTemplateDto;
import cn.com.poc.law.extractEntityStrategy.download.MotorVehicleDrivingComplaintDownload;
import cn.com.poc.law.service.BizAiLawyerWritingTemplateDownloadService;
import cn.com.poc.thirdparty.resource.demand.ai.aggregate.LegalService;
import cn.com.poc.thirdparty.resource.demand.ai.constants.LLMRoleEnum;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Message;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelResponse;
import cn.com.poc.thirdparty.resource.demand.ai.entity.legal.LegalFileResponse;
import cn.com.poc.thirdparty.resource.demand.ai.entity.legal.LegalFileResult;
import cn.com.poc.thirdparty.service.LLMService;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.hutool.core.util.ObjectUtil;
import com.tencent.core.utils.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.*;

/**
 * @Author：Roger Wu
 * @name：NonMotorVehicleDriving
 * @Date：2025-08-08 10:56
 */
@Service
public class MotorVehicleDrivingComplaintType implements ExtractEntityStrategy {

    final private ThreadPoolExecutor executor = new ThreadPoolExecutor(16, 64, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));

    @Resource
    BizAgentApplicationGcConfigService bizAgentApplicationGcConfigService;

    @Resource
    LLMService llmService;

    @Resource
    BizAiLawyerWritingTemplateDownloadService bizAiLawyerWritingTemplateDownloadService;

    @Resource
    LegalService legalService;


    /**
     * 提取实体
     *
     * @return
     */
    @Override
    public LegalTemplateDto extractEntity(String input) throws Exception {

        CompletableFuture<Plaintiff> extractPlaintiffFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractPlaintiff(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new Plaintiff();
        });
//
        CompletableFuture<PlaintiffOrg> extractPlaintiffOrgFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractPlaintiffOrg(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new PlaintiffOrg();
        });
//
        CompletableFuture<Agent> extractAgentFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractAgent(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new Agent();
        });

        CompletableFuture<Defendant> extractDefendantFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractDefendant(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new Defendant();
        });

        CompletableFuture<DefendantOrg> extractDefendantOrgFuture = CompletableFuture

                .supplyAsync(() -> {
                    try {
                        return extractDefendantOrg(input);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }, executor).exceptionally(ex -> {
                    return new DefendantOrg();
                });


        CompletableFuture<ThirdParty> extractThirdPartyFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractThirdParty(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new ThirdParty();
        });

        CompletableFuture<ThirdPartyOrg> extractThirdPartyOrgFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractThirdPartyOrg(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new ThirdPartyOrg();
        });

        CompletableFuture<Claim> extractClaimFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractClaim(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new Claim();
        });

        CompletableFuture<Preservation> extractPreservationFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractPreservation(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new Preservation();
        });

        CompletableFuture<FactsAndReasons> extractFactsAndReasonsFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractFactsAndReasons(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new FactsAndReasons();
        });

        CompletableFuture<UnderstandsMediationBenefit> extractUnderstandsMediationBenefitFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return extractUnderstandsMediationBenefit(input);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor).exceptionally(ex -> {
            return new UnderstandsMediationBenefit();
        });

        // 等待所有任务完成并获取结果
        CompletableFuture.allOf(extractPlaintiffFuture, extractPlaintiffOrgFuture, extractAgentFuture, extractDefendantFuture, extractDefendantOrgFuture, extractThirdPartyFuture, extractThirdPartyOrgFuture, extractClaimFuture, extractPreservationFuture, extractFactsAndReasonsFuture, extractUnderstandsMediationBenefitFuture).join();
//
        Plaintiff extractPlaintiffResults = extractPlaintiffFuture.get();
        PlaintiffOrg extractPlaintiffOrgResults = extractPlaintiffOrgFuture.get();
        Agent extractAgentResults = extractAgentFuture.get();
        Defendant extractDefendantResult = extractDefendantFuture.get();
        DefendantOrg extractDefendantOrgResult = extractDefendantOrgFuture.get();
        ThirdParty extractThirdPartyResult = extractThirdPartyFuture.get();
        ThirdPartyOrg extractThirdPartyOrgResult = extractThirdPartyOrgFuture.get();
        Claim extractClaimResult = extractClaimFuture.get();
        Preservation preservationResult = extractPreservationFuture.get();
        FactsAndReasons factsAndReasonsResult = extractFactsAndReasonsFuture.get();
        UnderstandsMediationBenefit UnderstandsMediationBenefitResult = extractUnderstandsMediationBenefitFuture.get();

        MotorVehicleDrivingComplaintEntity motorVehicleDrivingComplaintEntity = new MotorVehicleDrivingComplaintEntity();
        motorVehicleDrivingComplaintEntity.setPlaintiff(extractPlaintiffResults);
        motorVehicleDrivingComplaintEntity.setPlaintiffOrg(extractPlaintiffOrgResults);
        motorVehicleDrivingComplaintEntity.setAgent(extractAgentResults);
        motorVehicleDrivingComplaintEntity.setDefendant(extractDefendantResult);
        motorVehicleDrivingComplaintEntity.setDefendantOrg(extractDefendantOrgResult);
        motorVehicleDrivingComplaintEntity.setThirdParty(extractThirdPartyResult);
        motorVehicleDrivingComplaintEntity.setThirdPartyOrg(extractThirdPartyOrgResult);
        motorVehicleDrivingComplaintEntity.setClaim(extractClaimResult);
        motorVehicleDrivingComplaintEntity.setPreservation(preservationResult);
        motorVehicleDrivingComplaintEntity.setFactsAndReasons(factsAndReasonsResult);
        motorVehicleDrivingComplaintEntity.setUnderstandsMediationBenefit(UnderstandsMediationBenefitResult);

        return motorVehicleDrivingComplaintEntity;
    }

    /**
     * 下载文件
     *
     * @param dto 法律模板数据传输对象，包含下载文件所需的信息
     * @return 返回下载文件的路径或文件标识符
     * @throws Exception 当下载过程中发生错误时抛出异常
     */
    @Override
    public String downloadFile(LegalTemplateDto dto) throws Exception {

        String templateFileUrl = "https://gsst-poe-sit.gz.bcebos.com/v1/%E6%B0%91%E9%97%B4%E5%80%9F%E8%B4%B7%E7%BA%A0%E7%BA%B7%E6%B0%91%E4%BA%8B%E8%B5%B7%E8%AF%89%E7%8A%B6.docx";

        BizAiLawyerWritingTemplateDownloadEntity example = new BizAiLawyerWritingTemplateDownloadEntity();
        example.setTemplateCode("MotorVehicleDrivingComplaintType");
        List<BizAiLawyerWritingTemplateDownloadEntity> bizAiLawyerWritingTemplateDownloadEntityList = bizAiLawyerWritingTemplateDownloadService.findByExample(example, null);

        if (CollectionUtils.isEmpty(bizAiLawyerWritingTemplateDownloadEntityList)) {
            new BusinessException("未找到模板参数");
        }

        ArrayList<Item> items = new ArrayList<>();

        bizAiLawyerWritingTemplateDownloadEntityList = getValue((MotorVehicleDrivingComplaintEntity)dto, bizAiLawyerWritingTemplateDownloadEntityList);

        for (BizAiLawyerWritingTemplateDownloadEntity bizAiLawyerWritingTemplateDownloadEntity : bizAiLawyerWritingTemplateDownloadEntityList) {
            Item item = new Item();
            item.setKey(bizAiLawyerWritingTemplateDownloadEntity.getName());
            item.setValue(Arrays.asList(bizAiLawyerWritingTemplateDownloadEntity.getValue()));
            item.setType(bizAiLawyerWritingTemplateDownloadEntity.getType());
            if(StringUtils.isNotBlank(bizAiLawyerWritingTemplateDownloadEntity.getOption())){
                String[] split = bizAiLawyerWritingTemplateDownloadEntity.getOption().split(",");
                item.setOptions(Arrays.asList(split));
            }
            items.add(item);
        }

        LegalFileResponse response= new LegalFileResponse();
        response.setItems(items);
        response.setFilePath(templateFileUrl);
        LegalFileResult legalFileResult = legalService.legalFile(response);

        return legalFileResult.getFilePath();
    }

    public static List<BizAiLawyerWritingTemplateDownloadEntity> getValue( MotorVehicleDrivingComplaintEntity motorVehicleDrivingComplaintEntity, List<BizAiLawyerWritingTemplateDownloadEntity> bizAiLawyerWritingTemplateDownloadEntityList) throws Exception {
//        MotorVehicleDrivingComplaintEntity motorVehicleDrivingComplaintEntity = (MotorVehicleDrivingComplaintEntity) dto;

        // 获取MotorVehicleDrivingComplaintEntity类的所有属性
        Field[] fields = MotorVehicleDrivingComplaintEntity.class.getDeclaredFields();

        Map<String, Object> entityMap = new HashMap<>();

        // 将所有实体属性放入map中，方便后续查找
        for (Field field : fields) {
            field.setAccessible(true); // 设置可访问私有属性
            String fieldName = field.getName();
            Object fieldValue = field.get(motorVehicleDrivingComplaintEntity);
            entityMap.put(fieldName, fieldValue);
        }

        for (BizAiLawyerWritingTemplateDownloadEntity testEntity : bizAiLawyerWritingTemplateDownloadEntityList) {
            if("checkbox".equals(testEntity.getType())){
                try {
                    // 获取TestEntity中指定的类名
                    String targetEntityClass = testEntity.getEntityClass();

                    // 根据entityClass找到对应的实体对象
                    Object sourceEntity = findEntityObject(targetEntityClass, entityMap);

                    if (sourceEntity != null) {
                        // 获取属性值
                        Class<?> sourceClass = sourceEntity.getClass();
                        String fieldName = testEntity.getName();

                        // 构造getter方法名
                        String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                        // 调用getter方法获取值
                        Method getterMethod = sourceClass.getMethod(getterName);
                        Object fieldValue = getterMethod.invoke(sourceEntity);
                        System.out.println("属性 " + fieldName + " 的值为: " + fieldValue);
                        testEntity.setValue((String)fieldValue);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if("text".equals(testEntity.getType())){
                try {
                    // 获取TestEntity中指定的类名
                    String targetEntityClass = testEntity.getEntityClass();

                    // 根据entityClass找到对应的实体对象
                    Object sourceEntity = findEntityObject(targetEntityClass, entityMap);

                    if (sourceEntity != null) {
                        // 获取属性值
                        Class<?> sourceClass = sourceEntity.getClass();
                        String fieldName = testEntity.getName();

                        // 构造getter方法名
                        String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                        // 调用getter方法获取值
                        Method getterMethod = sourceClass.getMethod(getterName);
                        Object fieldValue = getterMethod.invoke(sourceEntity);
                        System.out.println("属性 " + fieldName + " 的值为: " + fieldValue);
                        testEntity.setValue(fieldValue==null?" ":(String)fieldValue);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return bizAiLawyerWritingTemplateDownloadEntityList;
    }

    // 根据类名在entityMap中查找对应的实体对象
    private static Object findEntityObject(String entityClassName, Map<String, Object> entityMap) {
        // 从类名中提取简单类名，例如从"cn.com.poc.law.entity.motorVehicleDrivingComplaint.Plaintiff"
        // 提取"Plaintiff"并转换为属性名"plaintiff"
        String simpleClassName = entityClassName.substring(entityClassName.lastIndexOf('.') + 1);
        String propertyName = Character.toLowerCase(simpleClassName.charAt(0)) + simpleClassName.substring(1);
        return entityMap.get(propertyName);
    }

    private Plaintiff extractPlaintiff(String input) throws Exception {

        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptPlaintiff";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);


        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        Plaintiff plaintiff = new Plaintiff();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        plaintiff = JsonUtils.deSerialize(message, Plaintiff.class);
        if (ObjectUtil.isEmpty(plaintiff)) {
            throw new BusinessException("提取失败");
        }
        return plaintiff;

    }

    private PlaintiffOrg extractPlaintiffOrg(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptPlaintiffOrg";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        PlaintiffOrg plaintiffOrg = new PlaintiffOrg();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        plaintiffOrg = JsonUtils.deSerialize(message, PlaintiffOrg.class);
        if (ObjectUtil.isEmpty(plaintiffOrg)) {
            throw new BusinessException("提取失败");
        }
        return plaintiffOrg;
    }

    private Agent extractAgent(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptAgent";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        Agent agent = new Agent();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        agent = JsonUtils.deSerialize(message, Agent.class);
        if (ObjectUtil.isEmpty(agent)) {
            throw new BusinessException("提取失败");
        }
        return agent;
    }


    private Defendant extractDefendant(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptDefendant";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        Defendant defendant = new Defendant();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        defendant = JsonUtils.deSerialize(message, Defendant.class);
        if (ObjectUtil.isEmpty(defendant)) {
            throw new BusinessException("提取失败");
        }
        return defendant;
    }


    private DefendantOrg extractDefendantOrg(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptDefendantOrg";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        DefendantOrg defendantOrg = new DefendantOrg();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        defendantOrg = JsonUtils.deSerialize(message, DefendantOrg.class);
        if (ObjectUtil.isEmpty(defendantOrg)) {
            throw new BusinessException("提取失败");
        }
        return defendantOrg;
    }

    private ThirdParty extractThirdParty(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptThirdParty";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        ThirdParty thirdParty = new ThirdParty();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        thirdParty = JsonUtils.deSerialize(message, ThirdParty.class);
        if (ObjectUtil.isEmpty(thirdParty)) {
            throw new BusinessException("提取失败");
        }
        return thirdParty;
    }

    private ThirdPartyOrg extractThirdPartyOrg(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptThirdPartyOrg";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        ThirdPartyOrg thirdPartyOrg = new ThirdPartyOrg();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        thirdPartyOrg = JsonUtils.deSerialize(message, ThirdPartyOrg.class);
        if (ObjectUtil.isEmpty(thirdPartyOrg)) {
            throw new BusinessException("提取失败");
        }
        return thirdPartyOrg;
    }

    private Claim extractClaim(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptClaim";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        Claim claim = new Claim();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        claim = JsonUtils.deSerialize(message, Claim.class);
        if (ObjectUtil.isEmpty(claim)) {
            throw new BusinessException("提取失败");
        }
        return claim;
    }

    private Preservation extractPreservation(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptPreservation";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        Preservation preservation = new Preservation();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        preservation = JsonUtils.deSerialize(message, Preservation.class);
        if (ObjectUtil.isEmpty(preservation)) {
            throw new BusinessException("提取失败");
        }
        return preservation;
    }

    private FactsAndReasons extractFactsAndReasons(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptFactsAndReasons";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        FactsAndReasons factsAndReasons = new FactsAndReasons();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        factsAndReasons = JsonUtils.deSerialize(message, FactsAndReasons.class);
        if (ObjectUtil.isEmpty(factsAndReasons)) {
            throw new BusinessException("提取失败");
        }
        return factsAndReasons;
    }

    private UnderstandsMediationBenefit extractUnderstandsMediationBenefit(String input) throws Exception {
        // 获取对话提示词
        String promptCode = "AILawyerWritingPromptUnderstandsMediationBenefit";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            throw new BusinessException("获取对话提示词失败");
        }

        String prompt = documentDialoguePrompt.getConfigSystem().replace("${input}", input);

        //组装请求参数
        List<Message> messages = buildMessages(input, null, prompt);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");//获取模型);
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(false);
        LargeModelDemandResult chat = llmService.chat(largeModelResponse);
        UnderstandsMediationBenefit understandsMediationBenefit = new UnderstandsMediationBenefit();
        if (ObjectUtil.isEmpty(chat) || !chat.getCode().equals("0")) {
            throw new BusinessException("获取失败");
        }
        String message = chat.getMessage().replaceAll("```json", StringUtils.EMPTY).replaceAll("```", StringUtils.EMPTY);
        understandsMediationBenefit = JsonUtils.deSerialize(message, UnderstandsMediationBenefit.class);
        if (ObjectUtil.isEmpty(understandsMediationBenefit)) {
            throw new BusinessException("提取失败");
        }
        return understandsMediationBenefit;
    }


    private List<Message> buildMessages(String input, String fileUrl, String prompt) throws Exception {


        // 加载文件
        String fileContent = StringUtils.EMPTY;
        if (StringUtils.isNoneBlank(fileUrl)) {
            File file = DocumentLoad.downloadURLDocument(fileUrl);
            fileContent = DocumentLoad.documentToText(file);
        }

        // 加载对话提示词
//        String prompt = documentDialoguePrompt.getConfigSystem();
//        if (CollectionUtils.isNotEmpty(knowledgeContentResults)) {
//            String knowledgeContent = JsonUtils.serialize(knowledgeContentResults);
//            prompt = prompt.replace("${knowledgeContent}", knowledgeContent);
//        } else {
//            prompt = prompt.replace("${knowledgeContent}", StringUtils.EMPTY);
//        }
//        if (toolFunction != null) {
//            prompt = prompt.replace("${toolFunction}", JsonUtils.serialize(toolFunction));
//        }
//
//        prompt = prompt.replace("${question}", input).replace("${fileContent}", fileContent);

        // 配置message
        List<Message> messages = new ArrayList<>();
        Message systemMessage = new Message();
        systemMessage.setContent(prompt);
        systemMessage.setRole(LLMRoleEnum.SYSTEM.getRole());
        messages.add(systemMessage);


        // 用户输入
        Message message = new Message();
        message.setContent("请根据要求提取");
        message.setRole(LLMRoleEnum.USER.getRole());
        messages.add(message);
//        logger.info("--------- Build Messages dialogsId:{},messages:{}--------------", dialogsId, messages);
        return messages;
    }

}
