package cn.com.poc.examination;

import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.thirdparty.resource.demand.ai.constants.LLMRoleEnum;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Message;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelResponse;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.Thinking;
import cn.com.poc.thirdparty.service.LLMService;
import cn.com.poc.writing.aggregate.ExaminationService;
import cn.com.poc.writing.entity.ExaminationConfigItemEntity;
import cn.com.poc.writing.entity.ExaminationDetail;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.spring.SingleContextInitializer;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 52747
 * @date 2025/8/14
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = SingleContextInitializer.class)
@WebAppConfiguration
public class ExaminationTest {

    private final String startXML = "<examination_questions>";
    private final String endXML = "</examination_questions>";

    private final String MODEL = "Doubao-seed-1.6";

    private String prompt = "你的任务是根据提供的相关文件资料，按照指定要求为制造业培训进行出题。请仔细阅读以下信息，并按照指示完成出题任务。\n" +
            "相关文件资料：\n" +
            "<files>\n" +
            "${file_content}\n" +
            "</files>\n" +
            "出题要求如下：\n" +
            "- 出题数量：\n" +
            "<number_of_questions>\n" +
            "${number}\n" +
            "</number_of_questions>\n" +
            "- 总分数：\n" +
            "<total_score>\n" +
            "${total_score}\n" +
            "</total_score>\n" +
            "- 难度级别：\n" +
            "<difficulty_level>\n" +
            "${level}\n" +
            "</difficulty_level>\n" +
            "- 适用岗位：\n" +
            "<applicable_position>\n" +
            "${position}\n" +
            "</applicable_position>\n" +
            "- 出题类型：\n" +
            "<question_type>\n" +
            "${question_type}\n" +
            "</question_type>\n" +
            "在出题时，请遵循以下指南：\n" +
            "1. 题目内容需紧密围绕相关文件资料和适用岗位的知识技能。\n" +
            "2. 根据难度级别合理设置题目的难易程度。\n" +
            "3. 确保题目数量和总分数相匹配，可根据出题类型合理分配每题的分值。\n" +
            "4. 题目表述应清晰、准确，避免产生歧义。\n" +
            "请按照固定方式输出json格式的题目,每一个题目使用<examination_questions> </examination_questions>包裹，用于前端渲染，每个题目需包含题目类型[questionType]，分数[score]，题目[question]，题目中的多个选项[choice]，正确答案[rightAnswers]，正确答案解析[rightAnswersAnalysis]。其中正确答案解析不仅要对正确答案依据文件进行说明，还需对每个错误选项进行详细分析，且包含选项之间的对比分析。\n" +
            "<examination_questions>\n" +
            "{\n" +
            "    \"questionType\": \"单选题\",\n" +
            "    \"score\": 5,\n" +
            "    \"question\": \"基础概念：以下哪项不属于产品表面严重缺陷？\",\n" +
            "    \"choice\": [\"A. 长度超过2cm的划痕\", \"B. 直径0.3mm以下的针孔\", \"C. 面积大于5mm²的污渍\", \"D. 明显的色差（ΔE3.0）\"],\n" +
            "    \"rightAnswers\": \"B\",\n" +
            "    \"rightAnswersAnalysis\": \"根据公司标准Q/ZW - 003，直径小于0.5mm的针孔属于轻微缺陷，可通过返工修复，不属于严重缺陷。A选项长度超过2cm的划痕，对产品外观影响较大，属于严重缺陷；C选项面积大于5mm²的污渍，同样影响产品外观质量，属于严重缺陷；D选项明显的色差（ΔE3.0）也会影响产品整体外观，属于严重缺陷。通过对比，B选项与其他选项在缺陷程度上存在差异，所以选B。\"\n" +
            "}\n" +
            "</examination_questions>\n" +
            "<examination_questions>\n" +
            "{\n" +
            "    \"questionType\": \"多选题\",\n" +
            "    \"score\": 5,\n" +
            "    \"question\": \"自动化测试工具（如Selenium、Appium）的主要功能包括哪些？（多选）\",\n" +
            "    \"choice\": [\"A. 录制用户操作并回放\", \"B. 支持脚本语言编写测试脚本\", \"C. 自动分析测试结果并标记缺陷\", \"D. 自动修复发现的软件缺陷\", \"E. 生成测试报告\"],\n" +
            "    \"rightAnswers\": \"A B C E\",\n" +
            "    \"rightAnswersAnalysis\": \"根据公司标准Q/ZW - 003，直径小于0.5mm的针孔属于轻微缺陷，可通过返工修复，不属于严重缺陷。A选项长度超过2cm的划痕，对产品外观影响较大，属于严重缺陷；C选项面积大于5mm²的污渍，同样影响产品外观质量，属于严重缺陷；D选项明显的色差（ΔE3.0）也会影响产品整体外观，属于严重缺陷。通过对比，B选项与其他选项在缺陷程度上存在差异，所以选B。\"\n" +
            "}\n" +
            "</examination_questions>\n";

    @Resource
    private LLMService llmService;

    @Test
    public void test() throws Exception {
        String content = prompt.replace("${file_content}", "软件测试")
                .replace("${number}", "10")
                .replace("${total_score}", "100")
                .replace("${level}", "中级")
                .replace("${position}", "软件测试")
                .replace("${question_type}", "单选题、多选题、判断题");

        Message userMessage = new Message();
        userMessage.setRole(LLMRoleEnum.USER.getRole());
        userMessage.setContent(content);

        Message[] messages = new Message[]{userMessage};
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("ep-20250814152748-6jlnx");
        largeModelResponse.setMessages(messages);
        largeModelResponse.setStream(true);
        largeModelResponse.setMaxTokens(32768);
        largeModelResponse.setThinking(new Thinking() {{
            setType("disabled");
        }});
        largeModelResponse.setUser("GENERATE_EXAMINATION");

        BufferedReader bufferedReader = llmService.chatChunk(largeModelResponse);

        String res = "";
        StringBuilder output = new StringBuilder();
        StringBuilder reasoningContent = new StringBuilder();

        List<ExaminationDetail> list = new ArrayList<>();
        try {
            while ((res = bufferedReader.readLine()) != null) {
                if (StringUtils.isEmpty(res)) {
                    continue;
                }
                res = StringUtils.replace(res, "data: ", StringUtils.EMPTY);
                LargeModelDemandResult result = JsonUtils.deSerialize(res, LargeModelDemandResult.class);
                if (!"0".equals(result.getCode())) {
                    BusinessException ex = new BusinessException("exception/call.failure");
                    result.setMessage(ex.getMessage());
                    throw ex;
                }
                if (StringUtils.isNotEmpty(result.getMessage())) {
                    output.append(result.getMessage());
                    int startIndex = output.indexOf(startXML);
                    if (startIndex != -1) {
                        int contentStart = startIndex + startXML.length();
                        int endIndex = output.indexOf(endXML, contentStart);
                        if (endIndex != -1) {
                            String extracted = output.substring(contentStart, endIndex);
                            ExaminationDetail generateExaminationEntity = JsonUtils.deSerialize(extracted, ExaminationDetail.class);
                            System.out.println(JsonUtils.serialize(generateExaminationEntity));
                            list.add(generateExaminationEntity);
                            output = new StringBuilder(output.substring(endIndex));
                        }
                    }
                }
                if (StringUtils.isNotEmpty(result.getReasoningContent())) {
                    reasoningContent.append(result.getReasoningContent());
                }
            }


        } catch (IOException e) {
            throw new BusinessException("连接断开");
        } finally {
            bufferedReader.close();
        }

        System.out.println("-------------------------------------------------");
        System.out.println("num:" + list.size());
        System.out.println(JsonUtils.serialize(list));
    }


    @Resource
    private ExaminationService examinationService;

    /**
     * 获取试卷生成配置项
     * 出题类型
     * 难度等级
     * 出题语言
     * 适用岗位
     */
    @Test
    public void getConfigurationItem() {
        ExaminationConfigItemEntity configurationItem = examinationService.getConfigurationItem();
        System.out.println(JsonUtils.serialize(configurationItem));
    }

    /**
     * 获取生成试卷信息
     */
    @Test
    public void getExaminations() {
        String examinationId;
        Long userId;
    }

    /**
     * 获取历史记录
     */
    @Test
    public void getList() {
        String query;
        Long userId;
    }

    @Test
    public void text_genereateExaminationFile() {
        String examinationId = "EXAMINATION_75ad7043b8064640a3eb222a0c6ab59b";
        Long userId = 198L;

        String url = examinationService.downloadExamination(examinationId, userId);
        System.out.println(url);

    }
}
