package cn.com.poc.law.service.impl;

import cn.com.poc.agent_application.entity.BizAgentApplicationDialoguesRecordEntity;
import cn.com.poc.agent_application.entity.BizAgentApplicationGcConfigEntity;
import cn.com.poc.agent_application.service.BizAgentApplicationDialoguesRecordService;
import cn.com.poc.agent_application.service.BizAgentApplicationGcConfigService;
import cn.com.poc.ai_dialogues.entity.BizAiDialoguesEntity;
import cn.com.poc.ai_dialogues.service.BizAiDialoguesService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.law.entity.legislativeDocument.LegislativeDocumentResult;
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.service.LLMService;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import cn.com.poc.law.service.BizAiLegislativeDocumentWritingService;
import cn.com.poc.law.model.BizAiLegislativeDocumentWritingModel;
import cn.com.poc.law.entity.BizAiLegislativeDocumentWritingEntity;
import cn.com.poc.law.convert.BizAiLegislativeDocumentWritingConvert;
import cn.com.poc.law.repository.BizAiLegislativeDocumentWritingRepository;
import cn.com.yict.framemax.data.model.PagingInfo;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import org.apache.commons.collections4.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.util.Assert;

@Service
public class BizAiLegislativeDocumentWritingServiceImpl extends BaseServiceImpl implements BizAiLegislativeDocumentWritingService {

    @Resource
    private BizAiLegislativeDocumentWritingRepository repository;
    @Resource
    private BizAiDialoguesService bizAiDialoguesService;
    @Resource
    private LLMService llmService;
    @Resource
    private BizAgentApplicationDialoguesRecordService bizAgentApplicationDialoguesRecordService;
    @Resource
    private BizAgentApplicationGcConfigService bizAgentApplicationGcConfigService;
    @Resource
    private BizAiLegislativeDocumentWritingService bizAiLegislativeDocumentWritingService;

    private static final Logger logger = LoggerFactory.getLogger(BizAiLegislativeDocumentWritingServiceImpl.class);


    public BizAiLegislativeDocumentWritingEntity get(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        BizAiLegislativeDocumentWritingModel model = this.repository.get(id);
        if (model == null) {
            return null;
        }
        if ("Y".equals(model.getIsDeleted())) {
            return null;
        }
        return BizAiLegislativeDocumentWritingConvert.modelToEntity(model);
    }


    public List<BizAiLegislativeDocumentWritingEntity> findByExample(BizAiLegislativeDocumentWritingEntity example, PagingInfo pagingInfo) throws Exception {
        List<BizAiLegislativeDocumentWritingEntity> result = new ArrayList<BizAiLegislativeDocumentWritingEntity>();
        BizAiLegislativeDocumentWritingModel model = new BizAiLegislativeDocumentWritingModel();
        if (example != null) {
            model = BizAiLegislativeDocumentWritingConvert.entityToModel(example);
        }
        model.setIsDeleted("N");
        List<BizAiLegislativeDocumentWritingModel> models = this.repository.findByExample(model, pagingInfo);
        if (CollectionUtils.isNotEmpty(models)) {
            result = models.stream().map(BizAiLegislativeDocumentWritingConvert::modelToEntity).collect(Collectors.toList());
        }
        return result;
    }

    public BizAiLegislativeDocumentWritingEntity save(BizAiLegislativeDocumentWritingEntity entity) throws Exception {
        Assert.notNull(entity);
        entity.setLegislativeDocumentWritingId(null);
        entity.setIsDeleted("N");
        BizAiLegislativeDocumentWritingModel model = BizAiLegislativeDocumentWritingConvert.entityToModel(entity);
        BizAiLegislativeDocumentWritingModel saveModel = this.repository.save(model);
        return BizAiLegislativeDocumentWritingConvert.modelToEntity(saveModel);
    }

    public BizAiLegislativeDocumentWritingEntity update(BizAiLegislativeDocumentWritingEntity entity) throws Exception {
        Assert.notNull(entity);
        Assert.notNull(entity.getLegislativeDocumentWritingId(), "update pk can not be null");
        BizAiLegislativeDocumentWritingModel model = this.repository.get(entity.getLegislativeDocumentWritingId());

        if (entity.getLegislativeDocumentWritingDialoguesId() != null) {
            model.setLegislativeDocumentWritingDialoguesId(entity.getLegislativeDocumentWritingDialoguesId());
        }
        if (entity.getLegislativeDocumentWritingDialoguesData() != null) {
            model.setLegislativeDocumentWritingDialoguesData(entity.getLegislativeDocumentWritingDialoguesData());
        }
        if (entity.getIsDeleted() != null) {
            model.setIsDeleted(entity.getIsDeleted());
        }
        if (entity.getCreator() != null) {
            model.setCreator(entity.getCreator());
        }
        if (entity.getCreatedTime() != null) {
            model.setCreatedTime(entity.getCreatedTime());
        }
        if (entity.getModifier() != null) {
            model.setModifier(entity.getModifier());
        }
        if (entity.getModifiedTime() != null) {
            model.setModifiedTime(entity.getModifiedTime());
        }
        if (entity.getSysVersion() != null) {
            model.setSysVersion(entity.getSysVersion());
        }
        BizAiLegislativeDocumentWritingModel saveModel = this.repository.save(model);
        return BizAiLegislativeDocumentWritingConvert.modelToEntity(saveModel);
    }

    public void deletedById(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        BizAiLegislativeDocumentWritingModel model = this.repository.get(id);
        if (model != null) {
            if ("N".equals(model.getIsDeleted())) {
                model.setIsDeleted("Y");
                this.repository.save(model);
            }
        }
    }

    @Override
    public LegislativeDocumentResult call(String dialoguesId, String input, String fileUrl, Long userId) throws Exception {
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> bizAiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(bizAiDialoguesEntities)) {
            throw new BusinessException("当前对话不存在");
        }
        BizAiDialoguesEntity aiDialoguesEntity = bizAiDialoguesEntities.get(0);
        if (StringUtils.isBlank(aiDialoguesEntity.getTitle())) {
            aiDialoguesEntity.setTitle(input);
            bizAiDialoguesService.update(aiDialoguesEntity);
        }

        //记录提问时间
        long inputTimestamp = System.currentTimeMillis();

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

        // 保存用户输入记录
        BizAgentApplicationDialoguesRecordEntity inputRecord = new BizAgentApplicationDialoguesRecordEntity();
        inputRecord.setMemberId(userId);
        inputRecord.setContent(input);
        inputRecord.setDialogsId(dialoguesId);
        inputRecord.setRole(LLMRoleEnum.USER.getRole());
        inputRecord.setTimestamp(inputTimestamp);

        // 保存AI回复记录
        BizAgentApplicationDialoguesRecordEntity assistantRecord = new BizAgentApplicationDialoguesRecordEntity();
        assistantRecord.setMemberId(userId);
        assistantRecord.setContent(message);
        assistantRecord.setReasoningContent(null);
        assistantRecord.setDialogsId(dialoguesId);
        assistantRecord.setRole(LLMRoleEnum.ASSISTANT.getRole());
        assistantRecord.setTimestamp(System.currentTimeMillis());

        bizAgentApplicationDialoguesRecordService.save(inputRecord);
        bizAgentApplicationDialoguesRecordService.save(assistantRecord);

        //找出原有的，做替换
        BizAiLegislativeDocumentWritingEntity example = new BizAiLegislativeDocumentWritingEntity();
        example.setLegislativeDocumentWritingDialoguesId(dialoguesId);
        example.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiLegislativeDocumentWritingEntity> bizAiLegislativeDocumentWritingEntities = findByExample(example, null);

        BizAiLegislativeDocumentWritingEntity bizAiLegislativeDocumentWritingEntity = new BizAiLegislativeDocumentWritingEntity();
        bizAiLegislativeDocumentWritingEntity.setLegislativeDocumentWritingDialoguesId(dialoguesId);

        if (CollectionUtils.isNotEmpty(bizAiLegislativeDocumentWritingEntities)) {
            BizAiLegislativeDocumentWritingEntity aiLegislativeDocumentWritingEntity = bizAiLegislativeDocumentWritingEntities.get(0);
            bizAiLegislativeDocumentWritingEntity.setLegislativeDocumentWritingId(aiLegislativeDocumentWritingEntity.getLegislativeDocumentWritingId());
            bizAiLegislativeDocumentWritingEntity.setLegislativeDocumentWritingDialoguesData(JsonUtils.serialize(legislativeDocumentResult));
            bizAiLegislativeDocumentWritingService.update(bizAiLegislativeDocumentWritingEntity);
        } else {
            bizAiLegislativeDocumentWritingEntity.setLegislativeDocumentWritingDialoguesData(JsonUtils.serialize(legislativeDocumentResult));
            bizAiLegislativeDocumentWritingService.save(bizAiLegislativeDocumentWritingEntity);

        }
        return legislativeDocumentResult;
    }

    @Override
    public LegislativeDocumentResult getlegislativeApplyDetail(String dialoguesId, Long userId) throws Exception {
        BizAiLegislativeDocumentWritingEntity example = new BizAiLegislativeDocumentWritingEntity();
        example.setLegislativeDocumentWritingDialoguesId(dialoguesId);
        example.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiLegislativeDocumentWritingEntity> bizAiLegislativeDocumentWritingEntityList = findByExample(example, null);
        if (CollectionUtils.isEmpty(bizAiLegislativeDocumentWritingEntityList)) {
            return null;
        }
        return JsonUtils.deSerialize(bizAiLegislativeDocumentWritingEntityList.get(0).getLegislativeDocumentWritingDialoguesData(), LegislativeDocumentResult.class);

    }

    @Override
    public void saveLegislativeApply(String dialoguesId, LegislativeDocumentResult legislativeDocumentResult) throws Exception {
        cn.com.poc.common.utils.Assert.notBlank(dialoguesId);
        BizAiLegislativeDocumentWritingEntity example = new BizAiLegislativeDocumentWritingEntity();
        example.setLegislativeDocumentWritingDialoguesId(dialoguesId);
        example.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiLegislativeDocumentWritingEntity> bizAiLegislativeDocumentWritingEntityList = findByExample(example, null);
        if (CollectionUtils.isEmpty(bizAiLegislativeDocumentWritingEntityList)) {
            throw new BusinessException("找不到该立案");
        }

        BizAiLegislativeDocumentWritingEntity bizAiLegislativeDocumentWritingEntity = bizAiLegislativeDocumentWritingEntityList.get(0);
        bizAiLegislativeDocumentWritingEntity.setLegislativeDocumentWritingDialoguesData(JsonUtils.serialize(legislativeDocumentResult));
        bizAiLegislativeDocumentWritingService.update(bizAiLegislativeDocumentWritingEntity);
    }

    private List<Message> buildMessages(String dialogsId, Long userId, String input, String fileUrl) throws Exception {
        // 获取对话提示词
        String promptCode = "LegislativeDocumentWriting";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            logger.error("获取对话提示词失败 , configCode:{}", promptCode);
            throw new BusinessException("获取对话提示词失败");
        }

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

        // 加载对话提示词
        String prompt = documentDialoguePrompt.getConfigSystem();

        String inputText = fileContent;

        if (inputText.length() > 25000) {
            inputText = inputText.substring(0, 25000);
        }
        prompt = prompt.replace("${input}", inputText);
        // 配置message
        List<Message> messages = new ArrayList<>();
        Message systemMessage = new Message();
        systemMessage.setContent(prompt);
        systemMessage.setRole(LLMRoleEnum.SYSTEM.getRole());
        messages.add(systemMessage);

        // 对话记录
        BizAgentApplicationDialoguesRecordEntity recordEntity = new BizAgentApplicationDialoguesRecordEntity();
        recordEntity.setDialogsId(dialogsId);
        recordEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        recordEntity.setMemberId(userId);
        List<BizAgentApplicationDialoguesRecordEntity> recordEntities = bizAgentApplicationDialoguesRecordService.findByExample(recordEntity, null);
        if (CollectionUtils.isNotEmpty(recordEntities)) {
            for (BizAgentApplicationDialoguesRecordEntity entity : recordEntities) {
                Message message = new Message();
                message.setContent(entity.getContent());
                message.setRole(entity.getRole());
                messages.add(message);
            }
        }
        //判断最后是否为User，若是则删除。
        if (CollectionUtils.isNotEmpty(messages)) {
            if (LLMRoleEnum.USER.getRole().equals(messages.get(messages.size() - 1).getRole())) {
                Long recordId = recordEntities.get(recordEntities.size() - 1).getId();
                bizAgentApplicationDialoguesRecordService.deletedById(recordId);
                messages.remove(messages.size() - 1);
            }
        }

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


}