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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.byzs.module.bjdx.controller.admin.courseconfig.vo.CourseConfigPageReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.courseconfig.vo.CourseConfigSaveReqVO;
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.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 org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

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

import cn.iocoder.byzs.module.bjdx.controller.admin.courseconfig.vo.*;
import cn.iocoder.byzs.module.bjdx.dal.dataobject.courseconfig.CourseConfigDO;
import cn.iocoder.byzs.framework.common.pojo.PageResult;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;

import cn.iocoder.byzs.module.bjdx.dal.mysql.courseconfig.CourseConfigMapper;

import static cn.iocoder.byzs.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.byzs.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.byzs.module.bjdx.enums.ErrorCodeConstants.*;

/**
 * 课程配置 Service 实现类
 *
 * @author 博雅智算源码
 */
@Service
@Validated
public class CourseConfigServiceImpl implements CourseConfigService {

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

    @Override
    public Long createCourseConfig(CourseConfigSaveReqVO createReqVO) {
        // 插入
        CourseConfigDO courseConfig = BeanUtils.toBean(createReqVO, CourseConfigDO.class);
        courseConfigMapper.insert(courseConfig);
        // 返回
        return courseConfig.getId();
    }

    @Override
    public void updateCourseConfig(CourseConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateCourseConfigExists(updateReqVO.getId());
        // 更新
        CourseConfigDO updateObj = BeanUtils.toBean(updateReqVO, CourseConfigDO.class);
        courseConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseConfig(Long id) {
        // 校验存在
        validateCourseConfigExists(id);
        // 删除
        courseConfigMapper.deleteById(id);
    }

    @Override
        public void deleteCourseConfigListByIds(List<Long> ids) {
        // 校验存在
        validateCourseConfigExists(ids);
        // 删除
        courseConfigMapper.deleteByIds(ids);
        }

    private void validateCourseConfigExists(List<Long> ids) {
        List<CourseConfigDO> list = courseConfigMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(COURSE_CONFIG_NOT_EXISTS);
        }
    }

    private void validateCourseConfigExists(Long id) {
        if (courseConfigMapper.selectById(id) == null) {
            throw exception(COURSE_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public CourseConfigDO getCourseConfig(Long id) {
        return courseConfigMapper.selectById(id);
    }

    @Override
    public List<CourseConfigRespVO> getCourseConfigQuestion(Long ccCourseId) {

        //课程配置列表
        List<CourseConfigPageReqVO> courseConfigPageReqVOS = courseConfigMapper.selectCourseConfigPage(new CourseConfigPageReqVO().setCcCourseId(Math.toIntExact(ccCourseId)));

        //课程配置列表转VO
        List<CourseConfigRespVO> courseConfigList = courseConfigPageReqVOS.stream()
                .map(doItem -> BeanUtils.toBean(doItem, CourseConfigRespVO.class))
                .toList();
        if (courseConfigList.isEmpty()) {return courseConfigList;}

        List<Long> quesIdList = courseConfigList.stream()
                .map(CourseConfigRespVO::getCcQuestId)
                .toList();
        //课程配置试题Map
        Map<Long, List<CourseQuestionRespVO>> questionMap;
        //课程配置试题选项Map
        Map<Long, List<CourseQuestOptionDO>> questOptionMap = new HashMap<>();

        if (quesIdList.isEmpty()) {
            questionMap = courseQuestionMapper.selectByIds(quesIdList).stream()
                    .map(doItem -> BeanUtils.toBean(doItem, CourseQuestionRespVO.class))
                    .collect(Collectors.groupingBy(CourseQuestionRespVO::getId));
        } else {
            questionMap = new HashMap<>();
        }
        if (quesIdList.isEmpty()) {
            questOptionMap = courseQuestOptionMapper.selectListByQuestId(questionMap.keySet()).stream().collect(Collectors.groupingBy(CourseQuestOptionDO::getCqoQuestId));

        }

        if(questionMap.size() > 0 && questOptionMap.size() > 0) {
            //封装
            Map<Long, List<CourseQuestOptionDO>> finalQuestOptionMap = questOptionMap;
            courseConfigList.forEach(courseConfig -> {
                Long questId = courseConfig.getCcQuestId();
                CourseQuestionRespVO courseQuestion = questionMap.get(questId).get(0);
                courseQuestion.setCourseQuestOptionList(finalQuestOptionMap.get(questId));
                courseConfig.setCourseQuestion(courseQuestion);
            });
        }

        return courseConfigList;
    }

    @Override
    public PageResult<CourseConfigPageReqVO> getCourseConfigPage(CourseConfigPageReqVO pageReqVO) {
        List<CourseConfigPageReqVO> courseConfigPageReqVOS = courseConfigMapper.selectCourseConfigPage(pageReqVO);

        // 调用服务层方法获取分页结果
        return new PageResult<>(
                courseConfigPageReqVOS.stream()
                       .map(doItem -> BeanUtils.toBean(doItem, CourseConfigPageReqVO.class))
                       .collect(Collectors.toList()),
                (long) courseConfigPageReqVOS.size()
        );
    }

}