package com.seer.teach.mp.app.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mp.app.controller.req.AppMpSignUpActivityReq;
import com.seer.teach.mp.app.controller.req.TestChildCharacterReq;
import com.seer.teach.mp.app.controller.resp.AppChildCharacterResp;
import com.seer.teach.mp.app.controller.resp.AppMpSignUpActivityResp;
import com.seer.teach.mp.app.controller.resp.TestChildCharacterResp;
import com.seer.teach.mp.app.convert.AppMpActivityInfoCollectionConvert;
import com.seer.teach.mp.entity.*;
import com.seer.teach.mp.service.*;
import com.seer.teach.teacher.service.AiModelCallService;
import com.seer.teach.teacher.service.platform.LlmResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;

@RequiredArgsConstructor
@Slf4j
@Service
public class AppParentAgentActivityService implements IAppParentAgentActivityService {

    private final IMpParentAgentActivityRelationService parentAgentActivityRelationService;

    private final IMpActivityInfoCollectionService activityInfoCollectionService;

    private final IMpActivityService activityService;

    private final IMpAgentService agentService;

    private final IMpAgentActivityParticipantService mpAgentActivityParticipantService;

    private final AiModelCallService aiModelCallService;

    private final IMpTestChildCharacterService mpTestChildCharacterService;

    /**
     * 报名活动
     *
     * @param request  报名信息
     * @param parentId 家长ID
     * @return true表示成功，false表示失败
     */
    @Transactional(rollbackFor = Exception.class, timeout = 120)
    public boolean signUpForActivityWithInfo(AppMpSignUpActivityReq request, Integer parentId) {
        Integer agentId = request.getAgentId();
        Integer activityId = request.getActivityId();
        MpActivityEntity activity = activityService.getById(activityId);
        AssertUtils.notNull(activity, ResultCodeEnum.INVALID_ACTIVITY);

        MpAgentEntity agent = agentService.getById(agentId);
        AssertUtils.notNull(agent, ResultCodeEnum.INVALID_AGENT);

        MpAgentActivityParticipantEntity participants = mpAgentActivityParticipantService.getParticipantsByActivityAndAgent(request.getActivityId(), request.getAgentId());
        AssertUtils.notNull(participants, ResultCodeEnum.AGENT_NON_PARTICIPANT_ACTIVE);

        MpParentAgentActivityRelationEntity relation = parentAgentActivityRelationService.getByAgentIdAndActivityIdAndParentId(agentId, activityId, parentId);
        AssertUtils.isNull(relation, ResultCodeEnum.PARENT_ALREADY_SIGN_UP);

        relation = new MpParentAgentActivityRelationEntity();
        relation.setActivityId(activityId);
        relation.setAgentId(agentId);
        relation.setParentId(parentId);
        relation.setActivityName(activity.getActivityName());
        relation.setAgentName(agent.getAgentName());
        relation.setStatus(1);
        relation.setSignUpTime(LocalDateTime.now());
        boolean saved = parentAgentActivityRelationService.save(relation);
        log.info("报名结果：{}，关系ID：{}", saved, relation.getId());

        if (saved) {
            MpActivityInfoCollectionEntity mpActivityInfoCollectionEntity = AppMpActivityInfoCollectionConvert.INSTANCE.convertOne2Entity(request);
            mpActivityInfoCollectionEntity.setRelationId(relation.getId());
            mpActivityInfoCollectionEntity.setParentId(parentId);
            boolean activityInfoCollectionResult = activityInfoCollectionService.save(mpActivityInfoCollectionEntity);
            log.info("活动信息收集结果：{}", activityInfoCollectionResult);
            return activityInfoCollectionResult;
        }
        return false;
    }

    /**
     * 更新活动信息
     *
     * @param request  活动信息
     * @param parentId 家长ID
     * @return true表示成功，false表示失败
     */
    public boolean updateActivityInfo(AppMpSignUpActivityReq request, Integer parentId) {
        MpActivityInfoCollectionEntity entity = activityInfoCollectionService.getById(request.getId());
        if (entity == null) {
            return false;
        }
        Integer agentId = request.getAgentId();
        Integer activityId = request.getActivityId();
        MpParentAgentActivityRelationEntity relation = parentAgentActivityRelationService.getByAgentIdAndActivityIdAndParentId(agentId, activityId, parentId);
        AssertUtils.notNull(relation, ResultCodeEnum.PARENT_NOT_SIGNED_UP);
        entity.setRelationId(relation.getId());
        entity.setParentId(parentId);
        entity.setMobile(request.getMobile());
        entity.setChildName(request.getChildName());
        entity.setChildGender(request.getChildGender());
        entity.setChildBirthDate(request.getChildBirthDate());
        entity.setGrade(request.getGrade());
        entity.setSchool(request.getSchool());
        entity.setRegion(request.getRegion());
        entity.setParentIdentity(request.getParentIdentity());
        entity.setLearningSituation(request.getLearningSituation());
        entity.setWeakSubjectIds(request.getWeakSubjectIds());
        entity.setStrongSubjectIds(request.getStrongSubjectIds());
        boolean updateResult = activityInfoCollectionService.updateById(entity);
        if (updateResult) {
            // 查询性格测试记录，如果存在则删除
            MpTestChildCharacterEntity characterEntity = mpTestChildCharacterService
                    .lambdaQuery()
                    .eq(MpTestChildCharacterEntity::getParentId, parentId)
                    .orderByDesc(MpTestChildCharacterEntity::getCreateTime)
                    .last("LIMIT 1")
                    .one();

            if (characterEntity != null) {
                // 如果存在性格测试记录，则删除
                boolean removeResult = mpTestChildCharacterService.removeById(characterEntity.getId());
                log.info("删除AI测试结果: {}", removeResult);
            } else {
                log.info("未找到家长 {} 的性格测试记录，无需删除", parentId);
            }
        }

        return updateResult;
    }

    /**
     * 取消报名
     *
     * @param id       报名ID
     * @param parentId 家长ID
     * @return true表示成功，false表示失败
     */
    @Transactional(rollbackFor = Exception.class, timeout = 120)
    public boolean cancelSignUp(Integer id, Integer parentId) {
        MpActivityInfoCollectionEntity entity = activityInfoCollectionService.getById(id);
        if (entity == null) {
            return false;
        }
        boolean activityResult = activityInfoCollectionService.removeById(entity);
        if (activityResult) {
            Integer relationId = entity.getRelationId();
            // 查询性格测试记录，如果存在则删除
            MpTestChildCharacterEntity characterEntity = mpTestChildCharacterService
                    .lambdaQuery()
                    .eq(MpTestChildCharacterEntity::getParentId, parentId)
                    .orderByDesc(MpTestChildCharacterEntity::getCreateTime)
                    .last("LIMIT 1")
                    .one();

            if (characterEntity != null) {
                // 如果存在性格测试记录，则删除
                boolean removeResult = mpTestChildCharacterService.removeById(characterEntity.getId());
                log.info("删除AI测试结果: {}", removeResult);
            } else {
                log.info("未找到家长 {} 的性格测试记录，无需删除", parentId);
            }
            
            return parentAgentActivityRelationService.removeById(relationId);
        }
        return false;
    }


    /**
     * 获取报名信息
     *
     * @param agentId    代理商ID
     * @param activityId 活动ID
     * @param parentId   家长ID
     * @return 报名信息
     */
    public AppMpSignUpActivityResp getByActivityIdAndParentId(Integer agentId, Integer activityId, Integer parentId) {
        LambdaQueryWrapper<MpParentAgentActivityRelationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MpParentAgentActivityRelationEntity::getActivityId, activityId)
                .eq(MpParentAgentActivityRelationEntity::getParentId, parentId)
                .eq(MpParentAgentActivityRelationEntity::getStatus, 1)
                .eq(MpParentAgentActivityRelationEntity::getAgentId, agentId);
        MpParentAgentActivityRelationEntity one = parentAgentActivityRelationService.getOne(wrapper);
        if (one == null) {
            log.info("活动不存在或已失效");
            return new AppMpSignUpActivityResp();
        }
        MpActivityInfoCollectionEntity activityInfoCollection = activityInfoCollectionService.getByActivityIdAndParentId(agentId, activityId, parentId);
        return AppMpActivityInfoCollectionConvert.INSTANCE.convert2Resp(activityInfoCollection);
    }

    /**
     * 测试孩子性格
     *
     * @param request  测试请求对象
     * @param parentId 家长ID
     * @return 性格测试结果
     */
    public TestChildCharacterResp testChildCharacter(TestChildCharacterReq request, Integer parentId) {
        log.info("开始测试孩子性格，家长ID: {}，请求参数: {}", parentId, request);

        // 构建AI模型的提示词
        String prompt = buildCharacterTestPrompt(request);

        // 调用AI模型获取性格分析
        LlmResponse response = aiModelCallService.callModel("child_character_analysis", prompt, new HashMap<>(), parentId);

        TestChildCharacterResp result = new TestChildCharacterResp();

        if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
            // 获取AI返回的内容
            String content = response.getChoices().get(0).getMessage().getContent();
            result = parseAiResponse(content);
            result.setConstellation(request.getConstellation());

            // 先查询该家长是否已有性格测试记录，有则更新，无则新增
            MpTestChildCharacterEntity existingEntity = mpTestChildCharacterService
                    .lambdaQuery()
                    .eq(MpTestChildCharacterEntity::getParentId, parentId)
                    .orderByDesc(MpTestChildCharacterEntity::getCreateTime)
                    .last("LIMIT 1")
                    .one();

            // 如果AI调用成功则将测试结果保存到数据库中
            MpTestChildCharacterEntity entity = getCharacterEntity(request, parentId, result);

            boolean saveOrUpdateResult;
            if (existingEntity != null) {
                // 如果存在记录，则更新
                entity.setId(existingEntity.getId());
                saveOrUpdateResult = mpTestChildCharacterService.updateById(entity);
                log.info("更新性格测试结果成功，家长ID: {}", parentId);
            } else {
                // 如果不存在记录，则新增
                saveOrUpdateResult = mpTestChildCharacterService.save(entity);
                log.info("保存性格测试结果成功，家长ID: {}", parentId);
            }

            if (!saveOrUpdateResult) {
                log.error("保存或更新性格测试结果失败，家长ID: {}", parentId);
            }
        } else {
            // 如果AI调用失败，返回默认响应
            result.setCharacterAnalysis("暂时无法分析孩子的性格，请稍后重试。");
            result.setCharacterTraits("未知");
            result.setSuggestions("请尝试重新分析或咨询专业教育专家。");
            result.setCharacterType("待定");
        }

        log.info("性格测试完成，返回结果: {}", result);
        return result;
    }

    private MpTestChildCharacterEntity getCharacterEntity(TestChildCharacterReq request, Integer parentId, TestChildCharacterResp result) {
        MpTestChildCharacterEntity entity = new MpTestChildCharacterEntity();
        entity.setParentId(parentId);
        entity.setConstellation(request.getConstellation());
        entity.setGrade(request.getGrade());
        entity.setChildBirthDate(request.getChildBirthDate());
        entity.setChildGender(request.getChildGender());
        entity.setCharacterType(result.getCharacterType());
        entity.setCharacterAnalysis(result.getCharacterAnalysis());
        entity.setCharacterTraits(result.getCharacterTraits());
        entity.setSuggestions(result.getSuggestions());
        return entity;
    }

    /**
     * 构建性格测试的提示词
     *
     * @param request 请求参数
     * @return 提示词内容
     */
    private String buildCharacterTestPrompt(TestChildCharacterReq request) {

        return "请根据以下孩子信息分析其性格特点，并给出教育建议：\n" +
                "- 性别: " + request.getChildGender() + "\n" +
                "- 出生日期: " + request.getChildBirthDate() + "\n" +
                "- 星座: " + (request.getConstellation() != null ? request.getConstellation() : "未知") + "\n" +
                "- 年级: " + request.getGrade() + "\n" +
                "- 学习情况: " + request.getLearningSituation() + "\n" +
                "- 偏科情况: " + request.getWeakSubject() + "\n" +
                "\n请按照以下格式返回分析结果：\n" +
                "1. 性格分析：[具体分析内容]\n" +
                "2. 性格特征：[关键特征]\n" +
                "3. 教育建议：[针对性建议]\n" +
                "4. 性格类型：[简要分类]";
    }

    /**
     * 解析AI返回的结果
     *
     * @param aiResponse AI返回的原始内容
     * @return 解析后的响应对象
     */
    private TestChildCharacterResp parseAiResponse(String aiResponse) {
        TestChildCharacterResp resp = new TestChildCharacterResp();

        String[] lines = aiResponse.split("\n");
        StringBuilder currentSection = new StringBuilder();
        String currentHeader = null;

        for (String line : lines) {
            // 检查是否为新的章节头部
            if (line.matches("^\\d+\\.\\s*[\\u4e00-\\u9fa5]+：.*|^\\s*[\\u4e00-\\u9fa5]+：.*")) {
                // 保存之前的章节
                if (currentHeader != null && !currentSection.isEmpty()) {
                    setResponseField(resp, currentHeader, currentSection.toString().trim());
                }

                // 开始新章节
                String[] parts = line.split("：", 2);
                if (parts.length >= 2) {
                    currentHeader = parts[0].replaceAll("^\\d+\\.\\s*", "").trim();
                    currentSection = new StringBuilder(parts[1]);
                }
            } else if (currentHeader != null) {
                // 添加到当前章节内容
                if (!currentSection.isEmpty()) {
                    currentSection.append("\n");
                }
                currentSection.append(line.trim());
            }
        }

        // 处理最后一个章节
        if (currentHeader != null && !currentSection.isEmpty()) {
            setResponseField(resp, currentHeader, currentSection.toString().trim());
        }

        if (resp.getCharacterAnalysis() == null || resp.getCharacterAnalysis().isEmpty()) {
            resp.setCharacterAnalysis(aiResponse);
        }

        return resp;
    }

    private void setResponseField(TestChildCharacterResp resp, String header, String content) {
        switch (header) {
            case "性格分析":
                resp.setCharacterAnalysis(content);
                break;
            case "性格特征":
                resp.setCharacterTraits(content);
                break;
            case "教育建议":
                resp.setSuggestions(content);
                break;
            case "性格类型":
                resp.setCharacterType(content);
                break;
        }
    }


    /**
     * 获取孩子性格返回结果
     *
     * @param parentId 家长ID
     * @return 孩子性格返回结果
     */
    public AppChildCharacterResp getChildCharacter(Integer parentId) {
        MpTestChildCharacterEntity one = mpTestChildCharacterService.lambdaQuery()
                .eq(MpTestChildCharacterEntity::getParentId, parentId)
                .orderByDesc(MpTestChildCharacterEntity::getCreateTime)
                .last("limit 1") // 获取最新的一条数据
                .one();
        if (one == null) {
            return new AppChildCharacterResp();
        }
        return AppMpActivityInfoCollectionConvert.INSTANCE.convert2ChildCharacterResp(one);
    }
}