package com.hotwj.platform.reportStatistics.provider.security;

import com.hotwj.platform.reportStatistics.domain.vo.security.StudyDetailData;
import com.hotwj.platform.reportStatistics.domain.vo.security.StudyRecordCourseVo;
import com.hotwj.platform.reportStatistics.mapper.LedgerReportMapper;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import com.hotwj.platform.securityManagement.training.domain.vo.HotTrainingVo;
import com.hotwj.platform.securityManagement.training.service.IHotTrainingService;
import com.hotwj.platform.securityManagement.trainingAnswer.domain.vo.HotTrainingAnswerRecordVo;
import com.hotwj.platform.securityManagement.trainingAnswer.mapper.HotTrainingAnswerRecordMapper;
import com.hotwj.platform.securityManagement.trainingParticipant.domain.bo.HotTrainingParticipantBo;
import com.hotwj.platform.securityManagement.trainingParticipant.domain.vo.HotTrainingParticipantVo;
import com.hotwj.platform.securityManagement.trainingParticipant.service.IHotTrainingParticipantService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

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

@Component
@RequiredArgsConstructor
public class StudyDetailProvider implements IReportDataProvider {

    private final IHotTrainingService trainingService;
    private final ISysCompanyService sysCompanyService;
    private final HotTrainingAnswerRecordMapper trainingAnswerRecordMapper;
    private final LedgerReportMapper ledgerReportMapper;
    private final IHotTrainingParticipantService trainingParticipantService;

    @Override
    public String getTemplateCode() {
        return "templates/securityManage/studyDetail.html.vm";
    }

    @Override
    public String getReportTitle() {
        return "在线安全学习考试明细";
    }

    @Override
    public Map<String, Object> prepareData(Map<String, Object> params) {
        // 1. 初始化上下文
        Map<String, Object> ctx = initContext(params);

        // 2. 参数校验
        Long companyId = (Long) params.get("companyId");
        Long trainingId = (Long) params.get("trainingId");
        String userId = (String) params.get("userId");
        if (companyId == null || trainingId == null || StringUtils.isBlank(userId)) {
            return ctx;
        }

        // 3. 基础信息查询（培训计划、公司）
        HotTrainingVo training = trainingService.queryById(trainingId);
        if (training == null) {
            return ctx;
        }
        ctx.put("training", training);
        ctx.put("companyName", getCompanyName(companyId));

        // 4. 构建详情数据
        StudyDetailData data = buildStudyDetailData(companyId, trainingId, userId);
        ctx.put("data", data);

        // 5. 设置其他辅助数据
        fillExtraContext(ctx, data);

        return ctx;
    }

    /**
     * 初始化上下文（二维码等）
     */
    private Map<String, Object> initContext(Map<String, Object> params) {
        Map<String, Object> ctx = new HashMap<>();
        ctx.put("verifyUrl", params.get("verifyUrl"));
        ctx.put("verifyQrBase64", params.get("verifyQrBase64"));
        return ctx;
    }

    /**
     * 获取公司名称
     */
    private String getCompanyName(Long companyId) {
        SysCompanyVo company = sysCompanyService.queryById(companyId);
        return company != null ? StringUtils.blankToDefault(company.getCompanyName(), "") : "";
    }

    /**
     * 构建主数据对象
     */
    private StudyDetailData buildStudyDetailData(Long companyId, Long trainingId, String userId) {
        StudyDetailData data = new StudyDetailData();

        // 1. 设置学员信息
        fillParticipantInfo(data, companyId, trainingId, userId);

        // 2. 设置课程列表
        fillCourseList(data, companyId, trainingId, userId);

        // 3. 设置答题明细及统计
        fillAnswerDetails(data, companyId, trainingId, userId);

        return data;
    }

    /**
     * 填充学员基本信息
     */
    private void fillParticipantInfo(StudyDetailData data, Long companyId, Long trainingId, String userId) {
        HotTrainingParticipantBo participantBo = new HotTrainingParticipantBo();
        participantBo.setCompanyId(companyId);
        participantBo.setTrainingId(trainingId);
        participantBo.setUserId(userId);
        participantBo.setIsDeleted(0L);
        List<HotTrainingParticipantVo> participants = trainingParticipantService.queryList(participantBo);
        if (participants != null && !participants.isEmpty()) {
            HotTrainingParticipantVo p = participants.get(0);
            data.setUserName(StringUtils.blankToDefault(p.getUserName(), ""));
        }
    }

    /**
     * 填充课程列表
     */
    private void fillCourseList(StudyDetailData data, Long companyId, Long trainingId, String userId) {
        List<StudyRecordCourseVo> courseList = ledgerReportMapper.selectStudyRecordCourses(companyId, trainingId, userId);
        if (courseList != null) {
            for (StudyRecordCourseVo vo : courseList) {
                if (vo.getDuration() != null) {
                    // 秒 -> 分钟，向上取整
                    vo.setDuration((long) Math.ceil(vo.getDuration() / 60.0));
                }
            }
        }
        data.setCourseList(courseList);
    }

    /**
     * 填充答题明细及统计
     */
    private void fillAnswerDetails(StudyDetailData data, Long companyId, Long trainingId, String userId) {
        List<HotTrainingAnswerRecordVo> detailList = trainingAnswerRecordMapper.selectPlanStudyDetailByTrainingAndUser(companyId, trainingId, userId);
        if (detailList == null || detailList.isEmpty()) {
            return;
        }

        data.setTrainingName(detailList.get(0).getTrainingName()); // 设置计划名称
        data.setPassScore(detailList.get(0).getPassScore());

        List<HotTrainingAnswerRecordVo> singleList = new ArrayList<>();
        List<HotTrainingAnswerRecordVo> multiList = new ArrayList<>();
        List<HotTrainingAnswerRecordVo> judgeList = new ArrayList<>();

        int singleCount = 0;
        int multiCount = 0;
        int judgeCount = 0;
        long singleTotalScore = 0;
        long multiTotalScore = 0;
        long judgeTotalScore = 0;
        long totalScore = 0;
        long studentGainedScore = 0;

        for (HotTrainingAnswerRecordVo ans : detailList) {
            Long type = ans.getQuestionType();
            Long score = ans.getQuestionScore() != null ? ans.getQuestionScore() : 0L;

            if (type != null) {
                if (type == 1) { // 单选
                    singleCount++;
                    singleTotalScore += score;
                    ans.setQuestionOrder((long) (singleList.size() + 1));
                    singleList.add(ans);
                } else if (type == 2) { // 多选
                    multiCount++;
                    multiTotalScore += score;
                    ans.setQuestionOrder((long) (multiList.size() + 1));
                    multiList.add(ans);
                } else if (type == 3) { // 判断
                    judgeCount++;
                    judgeTotalScore += score;
                    ans.setQuestionOrder((long) (judgeList.size() + 1));
                    judgeList.add(ans);
                }
            }
            totalScore += score;

            if (ans.getGainedScore() != null) {
                studentGainedScore += ans.getGainedScore();
            }
        }

        data.setSingleChoiceList(singleList);
        data.setMultiChoiceList(multiList);
        data.setJudgeList(judgeList);

        data.setSingleCount(singleCount);
        data.setMultiCount(multiCount);
        data.setJudgeCount(judgeCount);
        data.setSingleTotalScore(singleTotalScore);
        data.setMultiTotalScore(multiTotalScore);
        data.setJudgeTotalScore(judgeTotalScore);
        data.setTotalScore(totalScore);
        data.setExamScore(studentGainedScore);
    }

    /**
     * 填充额外的上下文（兼容旧模板等需求）
     */
    private void fillExtraContext(Map<String, Object> ctx, StudyDetailData data) {
        if (data.getTotalScore() != null) {
            ctx.put("paperTotalScore", data.getTotalScore());
        }

        // 兼容旧模板变量
        // 为了兼容，我们需要重新获取 raw list 或者从 categorized lists 重建，
        // 但这里为了简化，我们假设模板已经更新或者我们只传递必要的最少信息。
        // 如果旧模板严重依赖 records 和 r0，可能需要从 data 中反向构建一个临时 list 或者保留原始 detailList
        // 考虑到代码清晰度，建议更新模板。但为了保持行为一致：
        List<HotTrainingAnswerRecordVo> allRecords = new ArrayList<>();
        if (data.getSingleChoiceList() != null) allRecords.addAll(data.getSingleChoiceList());
        if (data.getMultiChoiceList() != null) allRecords.addAll(data.getMultiChoiceList());
        if (data.getJudgeList() != null) allRecords.addAll(data.getJudgeList());

        if (!allRecords.isEmpty()) {
            ctx.put("records", allRecords);
            ctx.put("r0", allRecords.get(0));
        }
    }
}
