package cn.iocoder.byzs.module.bjdx.service.coursequestion;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.byzs.framework.common.pojo.PageResult;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursequestion.vo.CourseQuestionPageReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursequestion.vo.CourseQuestionRespVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursequestion.vo.CourseQuestionSaveReqVO;
import cn.iocoder.byzs.module.bjdx.dal.dataobject.coursequestion.CourseQuestionDO;
import cn.iocoder.byzs.module.bjdx.dal.dataobject.coursequestoption.CourseQuestOptionDO;
import cn.iocoder.byzs.module.bjdx.dal.mysql.coursequestion.CourseQuestionMapper;
import cn.iocoder.byzs.module.bjdx.dal.mysql.coursequestoption.CourseQuestOptionMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.byzs.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.byzs.module.bjdx.enums.ErrorCodeConstants.COURSE_QUESTION_NOT_EXISTS;

/**
 * 课程-试题 Service 实现类
 *
 * @author lyb
 */
@Service
@Validated
public class CourseQuestionServiceImpl implements CourseQuestionService {

    @Resource
    private CourseQuestionMapper courseQuestionMapper;
    @Resource
    private CourseQuestOptionMapper courseQuestOptionMapper;

    @Override
    public Long createCourseQuestion(CourseQuestionSaveReqVO createReqVO) {
        // 插入
        CourseQuestionDO courseQuestion = BeanUtils.toBean(createReqVO, CourseQuestionDO.class);
        courseQuestionMapper.insert(courseQuestion);
        // 返回
        return courseQuestion.getId();
    }

    @Override
    public void updateCourseQuestion(CourseQuestionSaveReqVO updateReqVO) {
        // 校验存在
        validateCourseQuestionExists(updateReqVO.getId());
        // 更新
        CourseQuestionDO updateObj = BeanUtils.toBean(updateReqVO, CourseQuestionDO.class);

        if (updateObj.getId() != null) {
            List<CourseQuestOptionDO> courseQuestOptionDOS = courseQuestOptionMapper.selectListByQuestId(Collections.singleton(updateObj.getId()));
            courseQuestOptionDOS.forEach(item -> {
                item.setCqoIsAnswer(Objects.equals(item.getId(), updateObj.getCqQuestAnswerId()) ? "true" : "false");
                courseQuestOptionMapper.updateById(item);
            });
        }

        courseQuestionMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseQuestion(Long id) {
        // 校验存在
        validateCourseQuestionExists(id);
        // 删除
        courseQuestionMapper.deleteById(id);
    }

    @Override
        public void deleteCourseQuestionListByIds(List<Long> ids) {
        // 校验存在
        validateCourseQuestionExists(ids);
        // 删除
        courseQuestionMapper.deleteByIds(ids);
        }

    private void validateCourseQuestionExists(List<Long> ids) {
        List<CourseQuestionDO> list = courseQuestionMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(COURSE_QUESTION_NOT_EXISTS);
        }
    }

    private void validateCourseQuestionExists(Long id) {
        if (courseQuestionMapper.selectById(id) == null) {
            throw exception(COURSE_QUESTION_NOT_EXISTS);
        }
    }

    @Override
    public CourseQuestionDO getCourseQuestion(Long id) {
        return courseQuestionMapper.selectById(id);
    }

    @Override
    public PageResult<CourseQuestionDO> getCourseQuestionPage(CourseQuestionPageReqVO pageReqVO) {
        return courseQuestionMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<CourseQuestionDO> getCourseQuestionNoPage(CourseQuestionPageReqVO pageReqVO) {
        return courseQuestionMapper.selectPage(pageReqVO);
    }

    /**
     * 设置课程配置-试题列表(引用)
     *
     * @param quesIdList 课程配置的试题列表
     */
    @Override
    public Map<Long, CourseQuestionRespVO> setCourseQuestionList(List<Long> quesIdList) {
        if (quesIdList.isEmpty() || quesIdList.stream().allMatch(Objects::isNull)) {
            return Collections.emptyMap();
        }

        Map<Long, CourseQuestionRespVO> map = new HashMap<>();

        //课程配置试题Map
        Map<Long, List<CourseQuestionRespVO>> questionMap;
        //课程配置试题选项Map
        Map<Long, List<CourseQuestOptionDO>> questOptionMap = new HashMap<>();

        questionMap = courseQuestionMapper.selectByIds(quesIdList).stream()
                .map(doItem -> BeanUtils.toBean(doItem, CourseQuestionRespVO.class))
                .collect(Collectors.groupingBy(CourseQuestionRespVO::getId));

        if(!questionMap.isEmpty()) {
            questOptionMap = courseQuestOptionMapper.selectListByQuestId(questionMap.keySet()).stream().collect(Collectors.groupingBy(CourseQuestOptionDO::getCqoQuestId));

            //封装
            Map<Long, List<CourseQuestOptionDO>> finalQuestOptionMap = questOptionMap;
            quesIdList.forEach(questId -> {
                CourseQuestionRespVO courseQuestion = questionMap.get(questId).get(0);
                courseQuestion.setCourseQuestOptionList(finalQuestOptionMap.get(questId));
                map.put(questId, courseQuestion);
            });
            return map;
        }
        return Collections.emptyMap();
    }
}