package com.seer.teach.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.seer.teach.admin.request.GenerateQuestionImageReq;
import com.seer.teach.admin.service.AdminQuestionImageService;
import com.seer.teach.common.enums.QuestionTypesEnums;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.SubjectUtils;
import com.seer.teach.teacher.module.entity.BankQuestionsEntity;
import com.seer.teach.teacher.module.entity.KnowledgePointEntity;
import com.seer.teach.teacher.module.entity.QuestionOptionsEntity;
import com.seer.teach.teacher.service.AiModelCallService;
import com.seer.teach.teacher.service.BankQuestionsService;
import com.seer.teach.teacher.service.KnowledgePointQueryService;
import com.seer.teach.teacher.service.QuestionOptionsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 题目图片生成服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-10-28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminQuestionImageServiceImpl implements AdminQuestionImageService {

    @Autowired
    private AiModelCallService aiModelCallService;

    @Autowired
    private KnowledgePointQueryService knowledgePointQueryService;

    @Autowired
    private BankQuestionsService bankQuestionsService;

    @Autowired
    private QuestionOptionsService questionOptionsService;

    @Override
    public String generateQuestionImages(GenerateQuestionImageReq req) {
        log.info("开始根据题目内容生成相关图片，请求参数: {}", req);

        // 构建参数
        Map<String, Object> params = new HashMap<>();
        params.put("width", req.getWidth());
        params.put("height", req.getHeight());
        // 调用大模型API生成图片
        String prompt = getGenerateQuestionImageProp(req);
        String negative_prompt = "生成的图片不要包含文字";
        params.put("negative_prompt", negative_prompt);
        params.put("imgCount", req.getImgCount());
        String taskId = aiModelCallService.asyncCallText2ImageModel(req.getScenarioCode(), prompt, params, req.getUserId());
        log.info("调用大模型API生成图片的任务Id： {}", taskId);

        return taskId;
    }

    @Override
    public List<String> getTaskResult(String taskId) {
        return aiModelCallService.getTaskResult(taskId);
    }

    @Override
    public String getGenerateQuestionImageProp(GenerateQuestionImageReq req) {
        KnowledgePointEntity knowledgePoint = knowledgePointQueryService.getKnowledgePointByKnowId(req.getKnowId());
        AssertUtils.notNull(knowledgePoint, ResultCodeEnum.KNOW_NOT_EXIST);
        if (Objects.nonNull(req.getQuestionId())) {
            BankQuestionsEntity bankQuestion = bankQuestionsService.getById(req.getQuestionId());
            if(Objects.nonNull(req.getQuestionId())){
                List<QuestionOptionsEntity> questionOptions = new ArrayList<>(4);
                if(QuestionTypesEnums.isChoiceQuestion(bankQuestion.getType())){
                    questionOptions.addAll(questionOptionsService.getQuestionOptionsByQuestionId(req.getQuestionId()));
                }
                return buildPromptForImageGeneration(req,knowledgePoint,bankQuestion,questionOptions);
            }
        }
        return buildPromptForImageGeneration(req,knowledgePoint);
    }

    private String buildPromptForImageGeneration(GenerateQuestionImageReq req,KnowledgePointEntity knowledgePoint,BankQuestionsEntity bankQuestion,List<QuestionOptionsEntity> questionOptions) {
        StringBuilder prompt = new StringBuilder();

        // 添加学科和年级信息，帮助AI更好地理解教学背景
        // String subjectName = SubjectUtils.getSubjectNameBySubjectId(knowledgePoint.getSubjectId());
        //prompt.append("学科领域：").append(subjectName != null ? subjectName : "通用学科").append("\n");
       // prompt.append("知识点背景：").append(knowledgePoint.getKnowledgePointName()).append("\n\n");
       // prompt.append("\n");

        prompt.append("角色：K12教育领域的专业教学插图设计师\n\n");

        prompt.append("图像内容如下：\n");
        if (StringUtils.isNotEmpty(req.getPrompt()) && Objects.nonNull(req.getType())) {
            // 根据type字段确定生成图片的类型
            switch (req.getType()) {
                case 1:
                    prompt.append(req.getPrompt()).append("\n");
                    prompt.append(bankQuestion.getAnswer()).append("\n");
                    prompt.append(bankQuestion.getSolution()).append("\n");
                    break;
                case 2:
                case 3:
                case 4:
                    prompt.append(req.getPrompt()).append("\n");
                    break;
                default:
                    prompt.append("图片类型：通用教学图片\n");
                    break;
            }
            prompt.append("\n\n");
        }
        prompt.append("图像要求：\n");
        prompt.append("1. 采用干净、简洁的教育类插图风格\n");
        prompt.append("2. 确保图像主体突出、边界清晰\n");
        prompt.append("3. 严禁在图片中嵌入任何文字内容\n");

        prompt.append("图像用途：生成的图像将用于教学试卷或练习题，请务必保证教育性和准确性。");

        return prompt.toString();
    }

    /**
     * 构建生成图片的提示词
     *
     * @param req 生成图片参数
     * @return 提示词
     */
    private String buildPromptForImageGeneration(GenerateQuestionImageReq req,KnowledgePointEntity knowledgePoint) {
        StringBuilder prompt = new StringBuilder();
        
        // 添加学科和年级信息，帮助AI更好地理解教学背景
        String subjectName = SubjectUtils.getSubjectNameBySubjectId(req.getSubjectId());
        prompt.append("学科领域：").append(subjectName != null ? subjectName : "通用学科").append("\n");
        prompt.append("知识点背景：").append(knowledgePoint.getSummary()).append("\n\n");
        
        // 根据type字段确定生成图片的类型
        if (req.getType() != null) {
            switch (req.getType()) {
                case 1:
                    prompt.append("图片类型：题目内容相关图片\n");
                    prompt.append("核心内容：").append(req.getTitle()).append("\n");
                    break;
                case 2:
                    prompt.append("图片类型：选项相关图片\n");
                    if (CollectionUtil.isNotEmpty(req.getOptions())) {
                        prompt.append("选项内容：\n");
                        for (int i = 0; i < req.getOptions().size(); i++) {
                            prompt.append("  ").append((char) ('A' + i)).append(". ").append(req.getOptions().get(i)).append("\n");
                        }
                    }
                    break;
                case 3:
                    prompt.append("图片类型：答案相关图片\n");
                    prompt.append("答案内容：").append(req.getAnswer()).append("\n");
                    break;
                case 4:
                    prompt.append("图片类型：选项展示图片\n");
                    if (CollectionUtil.isNotEmpty(req.getOptions())) {
                        prompt.append("选项内容：\n");
                        for (int i = 0; i < req.getOptions().size(); i++) {
                            prompt.append("  ").append((char) ('A' + i)).append(". ").append(req.getOptions().get(i)).append("\n");
                        }
                    }
                    break;
                default:
                    prompt.append("图片类型：通用教学图片\n");
                    break;
            }
            prompt.append("\n");
        } else {
            // 如果没有指定type，则使用传统方式包含所有信息
            prompt.append("题目内容：").append(req.getTitle()).append("\n");
            prompt.append("题目答案：").append(req.getAnswer()).append("\n");
            if (CollectionUtil.isNotEmpty(req.getOptions())) {
                prompt.append("题目选项：\n");
                for (int i = 0; i < req.getOptions().size(); i++) {
                    prompt.append("  ").append((char) ('A' + i)).append(". ").append(req.getOptions().get(i)).append("\n");
                }
            }
            prompt.append("\n");
        }
        
        // 如果用户提供了具体的图片生成要求，则优先使用用户输入的内容
        if (StringUtils.isNotEmpty(req.getPrompt())) {
            prompt.append("用户指定的图片内容要求：").append(req.getPrompt()).append("\n\n");
        }

        prompt.append("角色：K12教育领域的专业教学插图设计师\n\n");
        
        prompt.append("教学目标：帮助学生通过视觉化方式理解和掌握题目内容\n\n");
        
        prompt.append("图像要求：\n");
        prompt.append("1. 内容必须与题目语义完全一致，并能直观展示答案\n");
        prompt.append("2. 精确匹配：如题目是\"数一数，图中有______只小猫\"，答案是\"3\"，图像中必须有且仅有3只小猫\n");
        prompt.append("3. 对于计数类题目，图像中的物品数量必须与答案完全对应\n");
        prompt.append("4. 严禁在图片中嵌入任何文字内容\n");
        prompt.append("5. 图像必须准确匹配题目要求和答案内容，不能有歧义\n\n");
        
        prompt.append("设计规范：\n");
        prompt.append("1. 采用干净、简洁的教育类插图风格\n");
        prompt.append("2. 确保图像主体突出、边界清晰\n");
        prompt.append("3. 使用柔和、不刺眼的色彩方案\n\n");
        
        prompt.append("用途：生成的图像将用于教学试卷或练习册，请务必保证教育性和准确性。");
        
        return prompt.toString();
    }
}