package com.sundot.airport.exam.adapter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sundot.airport.exam.common.service.QuesOptService;
import com.sundot.airport.exam.domain.DailyTask;
import com.sundot.airport.exam.domain.DailyTaskDetail;
import com.sundot.airport.exam.domain.QuesOpt;
import com.sundot.airport.exam.dto.SubmitAnswerDTO;
import com.sundot.airport.exam.dto.SubmitResultDTO;
import com.sundot.airport.exam.enums.QuesCompScoreTypeEnum;
import com.sundot.airport.exam.enums.QuesTypeEnum;
import com.sundot.airport.exam.logic.eighteen.model.params.SubmitExamParam;
import com.sundot.airport.exam.logic.eighteen.model.params.subparam.UserOptionParam;
import com.sundot.airport.exam.logic.eighteen.model.result.ExamGetResult;
import com.sundot.airport.exam.logic.eighteen.model.result.ExamQuesOptResult;
import com.sundot.airport.exam.logic.eighteen.model.result.ExamQuestionResult;
import com.sundot.airport.exam.logic.eighteen.model.result.SubmitExamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <b>功能名：</b>DailyTaskToExamAdapter<br>
 * <b>说明：</b> 每日任务到考试格式的适配器 <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：</b><br>
 *
 * @author 2025-01-16
 */
@Component
public class DailyTaskToExamAdapter {

    private static final Logger log = LoggerFactory.getLogger(DailyTaskToExamAdapter.class);

    @Autowired
    private QuesOptService quesOptService;

    /**
     * 将每日任务转换为考试格式
     *
     * @param task    每日任务
     * @param details 任务明细列表
     * @return 考试结果（兼容十八大格式）
     */
    public ExamGetResult convertDailyTaskToExam(DailyTask task, List<DailyTaskDetail> details) {
        log.info("开始转换每日任务到考试格式: taskId={}", task.getDtId());

        ExamGetResult result = new ExamGetResult();

        // 映射考试基本信息
        result.setErId(task.getDtId());                               // 考试记录ID = 任务ID
        result.setExId("DAILY_TASK_" + task.getDtBusinessDate());    // 虚拟考试ID（基于业务日期）
        result.setExName("每日抽问抽答");                              // 固定名称
        result.setExExamTime(task.getDtTimeLimit());                  // 时间限制（秒）
        result.setExExamCount(1);                                     // 每天1次（每个任务独立）
        result.setTotalScore("100");                                  // 总分100
        result.setExEnableAns(true);                                  // 允许查看答案
        result.setTpId("DAILY_TASK_TP");                              // 虚拟试卷ID

        // 转换题目列表
        List<ExamQuestionResult> questions = details.stream()
                .map(this::convertToExamQuestion)
                .collect(Collectors.toList());
        result.setQuestion(questions);

        log.info("转换完成: taskId={}, questionCount={}", task.getDtId(), questions.size());
        return result;
    }

    /**
     * 将任务明细转换为考试题目格式
     *
     * @param detail 任务明细
     * @return 考试题目
     */
    private ExamQuestionResult convertToExamQuestion(DailyTaskDetail detail) {
        ExamQuestionResult question = new ExamQuestionResult();

        // 基本信息
        question.setQuId(detail.getDtdQuesId());
        question.setQuContent(detail.getDtdQuesContent());
        question.setQuType(QuesTypeEnum.valueOf(detail.getDtdQuesType()));
        question.setQcId(detail.getDtdModuleId());
        question.setQcName(detail.getDtdModuleName());

        // 计分信息
        question.setTpqTotalScore(detail.getDtdScore().intValue());
        question.setTpqCompType(QuesCompScoreTypeEnum.LEFT);  // 默认左增（答对加分）
        question.setTpqLeftScore(detail.getDtdScore().intValue());
        question.setTpqRightScore(0);

        // 查询选项列表
        List<ExamQuesOptResult> options = loadQuestionOptions(detail.getDtdQuesId());
        question.setOptions(options);

        return question;
    }

    /**
     * 加载题目选项
     *
     * @param quesId 题目ID
     * @return 选项列表
     */
    private List<ExamQuesOptResult> loadQuestionOptions(String quesId) {
        LambdaQueryWrapper<QuesOpt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuesOpt::getQuId, quesId);
        wrapper.eq(QuesOpt::getDelStatus, 0);
        wrapper.orderByAsc(QuesOpt::getSort);

        List<QuesOpt> quesOpts = quesOptService.list(wrapper);

        return quesOpts.stream()
                .map(this::convertToExamOption)
                .collect(Collectors.toList());
    }

    /**
     * 转换题目选项
     *
     * @param quesOpt 题目选项实体
     * @return 考试选项结果
     */
    private ExamQuesOptResult convertToExamOption(QuesOpt quesOpt) {
        ExamQuesOptResult optResult = new ExamQuesOptResult();
        BeanUtils.copyProperties(quesOpt, optResult);
        return optResult;
    }

    /**
     * 将十八大考试提交参数转换为每日任务提交参数
     *
     * @param examParam 考试提交参数
     * @return 任务提交参数
     */
    public SubmitAnswerDTO convertExamParamToTaskSubmit(SubmitExamParam examParam) {
        log.info("转换考试提交参数到任务格式: erId={}", examParam.getErId());

        SubmitAnswerDTO taskDto = new SubmitAnswerDTO();
        taskDto.setTaskId(examParam.getErId()); // erId实际存的是taskId
        taskDto.setSubmitType(1); // 1-手动提交

        // 转换答案列表
        List<SubmitAnswerDTO.AnswerItem> answers = new ArrayList<>();
        if (examParam.getOptions() != null) {
            for (UserOptionParam option : examParam.getOptions()) {
                SubmitAnswerDTO.AnswerItem item = new SubmitAnswerDTO.AnswerItem();
                item.setQuestionId(option.getQuId());
                item.setUserAnswer(option.getEroConnNo());
                answers.add(item);
            }
        }
        taskDto.setAnswers(answers);

        return taskDto;
    }

    /**
     * 将任务提交结果转换为考试提交结果
     *
     * @param taskResult 任务提交结果
     * @return 考试提交结果
     */
    public SubmitExamResult convertTaskResultToExamResult(SubmitResultDTO taskResult) {
        log.info("转换任务提交结果到考试格式: taskId={}", taskResult.getTaskId());

        SubmitExamResult examResult = new SubmitExamResult();
        examResult.setErId(taskResult.getTaskId());

        return examResult;
    }
}
