package com.vetti.hotake.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.vetti.common.ai.gpt.ChatGPTClient;
import com.vetti.common.constant.AiCommonPromptConstants;
import com.vetti.common.core.domain.entity.SysUser;
import com.vetti.common.core.service.BaseServiceImpl;
import com.vetti.common.enums.FillTypeEnum;
import com.vetti.common.enums.RoleBenefitsEnum;
import com.vetti.common.exception.ServiceException;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.common.utils.html.ReadHtmlByOkHttp;
import com.vetti.hotake.domain.*;
import com.vetti.hotake.domain.dto.*;
import com.vetti.hotake.domain.dto.VcDto.*;
import com.vetti.hotake.domain.dto.roleDto.*;
import com.vetti.hotake.domain.vo.*;
import com.vetti.hotake.mapper.HotakeAiInterviewQuestionsInfoMapper;
import com.vetti.hotake.mapper.HotakeInitialScreeningQuestionsInfoMapper;
import com.vetti.hotake.mapper.HotakeRolesApplyInfoMapper;
import com.vetti.hotake.mapper.HotakeRolesInfoMapper;
import com.vetti.hotake.service.IHotakeAiCommonToolsService;
import com.vetti.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * AI共通工具 信息Service业务层处理
 *
 * @author wangxiangshun
 * @date 2025-12-14
 */
@Slf4j
@SuppressWarnings("all")
@Service
public class HotakeAiCommonToolsServiceImpl extends BaseServiceImpl implements IHotakeAiCommonToolsService {

    @Autowired
    private HotakeRolesInfoMapper hotakeRolesInfoMapper;

    @Autowired
    private HotakeRolesApplyInfoMapper hotakeRolesApplyInfoMapper;

    @Autowired
    private HotakeInitialScreeningQuestionsInfoMapper hotakeInitialScreeningQuestionsInfoMapper;

    @Autowired
    private HotakeAiInterviewQuestionsInfoMapper hotakeAiInterviewQuestionsInfoMapper;

    @Autowired
    private ChatGPTClient chatGPTClient;

    @Autowired
    private SysUserMapper userMapper;


    /**
     * 职位描述生成器
     *
     * @param roleId           岗位ID
     * @param industry         Industry sector 行业领域
     * @param coreRequirements Key skills or experience requirements 关键技能或经验要求
     * @return
     */
    @Override
    public HotakeJobDescriptionGeneratorDto getJobDescriptionGenerator(Long roleId) {
        HotakeJobDescriptionGeneratorDto generatorDto = new HotakeJobDescriptionGeneratorDto();
        //根据岗位ID查询岗位基本信息
        HotakeRolesInfo rolesInfo = hotakeRolesInfoMapper.selectHotakeRolesInfoById(roleId);
        String prompt = AiCommonPromptConstants.initializationJobDescriptionPrompt(rolesInfo.getRoleName(), rolesInfo.getRoleType(),
                rolesInfo.getRequiredSkillsJson());
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "JD");
        log.info("返回职位描述:{}", resultStr);
        //开始解析职位描述详细信息,主要生成的数据为第二步中的必备技能和优先加分技能,第三步中的关于岗位和职责
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");

        Map dataMap = JSONUtil.toBean(resultJson, Map.class);

        Map aboutRoleMap = (Map) dataMap.get("job_description");
        String aboutRole = aboutRoleMap.get("overview").toString();
        generatorDto.setAboutRole(aboutRole);

        List<Map> keyResponsibilitiesList = (List<Map>) dataMap.get("key_responsibilities");
        List<ResponsibilitiesDto> responsibilitiesList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(keyResponsibilitiesList)) {
            for (Map map : keyResponsibilitiesList) {
                ResponsibilitiesDto responsibilitiesDto = new ResponsibilitiesDto();
                responsibilitiesDto.setResponsibilities(map.get("responsibility").toString());
                responsibilitiesList.add(responsibilitiesDto);
            }
        }
        generatorDto.setResponsibilitiesList(responsibilitiesList);


        Map requirementsMap = (Map) dataMap.get("requirements");

        List<Map> essentialList = (List<Map>) requirementsMap.get("essential");
        List<RequiredSkillsDto> skillsDtoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(essentialList)) {
            for (Map map : essentialList) {
                RequiredSkillsDto skillsDto = new RequiredSkillsDto();
                skillsDto.setKeyValue(map.get("requirement").toString());
                skillsDtoList.add(skillsDto);
            }
        }
        generatorDto.setSkillsDtoList(skillsDtoList);


        List<Map> preferredList = (List<Map>) requirementsMap.get("preferred");
        List<NiceToHaveSkillsDto> haveSkillsDtoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(preferredList)) {
            for (Map map : preferredList) {
                NiceToHaveSkillsDto haveSkillsDto = new NiceToHaveSkillsDto();
                haveSkillsDto.setKeyValue(map.get("requirement").toString());
                haveSkillsDtoList.add(haveSkillsDto);
            }
        }
        generatorDto.setHaveSkillsDtoList(haveSkillsDtoList);

        return generatorDto;
    }

    /**
     * 初筛问题生成
     *
     * @return
     */
    @Override
    public List<HotakeInitialScreeningQuestionsInfo> getInitialScreeningQuestionsGenerator(HotakeInitialScreeningQuestionsVo questionsVo) {
        List<HotakeInitialScreeningQuestionsInfo> questionsInfoList = new ArrayList<>();
        //根据岗位ID查询岗位基本信息
        HotakeRolesInfo rolesInfo = hotakeRolesInfoMapper.selectHotakeRolesInfoById(questionsVo.getRoleId());
        String prompt = AiCommonPromptConstants.initializationInitialScreeningQuestionsPrompt(rolesInfo.getRoleName(), rolesInfo.getAboutRole(),
                rolesInfo.getResponsibilities());
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "ISQ");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("初筛问题生成:{}", resultStr);
        //筛选问题结构化处理-进行初始化问题解析处理
        Map dataMap = JSONUtil.toBean(resultJson, Map.class);

        List<Map> questionsList = (List<Map>) dataMap.get("questions");
        if (CollectionUtil.isNotEmpty(questionsList)) {
            for (Map map : questionsList) {
                HotakeInitialScreeningQuestionsInfo questionsInfo = new HotakeInitialScreeningQuestionsInfo();
                questionsInfo.setQuestionType(map.get("type").toString());
                questionsInfo.setQuestionTitle(map.get("question").toString());
                questionsInfo.setRequiredField("0");
                List<String> optionsList = (List<String>) map.get("options");
                List<AnswerOptionsDto> answerOptionsList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(optionsList)) {
                    for (String option : optionsList) {
                        AnswerOptionsDto answerOptionsDto = new AnswerOptionsDto();
                        answerOptionsDto.setAnswers(option);
                        answerOptionsList.add(answerOptionsDto);
                    }
                }
                if (CollectionUtil.isNotEmpty(answerOptionsList)) {
                    questionsInfo.setAnswerOptions(JSONUtil.toJsonStr(answerOptionsList));
                    questionsInfo.setAnswerOptionsList(answerOptionsList);
                }
                questionsInfoList.add(questionsInfo);
            }
        }
        return questionsInfoList;
    }

    /**
     * 简历岗位匹配度评分
     *
     * @return
     */
    @Override
    public String getResumeJobMatchingScore(HotakeResumeJobMatchingScoreVo scoreVo) {
        //查询岗位信息
        String prompt = AiCommonPromptConstants.initializationResumeJobMatchingScorePrompt(scoreVo.getJobTitle(), scoreVo.getJobDescription(),
                scoreVo.getKeyResponsibilities(), scoreVo.getJobRequirements(), scoreVo.getPersonalInformation(),
                scoreVo.getWorkHistory(), scoreVo.getProjectExperience(), scoreVo.getSkillsList(),
                scoreVo.getEducationalBackground(), scoreVo.getOtherRelevantInformation());

        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "ROLECV");
        log.info("简历岗位匹配度评分:{}", resultStr);

        return "";
    }

    /**
     * 简历分析优化器
     *
     * @param cvConnect 简历内容
     * @return
     */
    @Override
    public HotakeCvOptimizeDto getResumeAnalysisOptimizer(String cvConnect) {
        //传输简历内容,返回简历分析结果
        String prompt = AiCommonPromptConstants.initializationResumeAnalysisOptimizerPrompt();
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", "请分析以下简历并提供优化建议：\\n\\n" + cvConnect);
        list.add(mapUserEntity);

        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "CVJX");
        log.info("简历分析优化器:{}", resultStr);
        HotakeCvOptimizeDto cvOptimizeDto = new HotakeCvOptimizeDto();
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("初筛问题生成:{}", resultStr);
        //筛选问题结构化处理-进行初始化问题解析处理
        Map dataMap = JSONUtil.toBean(resultJson, Map.class);
        if (dataMap != null) {
            //分析总结
            CvAnalysisSummaryDto analysisSummary = new CvAnalysisSummaryDto();
            Map analysisSummaryMap = (Map) dataMap.get("analysis_summary");
            analysisSummary.setOverallScore(analysisSummaryMap.get("overall_score").toString());
            List<String> mainStrengthsList = (List<String>) analysisSummaryMap.get("main_strengths");
            analysisSummary.setMainStrengths(mainStrengthsList);
            List<String> criticalIssuesList = (List<String>) analysisSummaryMap.get("critical_issues");
            analysisSummary.setCriticalIssues(criticalIssuesList);
            analysisSummary.setImprovementPotential(analysisSummaryMap.get("improvement_potential").toString());
            cvOptimizeDto.setAnalysisSummary(analysisSummary);

            //文本修正（文字、语法等错误）
            CvTextCorrectionsDto textCorrections = new CvTextCorrectionsDto();
            Map textCorrectionsMap = (Map) dataMap.get("text_corrections");
            List<CvSpellingErrorsDto> spellingErrors = new ArrayList<>();
            List<Map> spellingErrorsMapList = (List<Map>) textCorrectionsMap.get("spelling_errors");
            if (CollectionUtil.isNotEmpty(spellingErrorsMapList)) {
                for (Map map : spellingErrorsMapList) {
                    CvSpellingErrorsDto spellingErrorsDto = new CvSpellingErrorsDto();
                    spellingErrorsDto.setOriginal(map.get("original").toString());
                    spellingErrorsDto.setCorrected(map.get("corrected").toString());
                    spellingErrorsDto.setLocation(map.get("location").toString());
                    spellingErrors.add(spellingErrorsDto);
                }
                textCorrections.setSpellingErrors(spellingErrors);
            }

            List<CvGrammarErrorsDto> grammarErrors = new ArrayList<>();
            List<Map> grammarErrorsMapList = (List<Map>) textCorrectionsMap.get("grammar_errors");
            if (CollectionUtil.isNotEmpty(grammarErrorsMapList)) {
                for (Map map : grammarErrorsMapList) {
                    CvGrammarErrorsDto grammarErrorsDto = new CvGrammarErrorsDto();
                    grammarErrorsDto.setOriginal(map.get("original").toString());
                    grammarErrorsDto.setCorrected(map.get("corrected").toString());
                    grammarErrorsDto.setLocation(map.get("location").toString());
                    grammarErrorsDto.setExplanation(map.get("explanation").toString());
                    grammarErrors.add(grammarErrorsDto);
                }
                textCorrections.setGrammarErrors(grammarErrors);
            }

            List<CvFormattingIssuesDto> formattingIssues = new ArrayList<>();
            List<Map> formattingIssuesMapList = (List<Map>) textCorrectionsMap.get("formatting_issues");
            if (CollectionUtil.isNotEmpty(formattingIssuesMapList)) {
                for (Map map : formattingIssuesMapList) {
                    CvFormattingIssuesDto formattingIssuesDto = new CvFormattingIssuesDto();
                    formattingIssuesDto.setIssue(map.get("issue").toString());
                    formattingIssuesDto.setSuggestion(map.get("suggestion").toString());
                    List<String> locationList = (List<String>) textCorrectionsMap.get("locations");
                    formattingIssuesDto.setLocations(locationList);
                    formattingIssues.add(formattingIssuesDto);
                }
                textCorrections.setFormattingIssues(formattingIssues);
            }
            cvOptimizeDto.setTextCorrections(textCorrections);

            //逻辑修正
            CvLogicCorrectionsDto logicCorrections = new CvLogicCorrectionsDto();
            Map logicCorrectionsMap = (Map) dataMap.get("logic_corrections");

            List<CvTimelineConflictsDto> timelineConflicts = new ArrayList<>();
            List<Map> timelineConflictsMapList = (List<Map>) textCorrectionsMap.get("timeline_conflicts");
            if (CollectionUtil.isNotEmpty(timelineConflictsMapList)) {
                for (Map map : timelineConflictsMapList) {
                    CvTimelineConflictsDto timelineConflictsDto = new CvTimelineConflictsDto();
                    timelineConflictsDto.setConflict(map.get("conflict").toString());
                    timelineConflictsDto.setDetails(map.get("details").toString());
                    timelineConflictsDto.setSuggestion(map.get("suggestion").toString());
                    timelineConflicts.add(timelineConflictsDto);
                }
                logicCorrections.setTimelineConflicts(timelineConflicts);
            }

            List<CvCareerProgressionDto> careerProgressionDtos = new ArrayList<>();
            List<Map> careerProgressionDtosMapList = (List<Map>) textCorrectionsMap.get("career_progression");
            if (CollectionUtil.isNotEmpty(careerProgressionDtosMapList)) {
                for (Map map : careerProgressionDtosMapList) {
                    CvCareerProgressionDto careerProgressionDto = new CvCareerProgressionDto();
                    careerProgressionDto.setIssue(map.get("issue").toString());
                    careerProgressionDto.setDetails(map.get("details").toString());
                    careerProgressionDto.setSuggestion(map.get("suggestion").toString());
                    careerProgressionDtos.add(careerProgressionDto);
                }
                logicCorrections.setCareerProgressionDtos(careerProgressionDtos);
            }

            List<CvSkillExperienceMismatchDto> skillExperienceMismatchDtos = new ArrayList<>();
            List<Map> skillExperienceMismatchDtosMapList = (List<Map>) textCorrectionsMap.get("formatting_issues");
            if (CollectionUtil.isNotEmpty(skillExperienceMismatchDtosMapList)) {
                for (Map map : skillExperienceMismatchDtosMapList) {
                    CvSkillExperienceMismatchDto skillExperienceMismatchDto = new CvSkillExperienceMismatchDto();
                    skillExperienceMismatchDto.setIssue(map.get("issue").toString());
                    skillExperienceMismatchDto.setSuggestion(map.get("suggestion").toString());
                    skillExperienceMismatchDto.setSkill(map.get("suggestion").toString());
                    skillExperienceMismatchDtos.add(skillExperienceMismatchDto);
                }
                logicCorrections.setSkillExperienceMismatchDtos(skillExperienceMismatchDtos);
            }
            cvOptimizeDto.setLogicCorrections(logicCorrections);

            //优化建议
            CvOptimizationSuggestionsDto optimizationSuggestions = new CvOptimizationSuggestionsDto();
            Map optimizationSuggestionsMap = (Map) dataMap.get("optimization_suggestions");
            CvPersonalSummaryDto personalSummary = new CvPersonalSummaryDto();
            Map personalSummaryMap = (Map) optimizationSuggestionsMap.get("personal_summary");
            if (personalSummaryMap != null) {
                List<String> currentIssues = (List<String>) personalSummaryMap.get("current_issues");
                personalSummary.setCurrentIssues(currentIssues);
                personalSummary.setOptimizedVersion(personalSummaryMap.get("optimized_version").toString());
                List<String> keyImprovements = (List<String>) personalSummaryMap.get("key_improvements");
                personalSummary.setKeyImprovements(keyImprovements);
            }
            optimizationSuggestions.setPersonalSummary(personalSummary);


            List<CvWorkExperienceDto> workExperienceDtoList = new ArrayList<>();
            List<Map> workExperienceMapList = (List<Map>) optimizationSuggestionsMap.get("work_experience");
            if (CollectionUtil.isNotEmpty(workExperienceMapList)) {
                for (Map map : workExperienceMapList) {
                    CvWorkExperienceDto workExperienceDto = new CvWorkExperienceDto();
                    workExperienceDto.setPosition(map.get("position").toString());
                    workExperienceDto.setOptimizedDescription(map.get("optimized_description").toString());
                    workExperienceDto.setCurrentDescription(map.get("current_description").toString());
                    List<String> improvements = (List<String>) personalSummaryMap.get("improvements");
                    workExperienceDto.setImprovements(improvements);
                    workExperienceDtoList.add(workExperienceDto);
                }
                optimizationSuggestions.setWorkExperienceDtoList(workExperienceDtoList);
            }


            CvSkillsSectionDto skillsSection = new CvSkillsSectionDto();
            Map skillsSectionMap = (Map) optimizationSuggestionsMap.get("skills_section");
            if (skillsSectionMap != null) {
                List<String> currentIssues = (List<String>) skillsSectionMap.get("current_issues");
                skillsSection.setCurrentIssues(currentIssues);

                CvSuggestedStructureDto suggestedStructureDto = new CvSuggestedStructureDto();
                Map suggestedStructureDtoMap = (Map) skillsSectionMap.get("suggested_structure");
                List<String> coreSkills = (List<String>) suggestedStructureDtoMap.get("core_skills");
                suggestedStructureDto.setCoreSkills(coreSkills);
                List<String> technicalSkills = (List<String>) suggestedStructureDtoMap.get("technical_skills");
                suggestedStructureDto.setTechnicalSkills(technicalSkills);
                List<String> certifications = (List<String>) suggestedStructureDtoMap.get("certifications");
                suggestedStructureDto.setCertifications(certifications);
                skillsSection.setSuggestedStructureDto(suggestedStructureDto);
            }
            optimizationSuggestions.setSkillsSection(skillsSection);


            CvKeywordOptimizationDto keywordOptimization = new CvKeywordOptimizationDto();
            Map keywordOptimizationMap = (Map) optimizationSuggestionsMap.get("keyword_optimization");
            if (keywordOptimizationMap != null) {
                List<String> atsKeywords = (List<String>) keywordOptimizationMap.get("ats_keywords");
                keywordOptimization.setAtsKeywords(atsKeywords);

                List<String> missingKeywords = (List<String>) keywordOptimizationMap.get("missing_keywords");
                keywordOptimization.setMissingKeywords(missingKeywords);

                List<String> industryTerms = (List<String>) keywordOptimizationMap.get("industry_terms");
                keywordOptimization.setIndustryTerms(industryTerms);
            }
            optimizationSuggestions.setKeywordOptimization(keywordOptimization);

            cvOptimizeDto.setOptimizationSuggestions(optimizationSuggestions);

            //行动计划
            CvActionPlanDto actionPlan = new CvActionPlanDto();
            Map actionPlanMap = (Map) dataMap.get("action_plan");
            if (actionPlanMap != null) {
                List<String> immediateFixes = (List<String>) actionPlanMap.get("immediate_fixes");
                actionPlan.setImmediateFixes(immediateFixes);

                List<String> contentImprovements = (List<String>) actionPlanMap.get("content_improvements");
                actionPlan.setContentImprovements(contentImprovements);

                List<String> strategicEnhancements = (List<String>) actionPlanMap.get("strategic_enhancements");
                actionPlan.setStrategicEnhancements(strategicEnhancements);
            }
            cvOptimizeDto.setActionPlan(actionPlan);

            //预期改进效果
            CvEstimatedImprovementDto estimatedImprovement = new CvEstimatedImprovementDto();
            Map estimatedImprovementMap = (Map) dataMap.get("estimated_improvement");
            if (estimatedImprovementMap != null) {
                estimatedImprovement.setCurrentAtsScore(estimatedImprovementMap.get("current_ats_score").toString());
                estimatedImprovement.setInterviewProbability(estimatedImprovementMap.get("interview_probability").toString());
                estimatedImprovement.setPotentialAtsScore(estimatedImprovementMap.get("potential_ats_score").toString());
                estimatedImprovement.setRecruiterAppeal(estimatedImprovementMap.get("recruiter_appeal").toString());
            }
            cvOptimizeDto.setEstimatedImprovement(estimatedImprovement);
        }

        return cvOptimizeDto;
    }

    /**
     * 初步筛选问题淘汰评分
     *
     * @param cvConnect
     * @return
     */
    @Override
    public HotakeInitialQuestionEliminationScoreDto getInitialQuestionEliminationScore(HotakeInitialQuestionEliminationScoreVo questionEliminationScoreVo) {
        HotakeInitialQuestionEliminationScoreDto dto = new HotakeInitialQuestionEliminationScoreDto();
        //查询岗位对应的初步筛选问题数据集合
        HotakeInitialScreeningQuestionsInfo queryQuestionsInfo = new HotakeInitialScreeningQuestionsInfo();
        queryQuestionsInfo.setRoleId(questionEliminationScoreVo.getRoleId());
        List<HotakeInitialScreeningQuestionsInfo> screeningQuestionsInfoList = hotakeInitialScreeningQuestionsInfoMapper.selectHotakeInitialScreeningQuestionsInfoList(queryQuestionsInfo);

        //提示词处理
        String prompt = AiCommonPromptConstants.initializationQuestionEliminationScorePrompt(questionEliminationScoreVo.getRoleName());
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);

        if (CollectionUtil.isNotEmpty(screeningQuestionsInfoList)) {
            for (HotakeInitialScreeningQuestionsInfo questionsInfo : screeningQuestionsInfoList) {
                //根据问题获取答案数据
                String answer = "";
                if (CollectionUtil.isNotEmpty(questionEliminationScoreVo.getInitScreQuestionsReplyRecordInfoList())) {
                    List<HotakeInitScreQuestionsReplyRecordInfo> initScreQuestionsReplyRecordInfoList = questionEliminationScoreVo.
                            getInitScreQuestionsReplyRecordInfoList().stream().filter(e -> e.getQuestionId().longValue() == questionsInfo.getId().longValue()).toList();
                    if (CollectionUtil.isNotEmpty(initScreQuestionsReplyRecordInfoList)) {
                        answer = initScreQuestionsReplyRecordInfoList.get(0).getAnswerConnect();
                    }
                }
                Map<String, String> mapUserEntity = new HashMap<>();
                mapUserEntity.put("role", "user");
                mapUserEntity.put("content", "question:" + questionsInfo.getQuestionTitle() + ",answer:" + answer);
                list.add(mapUserEntity);
            }
        }
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "CBQPF");
        log.info("初步筛选问题评分数据:{}", resultStr);
        //初步筛选问题评分数据
        dto = JSONUtil.toBean(resultStr, HotakeInitialQuestionEliminationScoreDto.class);
        return dto;
    }

    /**
     * 处理分析附件结果
     *
     * @param connect
     * @return
     */
    @Override
    public String handleAnalyzedAttachment(String connect) {
        //处理提示词数据
        String prompt = AiCommonPromptConstants.initializationAnalyzedAttachmentPrompt();
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", connect);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "AAFX");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        return resultJson;
    }

    /**
     * 处理附件分析结果合并信息
     *
     * @param basicInformation  基础信息
     * @param attachmentContent 所有附件信息
     * @return
     */
    @Override
    public String handleAttachmentResultMerging(String basicInformation, String attachmentContent) {
        //处理提示词数据
        String prompt = AiCommonPromptConstants.initializationAttachmentResultMergingPrompt(basicInformation, attachmentContent);
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", "基本信息：" + basicInformation + "\\n分析结果：" + attachmentContent);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "AAHB");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("处理附件分析结果合并信息:{}", resultJson);
        return resultJson;
    }

    /**
     * 生成最终的Markdown格式简历
     *
     * @param markdown
     * @return
     */
    @Override
    public String handleGenerateMarkdown(String markdown) {
        String prompt = AiCommonPromptConstants.initializationGenerateMarkdownPrompt();
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", markdown);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "MARKDOWN");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("处理附件分析结果合并信息:{}", resultJson);
        return resultJson;
    }


    /**
     * 网站内容抓取
     *
     * @param webUrl 网站链接地址
     * @return
     */
    @Override
    public String handleWebContentScraping(String webUrl) {
        //网站内容抓取
        try {
            String htmlContent = ReadHtmlByOkHttp.getHtmlContentByOkHttp(webUrl);
            String resultStr = ReadHtmlByOkHttp.removeHtmlTagAndAttrByJsoup(htmlContent);
            String resultData = ReadHtmlByOkHttp.removeBlankLineAndSpace(resultStr);
            return resultData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 网站AI信息提取（使用提示词）
     *
     * @param webInfoExtractVo 网站提取对象
     * @return
     */
    @Override
    public String handleWebInfoExtract(HotakeWebInfoExtractVo webInfoExtractVo) {
        //获取
        if (StrUtil.isEmpty(webInfoExtractVo.getWebUrl())) {
            throw new ServiceException("");
        }
        String webUrl = webInfoExtractVo.getWebUrl();
        if (!webInfoExtractVo.getWebUrl().toLowerCase().contains("https")) {
            webUrl = webUrl.replaceAll("http", "https");
        }

        String webContent = handleWebContentScraping(webUrl);

        String prompt = AiCommonPromptConstants.initializationWebInfoExtractPrompt();
        String userPrompt = "Please analyze the following company website:\n" +
                "\n" +
                "URL: " + webUrl + "\n" +
                "\n" +
                "Content:\n" +
                webContent;
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", userPrompt);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "WEBAITQ");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("网站AI信息提取:{}", resultJson);
        //直接更新个人信息中的企业名和地址
        Map dataMap = JSONUtil.toBean(resultJson, Map.class);
        Map companyOverviewMap = (Map) dataMap.get("company_overview");
        String companyName = companyOverviewMap.get("company_name").toString();
        Map contactInfoMap = (Map) companyOverviewMap.get("contact_info");
        String location = contactInfoMap.get("address").toString();

        SysUser user = userMapper.selectUserById(SecurityUtils.getUserId());
        user.setCompanyName(companyName);
        user.setLocation(location);
        userMapper.updateUser(user);
//        String resultData = handleWebInfoEnhancedProcessing(resultJson);
        return resultJson;
    }

    /**
     * 网站信息增强处理
     *
     * @param webUlr
     * @param webContent 网站内容
     * @return
     */
    @Override
    public String handleWebInfoEnhancedProcessing(String webContent) {

        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", "You are a professional HR consultant...\n" +
                "Please enhance and structure the company information...");
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", "Please enhance the following company information:\n" + webContent);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "WEBAITQ");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("网站信息增强处理:{}", resultJson);

        return resultJson;
    }

    /**
     * 个人简介生成器
     *
     * @param personalProfileGeneratorVo 个人信息
     * @return
     */
    @Override
    public HotakePersonalProfileGeneratorDto getPersonalProfileGenerator(HotakePersonalProfileGeneratorVo personalProfileGeneratorVo) {
        String prompt = AiCommonPromptConstants.initializationPersonalProfileGeneratorPrompt();

        String linedIn = "";
        String website = "";
        if (CollectionUtil.isNotEmpty(personalProfileGeneratorVo.getLinks())) {
            List<VcLinksDto> linedInList = personalProfileGeneratorVo.getLinks().stream().filter(e -> "LinkedIn".equals(e.getDataType())).toList();
            if (CollectionUtil.isNotEmpty(linedInList)) {
                linedIn = linedInList.get(0).getContent();
            }
            List<VcLinksDto> websiteList = personalProfileGeneratorVo.getLinks().stream().filter(e -> "Website".equals(e.getDataType())).toList();

            if (CollectionUtil.isNotEmpty(websiteList)) {
                website = websiteList.get(0).getContent();
            }
        }
        String candidateText = " Full Name: " + personalProfileGeneratorVo.getName() + " Birthday: " + personalProfileGeneratorVo.getBirthday() + " Job Position: " + personalProfileGeneratorVo.getPosition()
                + "Location: " + personalProfileGeneratorVo.getLocation() + " Email: " + personalProfileGeneratorVo.getEmail() + " Phone Number: " + personalProfileGeneratorVo.getPhone()
                + "LinkedIn: " + linedIn + " Website: " + website;

        String userPrompt = "Please generate a professional personal summary based on the following candidate information:\\n\\n" + candidateText;
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", userPrompt);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "PPG");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("个人简介生成器:{}", resultJson);

        Map dataMap = JSONUtil.toBean(resultJson, Map.class);
        HotakePersonalProfileGeneratorDto generatorDto = new HotakePersonalProfileGeneratorDto();

        Map personalSummaryMap = (Map) dataMap.get("personal_summary");
        generatorDto.setAbout(personalSummaryMap.get("generated_text").toString());
        return generatorDto;
    }

    /**
     * 工作经验生成器
     *
     * @param workExperienceGeneratorVo 工作信息
     * @return
     */
    @Override
    public HotakeWorkExperienceGeneratorDto getWorkExperienceGenerator(HotakeWorkExperienceGeneratorVo workExperienceGeneratorVo) {
        String prompt = AiCommonPromptConstants.initializationWorkExperienceGeneratorPrompt();

        String candidateText = " Job Title: " + workExperienceGeneratorVo.getTitle() + " Company Name: " + workExperienceGeneratorVo.getCompany() + " Work Period: " + workExperienceGeneratorVo.getDurationStart() + "-" + workExperienceGeneratorVo.getDurationEnd()
                + "Additional Info: ";

        String userPrompt = "Please generate a professional work experience description based on the following information:\\n\\n" + candidateText;
        List<Map<String, String>> list = new LinkedList();
        Map<String, String> mapEntity = new HashMap<>();
        mapEntity.put("role", "system");
        mapEntity.put("content", prompt);
        list.add(mapEntity);
        Map<String, String> mapUserEntity = new HashMap<>();
        mapUserEntity.put("role", "user");
        mapUserEntity.put("content", userPrompt);
        list.add(mapUserEntity);
        String promptJson = JSONUtil.toJsonStr(list);
        String resultStr = chatGPTClient.handleAiChat(promptJson, "PPG");
        String resultJson = resultStr.replaceAll("```json", "").replaceAll("```", "");
        log.info("工作经验生成器:{}", resultJson);

        Map dataMap = JSONUtil.toBean(resultJson, Map.class);
        HotakeWorkExperienceGeneratorDto generatorDto = new HotakeWorkExperienceGeneratorDto();
        List<VcExperienceDescriptionDto> description = new ArrayList<>();

        Map workExperienceMap = (Map) dataMap.get("work_experience");

        VcExperienceDescriptionDto descriptionDto = new VcExperienceDescriptionDto();
        descriptionDto.setContent(workExperienceMap.get("position_summary").toString());
        description.add(descriptionDto);

        List<String> keyResponsibilitiesList = (List<String>) workExperienceMap.get("key_responsibilities");
        if (CollectionUtil.isNotEmpty(keyResponsibilitiesList)) {
            for (String Str : keyResponsibilitiesList) {
                VcExperienceDescriptionDto descriptionDto1 = new VcExperienceDescriptionDto();
                descriptionDto1.setContent(Str);
                description.add(descriptionDto1);
            }
        }
        generatorDto.setDescription(description);
        return generatorDto;
    }

    /**
     * 招聘链接信息分析补全
     *
     * @param roleLinkAnalysisVo 岗位链接对象
     * @return
     */
    @Override
    public HotakeRolesInfoDto getRoleLinkAnalysis(HotakeRoleLinkAnalysisVo roleLinkAnalysisVo) {
        //获取
//        String webContent = handleWebContentScraping(roleLinkAnalysisVo.getRoleUrl());
        String webContent = "";
        //如果没有岗位信息添加一个默认值
//        if(StrUtil.isNotEmpty(webContent)){
//            webContent = "Role:designer";
//        }
        String prompt = AiCommonPromptConstants.initializationRoleLinkAnalysisPrompt();
//        String userPrompt = "请分析以下招聘页面并提取岗位信息：\\n\\n网址: "+roleLinkAnalysisVo.getRoleUrl()+"\\n\\n内容:\\n" +webContent;
//        List<Map<String, String>> list = new LinkedList();
//        Map<String, String> mapEntity = new HashMap<>();
//        mapEntity.put("role", "system");
//        mapEntity.put("content",prompt);
//        list.add(mapEntity);
//        Map<String, String> mapUserEntity = new HashMap<>();
//        mapUserEntity.put("role", "user");
//        mapUserEntity.put("content",userPrompt);
//        list.add(mapUserEntity);
//        String promptJson = JSONUtil.toJsonStr(list);
//        String resultStr = chatGPTClient.handleAiChat(promptJson,"RLINKAL");
        String resultJson = "{\"jobTitle\":\"Senior Software Engineer\",\"companyName\":\"Tech Innovation Corp\",\"jobType\":null}";
        log.info("招聘链接信息提取:{}", resultJson);
        //处理岗位信息补充
        String userPrompt_1 = "Please generate complete API-formatted data based on the extracted job information below：\\n\\n" + resultJson;
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "RLINKAL");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("招聘链接信息补全:{}", resultJsonOne);
        HotakeRolesInfoDto hotakeRolesInfoDto = new HotakeRolesInfoDto();
        Map resultMap = JSONUtil.toBean(resultJsonOne, Map.class);

        Map dataMap = (Map) resultMap.get("data");
        hotakeRolesInfoDto.setRoleName(dataMap.get("jobTitle").toString());

        hotakeRolesInfoDto.setCompanyName(dataMap.get("companyName").toString());
        hotakeRolesInfoDto.setLocations(dataMap.get("location").toString());
        hotakeRolesInfoDto.setSalaryStart(new BigDecimal(dataMap.get("salaryStart").toString()));
        hotakeRolesInfoDto.setSalaryEnd(new BigDecimal(dataMap.get("salaryEnd").toString()));
        hotakeRolesInfoDto.setJobType(dataMap.get("jobType").toString().toLowerCase());
        hotakeRolesInfoDto.setJobLevel(dataMap.get("jobLevel").toString().toLowerCase());
        hotakeRolesInfoDto.setJobExperience("5");
        hotakeRolesInfoDto.setLocationType(dataMap.get("locationType").toString().toLowerCase());

        hotakeRolesInfoDto.setAboutRole(dataMap.get("aboutRole").toString());

        hotakeRolesInfoDto.setResponsibilities(dataMap.get("responsibilities").toString());
        //岗位所需技能信息
        List<RequiredSkillsDto> requiredSkillsList = (List<RequiredSkillsDto>) dataMap.get("requiredSkillsList");
        hotakeRolesInfoDto.setRequiredSkillsList(requiredSkillsList);

        hotakeRolesInfoDto.setRequiredSkillsJson(JSONUtil.toJsonStr(requiredSkillsList));

        List<NiceToHaveSkillsDto> niceToHaveSkillsList = (List<NiceToHaveSkillsDto>) dataMap.get("niceToHaveSkillsList");
        hotakeRolesInfoDto.setNiceToHaveSkillsList(niceToHaveSkillsList);

        hotakeRolesInfoDto.setNiceToHaveSkillsJson(JSONUtil.toJsonStr(niceToHaveSkillsList));

        List<Map> roleBenefitsMapList = (List<Map>) dataMap.get("roleBenefitsList");
        List<RoleBenefitsDto> roleBenefitsList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roleBenefitsMapList)) {
            for (Map dto : roleBenefitsMapList) {
                //福利转换
                RoleBenefitsDto dto1 = new RoleBenefitsDto();
                if (ObjectUtil.isNotEmpty(dto.get("keyValue"))) {
                    RoleBenefitsEnum benefitsEnum = RoleBenefitsEnum.getByCode(dto.get("keyValue").toString());
                    if (benefitsEnum != null) {
                        dto1.setKeyValue(benefitsEnum.getCode());
                        roleBenefitsList.add(dto1);
                    }
                }
            }
        }
        hotakeRolesInfoDto.setRoleBenefitsList(roleBenefitsList);
        hotakeRolesInfoDto.setRoleBenefitsJson(JSONUtil.toJsonStr(roleBenefitsList));


        Map educationRequirementsMap = (Map) dataMap.get("educationRequirements");
        EducationRequirementsDto educationRequirements = new EducationRequirementsDto();
        educationRequirements.setAcademicMajor(educationRequirementsMap.get("academicMajor").toString());
        educationRequirements.setDegree(educationRequirementsMap.get("degree").toString());
        hotakeRolesInfoDto.setEducationRequirements(educationRequirements);
        hotakeRolesInfoDto.setEducationRequirementsJson(JSONUtil.toJsonStr(educationRequirements));

        List<CertificationsLicensesDto> certificationsLicensesList = (List<CertificationsLicensesDto>) dataMap.get("certificationsLicensesList");
        hotakeRolesInfoDto.setCertificationsLicensesList(certificationsLicensesList);

        hotakeRolesInfoDto.setCertificationsLicensesJson(JSONUtil.toJsonStr(certificationsLicensesList));

        fill(FillTypeEnum.INSERT.getCode(), hotakeRolesInfoDto);
        hotakeRolesInfoMapper.insertHotakeRolesInfo(hotakeRolesInfoDto);

        return hotakeRolesInfoDto;
    }


    /**
     * 招聘链接信息分析补全
     *
     * @param roleLinkAnalysisVo 岗位链接对象
     * @return
     */
    @Override
    public HotakeRolesInfoDto getRoleInfoAnalysisSetUp(HotakeRolesInfoDto rolesInfoDto) {

        String prompt = AiCommonPromptConstants.initializationRoleLinkAnalysisPrompt();

        String resultJson = "{\n" +
                "  \"jobTitle\": " + rolesInfoDto.getRoleName() + ",\n" +
                "  \"companyName\": " + rolesInfoDto.getCompanyName() + ",\n" +
                "  \"location\": " + rolesInfoDto.getLocations() + ",\n" +
                "  \"salaryRange\": " + rolesInfoDto.getSalaryStart() + "-" + rolesInfoDto.getSalaryEnd() + ",\n" +
                "  \"jobType\": " + rolesInfoDto.getJobType() + ",\n" +
                "  \"experience\": " + rolesInfoDto.getJobExperience() + ",\n" +
                "  \"education\": " + JSONUtil.toJsonStr(rolesInfoDto.getEducationRequirements()) + ",\n" +
                "  \"skills\": " + JSONUtil.toJsonStr(rolesInfoDto.getRequiredSkillsList()) + ",\n" +
                "  \"description\": " + rolesInfoDto.getAboutRole() + "\n" +
                "}";
        log.info("招聘链接信息提取:{}", resultJson);
        //处理岗位信息补充
        String userPrompt_1 = "Please generate complete API-formatted data based on the extracted job information below：\\n\\n" + resultJson;
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "RLINKAL");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("招聘信息补全:{}", resultJsonOne);
        HotakeRolesInfoDto hotakeRolesInfoDto = new HotakeRolesInfoDto();
        Map resultMap = JSONUtil.toBean(resultJsonOne, Map.class);

        Map dataMap = (Map) resultMap.get("data");
        hotakeRolesInfoDto.setRoleName(dataMap.get("jobTitle").toString());

        hotakeRolesInfoDto.setCompanyName(dataMap.get("companyName").toString());
        hotakeRolesInfoDto.setLocations(dataMap.get("location").toString());
        hotakeRolesInfoDto.setSalaryStart(new BigDecimal(dataMap.get("salaryStart").toString()));
        hotakeRolesInfoDto.setSalaryEnd(new BigDecimal(dataMap.get("salaryEnd").toString()));
        hotakeRolesInfoDto.setJobType(dataMap.get("jobType").toString().toLowerCase());
        hotakeRolesInfoDto.setJobLevel(dataMap.get("jobLevel").toString().toLowerCase());
        hotakeRolesInfoDto.setJobExperience("5");
        hotakeRolesInfoDto.setLocationType(dataMap.get("locationType").toString().toLowerCase());

        hotakeRolesInfoDto.setAboutRole(dataMap.get("aboutRole").toString());

        hotakeRolesInfoDto.setResponsibilities(dataMap.get("responsibilities").toString());
        //岗位所需技能信息
        List<RequiredSkillsDto> requiredSkillsList = (List<RequiredSkillsDto>) dataMap.get("requiredSkillsList");
        hotakeRolesInfoDto.setRequiredSkillsList(requiredSkillsList);

        hotakeRolesInfoDto.setRequiredSkillsJson(JSONUtil.toJsonStr(requiredSkillsList));

        List<NiceToHaveSkillsDto> niceToHaveSkillsList = (List<NiceToHaveSkillsDto>) dataMap.get("niceToHaveSkillsList");
        hotakeRolesInfoDto.setNiceToHaveSkillsList(niceToHaveSkillsList);

        hotakeRolesInfoDto.setNiceToHaveSkillsJson(JSONUtil.toJsonStr(niceToHaveSkillsList));

        List<Map> roleBenefitsMapList = (List<Map>) dataMap.get("roleBenefitsList");
        List<RoleBenefitsDto> roleBenefitsList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roleBenefitsMapList)) {
            for (Map dto : roleBenefitsMapList) {
                //福利转换
                RoleBenefitsDto dto1 = new RoleBenefitsDto();
                if (ObjectUtil.isNotEmpty(dto.get("keyValue"))) {
                    RoleBenefitsEnum benefitsEnum = RoleBenefitsEnum.getByCode(dto.get("keyValue").toString());
                    if (benefitsEnum != null) {
                        dto1.setKeyValue(benefitsEnum.getCode());
                        roleBenefitsList.add(dto1);
                    }
                }
            }
        }
        hotakeRolesInfoDto.setRoleBenefitsList(roleBenefitsList);
        hotakeRolesInfoDto.setRoleBenefitsJson(JSONUtil.toJsonStr(roleBenefitsList));

        Map educationRequirementsMap = (Map) dataMap.get("educationRequirements");
        EducationRequirementsDto educationRequirements = new EducationRequirementsDto();
        educationRequirements.setAcademicMajor(educationRequirementsMap.get("academicMajor").toString());
        educationRequirements.setDegree(educationRequirementsMap.get("degree").toString());
        hotakeRolesInfoDto.setEducationRequirements(educationRequirements);
        hotakeRolesInfoDto.setEducationRequirementsJson(JSONUtil.toJsonStr(educationRequirements));

        List<CertificationsLicensesDto> certificationsLicensesList = (List<CertificationsLicensesDto>) dataMap.get("certificationsLicensesList");
        hotakeRolesInfoDto.setCertificationsLicensesList(certificationsLicensesList);

        hotakeRolesInfoDto.setCertificationsLicensesJson(JSONUtil.toJsonStr(certificationsLicensesList));

        return hotakeRolesInfoDto;
    }


    /**
     * AI面试问题生成
     *
     * @param rolesInfo 岗位信息
     * @return
     */
    @Override
    public HotakeAiInterviewQuestionsInfo getAiInterviewQuestions(HotakeRolesInfo rolesInfo) {

        HotakeRolesInfo hotakeRolesInfo = hotakeRolesInfoMapper.selectHotakeRolesInfoById(rolesInfo.getId());
        String prompt = AiCommonPromptConstants.initializationAiInterviewQuestionsPrompt();

        String userPrompt_1 = "Please generate AI interview questions based on the following job description：\n" +
                "\n" +
                "**Job Information**：\n" +
                "Job Title：【" + hotakeRolesInfo.getRoleName() + "】\n" +
                "Technical Requirements：【" + hotakeRolesInfo.getRequiredSkillsJson() + "-" + hotakeRolesInfo.getNiceToHaveSkillsJson() + "】\n" +
                "Experience Requirements：【" + hotakeRolesInfo.getJobExperience() + "】\n" +
                "Interview Duration：【】\n" +
                "Company Culture：【】\n" +
                "Special Requirements：【" + hotakeRolesInfo.getAboutRole() + "】\n" +
                "`;";
        log.info("AI面试问题生成:{}", userPrompt_1);
        //处理岗位信息补充
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "RLINKAL");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("AI面试问题生成结果:{}", resultJsonOne);

        try {
            Map mapData = JSONUtil.toBean(resultJsonOne, Map.class);
            List<Map> questionMapList = (List<Map>) mapData.get("interview_questions");
            if (CollectionUtil.isNotEmpty(questionMapList)) {
                HotakeAiInterviewQuestionsInfo questionsInfo = new HotakeAiInterviewQuestionsInfo();
                questionsInfo.setQuestionTitle("General Questions");
                questionsInfo.setFocusType("Personality & Culture");
                questionsInfo.setRoleId(rolesInfo.getId());
                questionsInfo.setRecruiterId(SecurityUtils.getUserId());
                questionsInfo.setOverview("This is General Questions Overview");

                BigDecimal times = BigDecimal.ZERO;
                List<AiQuestionDto> questionDtoList = new ArrayList<>();
                for (Map map : questionMapList) {
                    AiQuestionDto questionDto = new AiQuestionDto();
                    questionDto.setQuestions(map.get("question_text").toString());
                    questionDtoList.add(questionDto);
                    times = times.add(new BigDecimal(map.get("estimated_time").toString()));
                }
                questionsInfo.setAiQuestionList(questionDtoList);
                questionsInfo.setTimes(times.toString());
                questionsInfo.setQuestionJson(JSONUtil.toJsonStr(questionDtoList));
                //先删除数据
                hotakeAiInterviewQuestionsInfoMapper.deleteHotakeAiInterviewQuestionsInfoByRoleId(rolesInfo.getId());
                //进行数据更新
                hotakeAiInterviewQuestionsInfoMapper.insertHotakeAiInterviewQuestionsInfo(questionsInfo);
                return questionsInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HotakeAiInterviewQuestionsInfo();
    }

    /**
     * 候选人AI面试分析
     *
     * @param rolesInfo 候选人AI面试分析信息
     * @return
     */
    @Override
    public HotakeCandidateAiInterviewAnalysisDto handleCandidateAiInterviewAnalysis(HotakeCandidateAiInterviewAnalysisVo analysisVo) {
        HotakeCandidateAiInterviewAnalysisDto analysisDto = new HotakeCandidateAiInterviewAnalysisDto();
        String prompt = AiCommonPromptConstants.initializationCandidateAiInterviewAnalysisPrompt();
        String qa = "";
        String qStr = "";
        String aStr = "";
        if (CollectionUtil.isNotEmpty(analysisVo.getAiInterviewQuestionRecordVoList())) {
            for (HotakeAiInterviewQuestionRecordVo recordVo : analysisVo.getAiInterviewQuestionRecordVoList()) {
                if ("assistant".equals(recordVo.getUserType())) {
                    qa = qa + "Question:" + recordVo.getContentText();
                    qStr = qStr + ";" + recordVo.getContentText();
                }
                if ("user".equals(recordVo.getUserType())) {
                    qa = qa + "Answer:" + recordVo.getContentText();
                    aStr = aStr + ";" + recordVo.getContentText();
                }
            }
        }
        String userPrompt_1 = "Please conduct an interview analysis based on the questions answered by the following candidates：\n" +
                "\n" +
                "**Job Information**：\n" +
                "Position：【" + analysisVo.getPosition() + "】\n" +
                "Question And Answer：【" + qa + "】\n" +
                "Please return the analysis results in the required JSON format.";

        log.info("AI面试问题生成:{}", userPrompt_1);
        //处理岗位信息补充
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "AIINTPF");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("候选人AI面试分析结果:{}", resultJsonOne);
        if (StrUtil.isNotEmpty(resultJsonOne)) {
            try {
                Map dataMap = JSONUtil.toBean(resultJsonOne, Map.class);
                Map scoresMap = (Map) dataMap.get("scores");
                analysisDto.setTechnical(new BigDecimal(scoresMap.get("technical").toString()));
                analysisDto.setCommunication(new BigDecimal(scoresMap.get("communication").toString()));
                analysisDto.setCultural(new BigDecimal(scoresMap.get("cultural").toString()));

                Map analysisMap = (Map) dataMap.get("analysis");
                Map technicalMap = (Map) analysisMap.get("technical");
                HotakeCandidateAiInterviewAnalysisAnalysisDto technicalDto = new HotakeCandidateAiInterviewAnalysisAnalysisDto();
                List<String> improvements = (List<String>) technicalMap.get("improvements");
                List<String> strengths = (List<String>) technicalMap.get("strengths");
                technicalDto.setImprovements(improvements);
                technicalDto.setStrengths(strengths);
                analysisDto.setTechnicalDto(technicalDto);

                Map communicationMap = (Map) analysisMap.get("communication");
                HotakeCandidateAiInterviewAnalysisAnalysisDto communicationDto = new HotakeCandidateAiInterviewAnalysisAnalysisDto();
                List<String> improvements1 = (List<String>) communicationMap.get("improvements");
                List<String> strengths1 = (List<String>) communicationMap.get("strengths");
                communicationDto.setImprovements(improvements1);
                communicationDto.setStrengths(strengths1);
                analysisDto.setCommunicationDto(communicationDto);

                Map culturalMap = (Map) analysisMap.get("cultural");
                HotakeCandidateAiInterviewAnalysisAnalysisDto culturalDto = new HotakeCandidateAiInterviewAnalysisAnalysisDto();
                List<String> improvements2 = (List<String>) culturalMap.get("improvements");
                List<String> strengths2 = (List<String>) culturalMap.get("strengths");
                culturalDto.setImprovements(improvements2);
                culturalDto.setStrengths(strengths2);
                analysisDto.setCulturalDto(culturalDto);
                List<HotakeCandidateAiInterviewAnalysisNotesDto> notesDtoList = new ArrayList<>();
                List<Map> notesMapList = (List<Map>) dataMap.get("notes");
                if (CollectionUtil.isNotEmpty(notesMapList)) {
                    for (Map noteMap : notesMapList) {
                        HotakeCandidateAiInterviewAnalysisNotesDto analysisNotesDto = new HotakeCandidateAiInterviewAnalysisNotesDto();
                        analysisNotesDto.setType(noteMap.get("type").toString());
                        analysisNotesDto.setContent(noteMap.get("content").toString());
                        notesDtoList.add(analysisNotesDto);
                    }
                }
                analysisDto.setNotesDtoList(notesDtoList);

            } catch (Exception e) {
                throw new ServiceException("No rating");
            }
        }
        //把面试结果分析和问答Qa保存到记录表中
        if (analysisVo.getRoleApplyId() != null) {
            HotakeRolesApplyInfo applyInfo = hotakeRolesApplyInfoMapper.selectHotakeRolesApplyInfoById(analysisVo.getRoleApplyId());
            applyInfo.setAiInterviewAnalysisJson(JSONUtil.toJsonStr(analysisVo));
            applyInfo.setAiInterviewAnalysisQaJson(JSONUtil.toJsonStr(analysisVo.getAiInterviewQuestionRecordVoList()));
            HotakeRolesInfo rolesInf = hotakeRolesInfoMapper.selectHotakeRolesInfoById(applyInfo.getRoleId());
            try {
                //候选人面试综合评估
                HotakeCandidateInterviewEvaluationVo evaluationVo = new HotakeCandidateInterviewEvaluationVo();

                evaluationVo.setTitle(rolesInf.getRoleName());
                evaluationVo.setDescription(rolesInf.getAboutRole());
                evaluationVo.setRequiredSkills(rolesInf.getRequiredSkillsJson());
                evaluationVo.setPreferredSkills(rolesInf.getNiceToHaveSkillsJson());
                evaluationVo.setExperienceRequired(rolesInf.getJobExperience());
                HotakeCvInfoDto cvInfoDto = JSONUtil.toBean(applyInfo.getCvTemplateJson(), HotakeCvInfoDto.class);
                evaluationVo.setName(cvInfoDto.getName());
                evaluationVo.setCurrentPosition(cvInfoDto.getPosition());
                evaluationVo.setEmail(cvInfoDto.getEmail());
                evaluationVo.setWorkExperience(JSONUtil.toJsonStr(cvInfoDto.getExperience()));
                evaluationVo.setSkills(JSONUtil.toJsonStr(cvInfoDto.getSkillsTools()));
                evaluationVo.setEducation(JSONUtil.toJsonStr(cvInfoDto.getEducation()));
                evaluationVo.setCertifications("");
                evaluationVo.setInterviewData(DateUtil.now());

                evaluationVo.setQuestions(qStr);
                evaluationVo.setAnswers(aStr);
                evaluationVo.setTechnical(analysisDto.getTechnical().toString());
                evaluationVo.setCommunication(analysisDto.getCommunication().toString());
                evaluationVo.setSafetyAwareness("");
                evaluationVo.setProblemSolving("");

                HotakeCandidateInterviewEvaluationDto evaluationDto = getCandidateInterviewEvaluation(evaluationVo);
                applyInfo.setEvaluationJson(JSONUtil.toJsonStr(evaluationDto));
                applyInfo.setEvaluationScore(new BigDecimal(evaluationDto.getOverallScore()));
            } catch (Exception e) {
                e.printStackTrace();
            }


            hotakeRolesApplyInfoMapper.updateHotakeRolesApplyInfo(applyInfo);
        }
        return analysisDto;
    }

    /**
     * 招聘者AI简历评分和排名系统
     *
     * @param scoringRankingVo 招聘者AI简历评分和排名系统输入信息
     * @return
     */
    @Override
    public HotakeAiCvScoringRankingDto handleAiCvScoringRanking(HotakeAiCvScoringRankingRoleApplyVo roleApplyVo) {
        HotakeAiCvScoringRankingDto dto = new HotakeAiCvScoringRankingDto();
        HotakeRolesInfo rolesInfo = hotakeRolesInfoMapper.selectHotakeRolesInfoById(roleApplyVo.getApplyInfo().getRoleId());

        HotakeAiCvScoringRankingVo scoringRankingVo = new HotakeAiCvScoringRankingVo();
        scoringRankingVo.setTitle(rolesInfo.getRoleName());
        scoringRankingVo.setDescription(rolesInfo.getAboutRole());

        List<RequiredSkillsDto> requiredSkillsList = JSONUtil.toList(rolesInfo.getRequiredSkillsJson(), RequiredSkillsDto.class);
        List<String> requiredSkills = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(requiredSkillsList)) {
            for (RequiredSkillsDto requiredSkillsDto : requiredSkillsList) {
                requiredSkills.add(requiredSkillsDto.getKeyValue());
            }
        }
        List<NiceToHaveSkillsDto> niceToHaveSkillsList = JSONUtil.toList(rolesInfo.getNiceToHaveSkillsJson(), NiceToHaveSkillsDto.class);
        List<String> niceToHaveSkills = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(niceToHaveSkillsList)) {
            for (NiceToHaveSkillsDto haveSkillsDto : niceToHaveSkillsList) {
                niceToHaveSkills.add(haveSkillsDto.getKeyValue());
            }
        }
        scoringRankingVo.setRequiredSkills(requiredSkills);
        scoringRankingVo.setNiceToHaveSkills(niceToHaveSkills);
        scoringRankingVo.setExperienceRequired(rolesInfo.getJobExperience());
        EducationRequirementsDto educationRequirements = JSONUtil.toBean(rolesInfo.getEducationRequirementsJson(), EducationRequirementsDto.class);
        scoringRankingVo.setEducationRequired(educationRequirements.getDegree() + "," + educationRequirements.getAcademicMajor());

        HotakeCvInfoDto cvInfoDto = JSONUtil.toBean(roleApplyVo.getCvTemplateJson(), HotakeCvInfoDto.class);
        HotakeCandidateVcInfoVo infoVo = new HotakeCandidateVcInfoVo();

        infoVo.setName(cvInfoDto.getName());
        infoVo.setCurrentPosition(cvInfoDto.getPosition());
        infoVo.setWorkExperience(JSONUtil.toJsonStr(cvInfoDto.getExperience()));
        infoVo.setEducation(JSONUtil.toJsonStr(cvInfoDto.getEducation()));

        List<String> skills = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(cvInfoDto.getSkillsTools())) {
            for (VcSkillsToolsDto skillsToolsDto : cvInfoDto.getSkillsTools()) {
                skills.add(skillsToolsDto.getContent());
            }
        }
        infoVo.setSkills(skills);
        infoVo.setSummary(cvInfoDto.getAbout());

        scoringRankingVo.setCandidates(infoVo);

        String prompt = AiCommonPromptConstants.initializationAiCvScoringRankingPrompt();
        String userPrompt_1 = JSONUtil.toJsonStr(scoringRankingVo);
        //处理岗位信息补充
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "AICVSR");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("招聘者AI简历评分和排名系统结果:{}", resultJsonOne);
        try {
            Map dataMap = JSONUtil.toBean(resultJsonOne, Map.class);
            Map scoresMap = (Map) dataMap.get("scores");
            if (ObjectUtil.isNotEmpty(scoresMap.get("skills"))) {
                dto.setSkills(new BigDecimal(scoresMap.get("skills").toString()));
            } else {
                dto.setSkills(BigDecimal.ZERO);
            }
            if (ObjectUtil.isNotEmpty(scoresMap.get("experience"))) {
                dto.setExperience(new BigDecimal(scoresMap.get("experience").toString()));
            } else {
                dto.setExperience(BigDecimal.ZERO);
            }
            if (ObjectUtil.isNotEmpty(scoresMap.get("education"))) {
                dto.setEducation(new BigDecimal(scoresMap.get("education").toString()));
            } else {
                dto.setEducation(BigDecimal.ZERO);
            }
            if (ObjectUtil.isNotEmpty(scoresMap.get("cultural"))) {
                dto.setCultural(new BigDecimal(scoresMap.get("cultural").toString()));
            } else {
                dto.setCultural(BigDecimal.ZERO);
            }
            if (ObjectUtil.isNotEmpty(scoresMap.get("potential"))) {
                dto.setPotential(new BigDecimal(scoresMap.get("potential").toString()));
            } else {
                dto.setPotential(BigDecimal.ZERO);
            }

            List<String> strengths = (List<String>) dataMap.get("strengths");
            dto.setStrengths(strengths);

            List<String> weaknesses = (List<String>) dataMap.get("weaknesses");
            dto.setWeaknesses(weaknesses);

            dto.setReason(dataMap.get("reason").toString());
            dto.setRecommendation(dataMap.get("recommendation").toString());

            //计算总体评分 (70×0.3 + 75×0.25 + 80×0.15 + 85×0.15 + 88×0.15)
            BigDecimal overallScore = dto.getSkills().multiply(new BigDecimal(0.3)).
                    add(dto.getExperience().multiply(new BigDecimal(0.25)).add(dto.getEducation().multiply(new BigDecimal(0.15))).
                            add(dto.getCultural().multiply(new BigDecimal(0.15)).add(dto.getPotential().multiply(new BigDecimal(0.15)))));
            dto.setOverallScore(overallScore);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    /**
     * 招聘者查看候选人匹配度
     *
     * @param compatibilityVo 招聘者查看候选人匹配度 输入信息
     * @return
     */
    @Override
    public HotakeCandidateCompatibilityDto handleCandidateCompatibility(HotakeCandidateCompatibilityVo compatibilityVo) {
        HotakeCandidateCompatibilityDto dto = new HotakeCandidateCompatibilityDto();
        String prompt = AiCommonPromptConstants.initializationCandidateCompatibilityPrompt();

        String userPrompt_1 = "Please analyze the matching details of the following candidates：\n" +
                "\n" +
                "【Position】: " + compatibilityVo.getPosition() + "\n" +
                "【Candidate】: " + compatibilityVo.getCandidate() + "\n" +
                "【Current position】: " + compatibilityVo.getCurrentPosition() + "\n" +
                "【Work Experience】: " + compatibilityVo.getWorkExperience() + "\n" +
                "【Skill】: " + JSONUtil.toJsonStr(compatibilityVo.getSkills()) + "\n" +
                "【Overall Rating】: " + compatibilityVo.getOverallRating() + "\n" +
                "\n" +
                "Please return a detailed analysis in JSON format。";

        //处理岗位信息补充
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "AICAC");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("招聘者查看候选人匹配度结果:{}", resultJsonOne);
        Map dataMap = JSONUtil.toBean(resultJsonOne, Map.class);
        if (ObjectUtil.isNotEmpty(dataMap.get("strengths_score"))) {
            dto.setStrengthsScore(new BigDecimal(dataMap.get("strengths_score").toString()));
        } else {
            dto.setStrengthsScore(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNotEmpty(dataMap.get("differences_score"))) {
            dto.setDifferencesScore(new BigDecimal(dataMap.get("differences_score").toString()));
        } else {
            dto.setDifferencesScore(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNotEmpty(dataMap.get("cultural_score"))) {
            dto.setCulturalScore(new BigDecimal(dataMap.get("cultural_score").toString()));
        } else {
            dto.setCulturalScore(BigDecimal.ZERO);
        }

        List<String> strengths = (List<String>) dataMap.get("key_strengths");
        dto.setKeyStrengths(strengths);

        List<String> differences = (List<String>) dataMap.get("key_differences");
        dto.setKeyDifferences(differences);

        List<String> fitDetails = (List<String>) dataMap.get("cultural_fit_details");
        dto.setCulturalFitDetails(fitDetails);

        BigDecimal overallScore = dto.getStrengthsScore().multiply(new BigDecimal(0.4)).
                add(dto.getDifferencesScore().multiply(new BigDecimal(0.3)).add(dto.getCulturalScore().multiply(new BigDecimal(0.3))));
        dto.setOverallScore(overallScore);

        return dto;
    }


    /**
     * 候选人面试综合评估
     *
     * @param evaluationVo 候选人面试综合评估 输入信息
     * @return
     */
    @Override
    public HotakeCandidateInterviewEvaluationDto getCandidateInterviewEvaluation(HotakeCandidateInterviewEvaluationVo evaluationVo) {
        HotakeCandidateInterviewEvaluationDto dto = new HotakeCandidateInterviewEvaluationDto();
        String prompt = AiCommonPromptConstants.initializationCandidateInterviewEvaluationPrompt();

        String userPrompt_1 = "Job Posting:\n" +
                "Title: " + evaluationVo.getTitle() + "\n" +
                "Description: " + evaluationVo.getDescription() + "\n" +
                "Required Skills: " + evaluationVo.getRequiredSkills() + "\n" +
                "Preferred Skills: " + evaluationVo.getPreferredSkills() + "\n" +
                "Experience Required: " + evaluationVo.getExperienceRequired() + "\n" +
                "\n" +
                "Candidate Information:\n" +
                "Name: " + evaluationVo.getName() + "\n" +
                "Current Position: " + evaluationVo.getCurrentPosition() + "\n" +
                "Email: " + evaluationVo.getEmail() + "\n" +
                "Work Experience: " + evaluationVo.getWorkExperience() + "\n" +
                "Skills: " + evaluationVo.getSkills() + "\n" +
                "Education: " + evaluationVo.getEducation() + "\n" +
                "Certifications: " + evaluationVo.getCertifications() + "\n" +
                "\n" +
                "Interview Data:" + evaluationVo.getInterviewData() + "\n" +
                "Questions: " + evaluationVo.getQuestions() + "\n" +
                "Answers: " + evaluationVo.getAnswers() + "\n" +
                "Scores: Technical=" + evaluationVo.getTechnical() + ", Communication=" + evaluationVo.getCommunication() + ", Safety Awareness=" + evaluationVo.getSafetyAwareness() + ", Problem Solving=" + evaluationVo.getProblemSolving() + "}\n" +
                "\n" +
                "Please analyze this candidate and provide a comprehensive overview with Assessment, Rating, and Questions scores.";

        //处理岗位信息补充
        List<Map<String, String>> listOne = new LinkedList();
        Map<String, String> mapEntityOne = new HashMap<>();
        mapEntityOne.put("role", "system");
        mapEntityOne.put("content", prompt);
        listOne.add(mapEntityOne);
        Map<String, String> mapUserEntityOne = new HashMap<>();
        mapUserEntityOne.put("role", "user");
        mapUserEntityOne.put("content", userPrompt_1);
        listOne.add(mapUserEntityOne);
        String promptJsonOne = JSONUtil.toJsonStr(listOne);
        String resultStrOne = chatGPTClient.handleAiChat(promptJsonOne, "AICIV");
        String resultJsonOne = resultStrOne.replaceAll("```json", "").replaceAll("```", "");
        log.info("候选人面试综合评估:{}", resultJsonOne);
        Map dataMap = JSONUtil.toBean(resultJsonOne, Map.class);
        if(dataMap != null){
            Map scoreBreakdownMap = (Map) dataMap.get("score_breakdown");
            if (scoreBreakdownMap != null) {
                Map assessmentMap = (Map) scoreBreakdownMap.get("assessment");
                if (assessmentMap != null) {
                    dto.setAssessmentScore(assessmentMap.get("score").toString());
                    dto.setAssessmentLevel(assessmentMap.get("score").toString());
                    List<String> details = (List<String>) assessmentMap.get("details");
                    dto.setAssessmentDetails(details);
                }
                Map ratingMap = (Map) scoreBreakdownMap.get("rating");
                if (ratingMap != null) {
                    dto.setRatingScore(ratingMap.get("score").toString());
                    dto.setRatingLevel(ratingMap.get("score").toString());
                    List<String> details = (List<String>) ratingMap.get("details");
                    dto.setRatingDetails(details);
                }
                Map questionsMap = (Map) scoreBreakdownMap.get("questions");
                if (questionsMap != null) {
                    dto.setQuestionsScore(questionsMap.get("score").toString());
                    dto.setQuestionsLevel(questionsMap.get("score").toString());
                    List<String> details = (List<String>) questionsMap.get("details");
                    dto.setQuestionsDetails(details);
                }
            }
        }

        dto.setOverallScore(dataMap.get("overall_score").toString());
        dto.setRecommendation(dataMap.get("recommendation").toString());

        return dto;
    }
}
