package com.fs.course.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.core.domain.R;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.course.cache.FsUserCourseCategoryCacheService;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCourseAnswerLogs;
import com.fs.course.domain.FsCourseQuestionBank;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.domain.FsUserCourseCategory;
import com.fs.course.dto.FsCourseQuestionBankImportDTO;
import com.fs.course.mapper.*;
import com.fs.course.param.FsCourseQuestionAnswerUParam;
import com.fs.course.service.IFsCourseQuestionBankService;
import com.fs.course.service.cache.IFsCourseQuestionBankCacheService;
import com.fs.store.domain.FsUser;
import com.fs.store.mapper.FsUserMapper;
import com.fs.store.service.IFsStorePaymentService;
import com.fs.system.service.ISysConfigService;
import com.google.gson.JsonParser;
import jodd.util.StringUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 题库Service业务层处理
 *
 * @author fs
 * @date 2024-09-07
 */
@Service
public class FsCourseQuestionBankServiceImpl implements IFsCourseQuestionBankService
{
    @Autowired
    private FsCourseQuestionBankMapper fsCourseQuestionBankMapper;
    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private IFsStorePaymentService paymentService;
    @Autowired
    private FsCourseAnswerLogsMapper courseAnswerLogsMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private FsCourseRedPacketLogMapper redPacketLogMapper;
    @Autowired
    private FsUserCourseVideoRedPackageMapper fsUserCourseVideoRedPackageMapper;
    @Autowired
    private FsUserCourseVideoMapper courseVideoMapper;
    @Autowired
    private FsCourseWatchLogMapper courseWatchLogMapper;
    @Autowired
    private FsUserCourseCategoryMapper courseCategoryMapper;

    @Autowired
    private IFsCourseQuestionBankCacheService fsCourseQuestionBankCacheService;

    @Autowired
    private FsUserCourseCategoryCacheService fsUserCourseCategoryCacheService;

    /**
     * 查询题库
     *
     * @param id 题库主键
     * @return 题库
     */
    @Override
    public FsCourseQuestionBank selectFsCourseQuestionBankById(Long id)
    {
        return fsCourseQuestionBankMapper.selectFsCourseQuestionBankById(id);
    }

    /**
     * 查询题库列表
     *
     * @param fsCourseQuestionBank 题库
     * @return 题库
     */
    @Override
    public List<FsCourseQuestionBank> selectFsCourseQuestionBankList(FsCourseQuestionBank fsCourseQuestionBank)
    {
        List<FsCourseQuestionBank> fsCourseQuestionBanks = fsCourseQuestionBankMapper.selectFsCourseQuestionBankList(fsCourseQuestionBank);
        return fsCourseQuestionBanks;
    }

    /**
     * 新增题库
     *
     * @param fsCourseQuestionBank 题库
     * @return 结果
     */
    @Override
    public int insertFsCourseQuestionBank(FsCourseQuestionBank fsCourseQuestionBank)
    {
        fsCourseQuestionBank.setCreateTime(DateUtils.getNowDate());
        return fsCourseQuestionBankMapper.insertFsCourseQuestionBank(fsCourseQuestionBank);
    }

    /**
     * 修改题库
     *
     * @param fsCourseQuestionBank 题库
     * @return 结果
     */
    @Override
    public int updateFsCourseQuestionBank(FsCourseQuestionBank fsCourseQuestionBank)
    {
        return fsCourseQuestionBankMapper.updateFsCourseQuestionBank(fsCourseQuestionBank);
    }

    /**
     * 批量删除题库
     *
     * @param ids 需要删除的题库主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseQuestionBankByIds(Long[] ids)
    {
        return fsCourseQuestionBankMapper.deleteFsCourseQuestionBankByIds(ids);
    }

    /**
     * 删除题库信息
     *
     * @param id 题库主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseQuestionBankById(Long id)
    {
        return fsCourseQuestionBankMapper.deleteFsCourseQuestionBankById(id);
    }

    @Override
    @Transactional
    public R courseAnswer(FsCourseQuestionAnswerUParam param, Boolean isH5User) {
        FsUser user = fsUserMapper.selectFsUserByUserId(param.getUserId());
        if (user==null){
            return R.error("未识别到领取信息");
        }
        //获取配置参数
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        //本次答题正确个数
        int thisRightCount = 0;
        //用户答错次数
        int errorCount = 0;
        List<FsCourseQuestionBank> incorrectQuestions = new ArrayList<>();
        //日志id
        Long logId = null;

        new FsCourseAnswerLogs();
        FsCourseAnswerLogs rightLog;
        //判断短链类型
        if (param.getLinkType()!=null&&param.getLinkType()==1){
            rightLog = courseAnswerLogsMapper.selectRightLogByCourseVideo(param.getVideoId(), param.getUserId(),null);
            if (rightLog!=null){
                return R.error("该课程已答题完成，不可重复答题");
            }
            errorCount = courseAnswerLogsMapper.selectErrorCountByCourseVideo(param.getVideoId(), param.getUserId(),null);

        }else {
            FsCourseWatchLog log;
            if(isH5User){
               log = courseWatchLogMapper.getWatchLogByFsUser(param.getVideoId(), param.getUserId(), param.getCompanyUserId());
            } else {
                log = courseWatchLogMapper.getWatchCourseVideo(param.getUserId(), param.getVideoId(), param.getQwUserId(), param.getQwExternalId());
            }
            if (log==null){
                return R.error("无记录");
            }
            if (log.getLogType()!=2){
                return R.error("未完课");
            }
            logId = log.getLogId();

            rightLog = courseAnswerLogsMapper.selectRightLogByCourseVideo(param.getVideoId(), param.getUserId(), param.getQwUserId());
            if (rightLog != null) {
                if (log.getRewardType() != null) {
                    return R.error("该课程已答题完成，不可重复答题");
                } else {
                    return R.ok("答题成功");
                }
//                return R.error("该课程已答题完成，不可重复答题");
            }
            errorCount = courseAnswerLogsMapper.selectErrorCountByCourseVideo(param.getVideoId(), param.getUserId(),param.getQwUserId());
        }


        if (errorCount >= config.getAnswerErrorCount()) {
            return R.error("该课题到达答错次数限制");
        }
        int remainCount = config.getAnswerErrorCount()-errorCount-1;

        // 一次性获取所有问题的正确答案
        Map<Long, FsCourseQuestionBank> correctAnswersMap = fsCourseQuestionBankMapper.selectFsCourseQuestionBankByIds(
                param.getQuestions().stream().map(FsCourseQuestionBank::getId).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(FsCourseQuestionBank::getId, question -> question));

        for (FsCourseQuestionBank questionBank : param.getQuestions()) {
            FsCourseQuestionBank correctAnswer = correctAnswersMap.get(questionBank.getId());
            if (correctAnswer.getType() == 1) {
                if (questionBank.getAnswer().equals(correctAnswer.getAnswer())) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            } else if (correctAnswer.getType() == 2) {
                String[] userAnswers = convertStringToArray(questionBank.getAnswer());
                String[] correctAnswers = convertStringToArray(correctAnswer.getAnswer());

                Arrays.sort(userAnswers);
                Arrays.sort(correctAnswers);

                if (Arrays.equals(userAnswers, correctAnswers)) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            }
        }

        FsCourseAnswerLogs logs = new FsCourseAnswerLogs();
        logs.setWatchLogId(logId);
        logs.setUserId(param.getUserId());
        logs.setVideoId(param.getVideoId());
        logs.setCourseId(param.getCourseId());
        logs.setCompanyId(param.getCompanyId());
        logs.setCompanyUserId(param.getCompanyUserId());
        logs.setQwUserId(param.getQwUserId() != null ? param.getQwUserId() : null );
        logs.setQuestionJson(JSONObject.toJSONString(param.getQuestions()));
        logs.setCreateTime(new Date());
        logs.setPeriodId(param.getPeriodId());

        if (thisRightCount == param.getQuestions().size()) {
            logs.setIsRight(1);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题成功");
        } else {
            logs.setIsRight(0);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题失败").put("incorrectQuestions", incorrectQuestions).put("remain",remainCount);
        }
    }


    @Override
    @Transactional
    public R courseAnswerByfsUser(FsCourseQuestionAnswerUParam param) {
        FsUser user = fsUserMapper.selectFsUserByUserId(param.getUserId());
        if (StringUtils.isEmpty(user.getMpOpenId())){
            return R.error("未识别到领取信息");
        }
        //获取配置参数
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        //本次答题正确个数
        int thisRightCount = 0;
        //用户答错次数
        int errorCount = 0;
        List<FsCourseQuestionBank> incorrectQuestions = new ArrayList<>();

        //查询看课记录
        FsCourseWatchLog log = courseWatchLogMapper.getWatchCourseVideoByFsUser(param.getUserId(),param.getVideoId(),param.getCompanyUserId());

        if (log==null){
            return R.error("无记录");
        }
        if (log.getLogType()!=2){
            return R.error("未完课");
        }

        FsCourseAnswerLogs rightLog = courseAnswerLogsMapper.selectRightLogByCourseVideoByFsUser(log.getLogId());
        if (rightLog != null) {
            if (log.getRewardType() != null) {
                return R.error("该课程已答题完成，不可重复答题");
            } else {
                return R.ok("答题成功");
            }
        }
        errorCount = courseAnswerLogsMapper.selectErrorCountByCourseVideo(param.getVideoId(), param.getUserId(),param.getQwUserId());


        if (errorCount >= config.getAnswerErrorCount()) {
            return R.error("该课题到达答错次数限制");
        }
        int remainCount = config.getAnswerErrorCount()-errorCount-1;

        // 一次性获取所有问题的正确答案
        Map<Long, FsCourseQuestionBank> correctAnswersMap = fsCourseQuestionBankMapper.selectFsCourseQuestionBankByIds(
                param.getQuestions().stream().map(FsCourseQuestionBank::getId).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(FsCourseQuestionBank::getId, question -> question));

        for (FsCourseQuestionBank questionBank : param.getQuestions()) {
            FsCourseQuestionBank correctAnswer = correctAnswersMap.get(questionBank.getId());
            if (correctAnswer.getType() == 1) {
                if (questionBank.getAnswer().equals(correctAnswer.getAnswer())) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            } else if (correctAnswer.getType() == 2) {
                String[] userAnswers = convertStringToArray(questionBank.getAnswer());
                String[] correctAnswers = convertStringToArray(correctAnswer.getAnswer());

                Arrays.sort(userAnswers);
                Arrays.sort(correctAnswers);

                if (Arrays.equals(userAnswers, correctAnswers)) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            }
        }

        FsCourseAnswerLogs logs = new FsCourseAnswerLogs();
        logs.setWatchLogId(log.getLogId());
        logs.setUserId(param.getUserId());
        logs.setVideoId(param.getVideoId());
        logs.setCourseId(param.getCourseId());
        logs.setCompanyId(param.getCompanyId());
        logs.setCompanyUserId(param.getCompanyUserId());
        logs.setQuestionJson(JSONObject.toJSONString(param.getQuestions()));
        logs.setCreateTime(new Date());

        if (thisRightCount == param.getQuestions().size()) {
            logs.setIsRight(1);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题成功");
        } else {
            logs.setIsRight(0);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题失败").put("incorrectQuestions", incorrectQuestions).put("remain",remainCount);
        }
    }

    /**
     * 题目导入
     *
     * @param list     数据
     * @param nickName 昵称
     * @return String
     */
    @Override
    public String importData(List<FsCourseQuestionBankImportDTO> list, String nickName) {
        if (Objects.isNull(list) || list.isEmpty()) {
            throw new ServiceException("导入数据不能为空");
        }

        ImportResult result = new ImportResult();
        List<FsCourseQuestionBank> importData = new ArrayList<>();
        Map<String, FsUserCourseCategory> categoryData = courseCategoryMapper.queryAllCategoryData();

        for (FsCourseQuestionBankImportDTO importDTO : list) {
            try {
                // 数据验证
                ValidationResult validation = validateImportData(importDTO);
                if (!validation.isValid()) {
                    result.addFailure(importDTO.getTitle(), validation.getErrorMessage());
                    continue;
                }

                // 构建题目对象
                FsCourseQuestionBank questionBank = buildQuestionBank(importDTO, categoryData, nickName);
                importData.add(questionBank);
                result.addSuccess(importDTO.getTitle());

            } catch (Exception e) {
                result.addFailure(importDTO.getTitle(), "导入异常: " + e.getMessage());
            }
        }

        // 批量保存
        if (!importData.isEmpty()) {
            fsCourseQuestionBankMapper.insertFsCourseQuestionBankBatch(importData);
        }

        return result.buildResultMessage();
    }

    /**
     * 验证导入数据
     */
    private ValidationResult validateImportData(FsCourseQuestionBankImportDTO importDTO) {
        // 基础字段验证
        if (StringUtils.isBlank(importDTO.getTitle())) {
            return ValidationResult.fail("标题不能为空");
        }
        if (StringUtils.isBlank(importDTO.getType())) {
            return ValidationResult.fail("类别不能为空");
        }
        if (Objects.isNull(importDTO.getSort())) {
            return ValidationResult.fail("排序不能为空");
        }
        if (StringUtils.isBlank(importDTO.getAnswer())) {
            return ValidationResult.fail("答案不能为空");
        }

        // 选项验证
        ValidationResult optionValidation = validateOptions(importDTO);
        if (!optionValidation.isValid()) {
            return optionValidation;
        }

        // 题目类型验证
        if (!isValidQuestionType(importDTO.getType())) {
            return ValidationResult.fail("题目类型不正确，仅支持单选题和多选题");
        }

        // 答案验证
        return validateAnswers(importDTO);
    }

    /**
     * 验证选项
     */
    private ValidationResult validateOptions(FsCourseQuestionBankImportDTO importDTO) {
        if (StringUtils.isBlank(importDTO.getQuestionA()) ||
                StringUtils.isBlank(importDTO.getQuestionB()) ||
                StringUtils.isBlank(importDTO.getQuestionC())) {
            return ValidationResult.fail("选项A、B、C不能为空");
        }
        return ValidationResult.success();
    }

    /**
     * 验证题目类型
     */
    private boolean isValidQuestionType(String type) {
        return type.contains("单") || type.contains("多");
    }

    /**
     * 验证答案
     */
    private ValidationResult validateAnswers(FsCourseQuestionBankImportDTO importDTO) {
        String[] answers = importDTO.getAnswer().trim().toUpperCase().split("");

        // 多选题答案数量验证
        if (importDTO.getType().contains("多") && answers.length < 2) {
            return ValidationResult.fail("多选题答案不能少于2个");
        }

        // 答案选项验证
        List<String> validOptions = getValidOptions(importDTO);
        for (String answer : answers) {
            if (!validOptions.contains(answer.trim())) {
                return ValidationResult.fail("答案不在选项中");
            }
        }

        return ValidationResult.success();
    }

    /**
     * 获取有效选项列表
     */
    private List<String> getValidOptions(FsCourseQuestionBankImportDTO importDTO) {
        List<String> options = new ArrayList<>(Arrays.asList("A", "B", "C"));
        if (StringUtils.isNotBlank(importDTO.getQuestionD())) {
            options.add("D");
        }
        return options;
    }

    /**
     * 构建题目对象
     */
    private FsCourseQuestionBank buildQuestionBank(FsCourseQuestionBankImportDTO importDTO,
                                                   Map<String, FsUserCourseCategory> categoryData,
                                                   String nickName) {
        FsCourseQuestionBank questionBank = new FsCourseQuestionBank();

        // 基础信息
        questionBank.setTitle(importDTO.getTitle());
        questionBank.setType(getQuestionTypeCode(importDTO.getType()));
        questionBank.setSort(importDTO.getSort());
        questionBank.setStatus(parseStatus(importDTO.getStatus()));
        questionBank.setCreateTime(new Date());
        questionBank.setCreateBy(nickName);

        // 分类信息
        setQuestionCategories(questionBank, importDTO, categoryData);

        // 选项和答案
        questionBank.setQuestion(buildQuestionOptions(importDTO));
        questionBank.setAnswer(buildAnswer(importDTO));

        return questionBank;
    }

    /**
     * 获取题目类型编码
     */
    private Long getQuestionTypeCode(String type) {
        return type.contains("单") ? 1L : 2L;
    }

    /**
     * 解析状态
     */
    private Long parseStatus(String statusStr) {
        if (StringUtils.isBlank(statusStr)) {
            return 1L;
        }
        try {
            return statusStr.contains("正常") ? 1L : 0L;
        } catch (Exception e) {
            return 1L;
        }
    }

    /**
     * 设置题目分类
     */
    private void setQuestionCategories(FsCourseQuestionBank questionBank,
                                       FsCourseQuestionBankImportDTO importDTO,
                                       Map<String, FsUserCourseCategory> categoryData) {
        if (StringUtils.isBlank(importDTO.getQuestionType())) {
            return;
        }

        FsUserCourseCategory category = categoryData.get(importDTO.getQuestionType().trim());
        if (category != null) {
            questionBank.setQuestionType(category.getCateId());

            // 子分类
            if (StringUtils.isNotBlank(importDTO.getQuestionSubTyp())) {
                FsUserCourseCategory subCategory = categoryData.get(importDTO.getQuestionSubTyp().trim());
                if (subCategory != null && Objects.equals(subCategory.getPid(), category.getCateId())) {
                    questionBank.setQuestionSubType(subCategory.getCateId());
                }
            }
        }
    }

    /**
     * 构建选项JSON
     */
    private String buildQuestionOptions(FsCourseQuestionBankImportDTO importDTO) {
        JSONArray questionArray = new JSONArray();
        String[] answers = importDTO.getAnswer().trim().toUpperCase().split("");
        List<String> answerList = Arrays.asList(answers);

        // 构建选项
        addOption(questionArray, importDTO.getQuestionA(), answerList.contains("A"), 0);
        addOption(questionArray, importDTO.getQuestionB(), answerList.contains("B"), 1);
        addOption(questionArray, importDTO.getQuestionC(), answerList.contains("C"), 2);

        if (StringUtils.isNotBlank(importDTO.getQuestionD())) {
            addOption(questionArray, importDTO.getQuestionD(), answerList.contains("D"), 3);
        }

        return JSON.toJSONString(questionArray);
    }

    /**
     * 添加选项
     */
    private void addOption(JSONArray questionArray, String optionText,
                           boolean isAnswer, int indexId) {
        JSONObject option = new JSONObject();
        option.put("name", optionText.trim());
        option.put("isAnswer", isAnswer ? 1 : 0);
        option.put("indexId", indexId);
        questionArray.add(option);
    }

    /**
     * 构建答案
     */
    private String buildAnswer(FsCourseQuestionBankImportDTO importDTO) {
        String[] answers = importDTO.getAnswer().trim().toUpperCase().split("");
        List<String> answerList = Arrays.asList(answers);

        Map<String, String> questionMap = new HashMap<>();
        questionMap.put("A", importDTO.getQuestionA().trim());
        questionMap.put("B", importDTO.getQuestionB().trim());
        questionMap.put("C", importDTO.getQuestionC().trim());
        questionMap.put("D", importDTO.getQuestionD().trim());

        List<String> selectedAnswers = answerList.stream()
                .map(questionMap::get)
                .collect(Collectors.toList());

        if (answerList.size() == 1) {
            return selectedAnswers.get(0);
        }

        return JSON.toJSONString(selectedAnswers);
    }

    // 辅助类
    @Getter
    private static class ValidationResult {
        private final boolean valid;
        private final String errorMessage;

        private ValidationResult(boolean valid, String errorMessage) {
            this.valid = valid;
            this.errorMessage = errorMessage;
        }

        public static ValidationResult success() {
            return new ValidationResult(true, null);
        }

        public static ValidationResult fail(String message) {
            return new ValidationResult(false, message);
        }

    }

    private static class ImportResult {
        private int successNum = 0;
        private int failureNum = 0;
        private final StringBuilder successMsg = new StringBuilder();
        private final StringBuilder errorMsg = new StringBuilder();

        public void addSuccess(String title) {
            successNum++;
            successMsg.append("<br/>").append(successNum).append("、题目 ").append(title).append(" 导入成功");
        }

        public void addFailure(String title, String error) {
            failureNum++;
            errorMsg.append("<br/>").append(failureNum).append("、题目 ").append(title).append(" 导入失败：").append(error);
        }

        public String buildResultMessage() {
            return "导入完成！成功" + successNum + " 条，失败" + failureNum + "条。" + errorMsg + successMsg;
        }
    }


    /**
     * 根据ID查询题目
     * @param ids   ids
     * @return  list
     */
    @Override
    public List<FsCourseQuestionBank> selectFsCourseQuestionBankByIds(List<Long> ids) {
        return fsCourseQuestionBankMapper.selectFsCourseQuestionBankByIds(ids);
    }

    @Override
    public List<FsCourseQuestionBank> selectFsCourseQuestionBankListExport(FsCourseQuestionBank fsCourseQuestionBank) {
        List<FsCourseQuestionBank> fsCourseQuestionBanks = this.selectFsCourseQuestionBankList(fsCourseQuestionBank);

        for (FsCourseQuestionBank courseQuestionBank : fsCourseQuestionBanks) {

            if(StringUtil.isNotBlank(courseQuestionBank.getQuestion())) {
                // 问题列表多个 以分隔符 | 结尾
                JSONArray questionArr = com.alibaba.fastjson.JSON.parseArray(courseQuestionBank.getQuestion());
                List<String> questionOpt = new ArrayList<>();
                for(int i=0;i<questionArr.size();i++){
                    JSONObject jsonObject = questionArr.getJSONObject(i);
                    String name = jsonObject.getString("name");
                    questionOpt.add(name);
                }
                courseQuestionBank.setQuestionOption(String.join("|",questionOpt));
            }

            if(StringUtil.isNotBlank(courseQuestionBank.getAnswer())) {
                // 如果是json数组
                if(JsonParser.parseString(courseQuestionBank.getAnswer()).isJsonArray()) {
                    String answerOpt = String.join("|", JSONUtil.parseArray(courseQuestionBank.getAnswer()).toList(String.class));
                    courseQuestionBank.setAnswerOption(answerOpt);
                } else {
                    courseQuestionBank.setAnswerOption(courseQuestionBank.getAnswer());
                }
            }

            // 问题类别
            if(ObjectUtils.isNotNull(courseQuestionBank.getQuestionType())) {
                String questionType = fsCourseQuestionBankCacheService.selectFsUserCourseCategoryByCateId(courseQuestionBank.getQuestionType());

                courseQuestionBank.setQuestionTypeStr(questionType);
            }

            // 题目类型
            if(ObjectUtils.isNotNull(courseQuestionBank.getType())) {
                String type = courseQuestionBank.getType() == 1 ? "单选" : "多选";
                courseQuestionBank.setTypeStr(type);
            }

            // 题目子类别
            if(ObjectUtils.isNotNull(courseQuestionBank.getQuestionSubType())) {
                String questionType = fsCourseQuestionBankCacheService.selectFsUserCourseCategoryByCateId(courseQuestionBank.getQuestionSubType());
                courseQuestionBank.setQuestionSubTypeStr(questionType);
            }

        }
        return fsCourseQuestionBanks;
    }

    @Override
    public String selectNameByCateId(Long cateId) {
        return fsCourseQuestionBankMapper.selectNameByCateId(cateId);
    }

    /**
     * 题目导出
     * @param fsCourseQuestionBank  参数
     * @return  list
     */
    @Override
    public List<FsCourseQuestionBankImportDTO> exportData(FsCourseQuestionBank fsCourseQuestionBank) {
        List<FsCourseQuestionBank> fsCourseQuestionBanks = fsCourseQuestionBankMapper.selectFsCourseQuestionBankList(fsCourseQuestionBank);
        Map<Long, FsUserCourseCategory> categoryMap = courseCategoryMapper.queryAllIdKeyCategoryData();

        // 辅助方法：根据ID从Map获取分类名称
        Function<Long, String> getCategoryName = id -> Optional.ofNullable(categoryMap.get(id))
                .map(FsUserCourseCategory::getCateName)
                .orElse(null);

        Map<Integer, BiConsumer<FsCourseQuestionBankImportDTO, String>> questionSetters = new HashMap<>();
        questionSetters.put(0, FsCourseQuestionBankImportDTO::setQuestionA);
        questionSetters.put(1, FsCourseQuestionBankImportDTO::setQuestionB);
        questionSetters.put(2, FsCourseQuestionBankImportDTO::setQuestionC);
        questionSetters.put(3, FsCourseQuestionBankImportDTO::setQuestionD);

        Map<Integer, String> answerLettersMap = new HashMap<>();
        answerLettersMap.put(0, "A");
        answerLettersMap.put(1, "B");
        answerLettersMap.put(2, "C");
        answerLettersMap.put(3, "D");

        return fsCourseQuestionBanks.stream().map(q -> {
            FsCourseQuestionBankImportDTO dto = new FsCourseQuestionBankImportDTO();
            dto.setTitle(q.getTitle());
            dto.setSort(q.getSort());
            dto.setType(q.getType() == 1 ? "单选" : "多选");
            Optional.ofNullable(q.getQuestionType()).map(getCategoryName).ifPresent(dto::setQuestionType);
            Optional.ofNullable(q.getQuestionSubType()).map(getCategoryName).ifPresent(dto::setQuestionSubTyp);
            dto.setStatus(q.getStatus() == 1 ? "正常" : "停用");

            StringBuilder answersBuilder = new StringBuilder();
            JSONArray array = JSON.parseArray(q.getQuestion());
            array.forEach(jsonObject -> {
                JSONObject json = (JSONObject) jsonObject;
                int index = json.getInteger("indexId");
                String name = json.getString("name");
                int isAnswer = json.getInteger("isAnswer");

                questionSetters.get(index).accept(dto, name);
                if (isAnswer == 1) {
                    answersBuilder.append(answerLettersMap.get(index));
                }

            });
            dto.setAnswer(answersBuilder .toString());
            return dto;
        }).collect(Collectors.toList());
    }


    public static String[] convertStringToArray(String inputString) {
        String cleanString = inputString.replaceAll("[\\[\\]\"\\s]", "");
        return cleanString.split(",");
    }
}
