package cn.iocoder.byzs.module.web.service.blockly;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.byzs.framework.common.enums.CommonStatusEnum;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.module.blockly.controller.admin.blockly.vo.BlocklyPageReqVO;
import cn.iocoder.byzs.module.blockly.controller.admin.blocklyConfig.vo.BlocklyConfigRespVO;
import cn.iocoder.byzs.module.blockly.service.blockly.BlocklyService;
import cn.iocoder.byzs.module.blockly.service.blocklyConfig.BlocklyConfigService;
import cn.iocoder.byzs.module.web.controller.admin.blockly.vo.WebBlocklyTypeVO;
import cn.iocoder.byzs.module.web.controller.admin.blockly.vo.WebBlocklyVO;
import cn.iocoder.byzs.module.web.controller.admin.blocklyprogress.vo.WebBlocklyProgressDO;
import cn.iocoder.byzs.module.web.dal.mysql.blockly.WebBlocklyMapper;
import cn.iocoder.byzs.module.web.service.blocklyprogress.WebBlocklyProgressServiceImpl;
import cn.iocoder.byzs.module.web.service.role.WebAuthRoleServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

/**
 * web课程 Service 实现类
 *
 * @author lyb
 */
@Service
@Validated
public class WebBlocklyServiceImpl {

    @Resource
    private BlocklyService blocklyService;
    @Resource
    private BlocklyConfigService blocklyConfigService;
    @Resource
    private WebBlocklyMapper webBlocklyMapper;
    @Resource
    private WebBlocklyProgressServiceImpl webBlocklyProgressService;
    @Resource
    private WebAuthRoleServiceImpl webAuthRoleService;



    /**
     * 根据课程类型id查询课程列表
     *
     * @param typeId 课程类型id
     * @return 课程列表
     */
    public List<WebBlocklyVO> getBlocklyVoByTypeId(Long typeId) {
        List<BlocklyPageReqVO> blocklyList = blocklyService.getBlocklyList(new BlocklyPageReqVO().setBcType(typeId).setBcStatus(String.valueOf(CommonStatusEnum.ENABLE.getStatus())));

        //填充课程配置
        List<Long> idList = blocklyList.stream()
                .map(BlocklyPageReqVO::getId)
                .collect(Collectors.toList());
        List<BlocklyConfigRespVO> blocklyConfigQuestionList = blocklyConfigService.getBlocklyConfigQuestionByCourseIds(idList);
        Map<Long, List<BlocklyConfigRespVO>> blocklyConfigQuestionMap = blocklyConfigQuestionList.stream().collect(Collectors.groupingBy(BlocklyConfigRespVO::getCcCourseId));

        //课程小节进度
        List<WebBlocklyProgressDO> progressList = webBlocklyProgressService.getBlocklyProgressByTypeId(typeId);
        Map<Long, WebBlocklyProgressDO> progressMap = progressList.stream().collect(Collectors.toMap(WebBlocklyProgressDO::getBrpCourseId, a -> a));


        //重新组装
        List<WebBlocklyVO> blocklyVoList = new ArrayList<>();
        for (BlocklyPageReqVO blockly : blocklyList) {

            //组装试题配置
            List<BlocklyConfigRespVO> blocklyConfigQuestion = blocklyConfigQuestionMap.get(blockly.getId());
            List<BlocklyConfigRespVO> list = new ArrayList<>();

            WebBlocklyVO webBlocklyVO = BeanUtils.toBean(blockly, WebBlocklyVO.class);
            if (CollUtil.isNotEmpty(blocklyConfigQuestion)) {
                // 根据 ccTime 升序排序（弹框时间）
                list = blocklyConfigQuestion.stream().sorted(Comparator.comparing(BlocklyConfigRespVO::getCcTime)).toList();
            }
            webBlocklyVO.setBlocklyConfigList(list);

            //填充进度
            if (progressMap.containsKey(blockly.getId())) {
                WebBlocklyProgressDO progress = progressMap.get(blockly.getId());
                webBlocklyVO.setProgress(progress.getBrpProgress().intValue());
            }else{
                webBlocklyVO.setProgress(0);
            }

            blocklyVoList.add(webBlocklyVO);
        }

        return blocklyVoList;
    }

    /**
     * 根据课程类型查询课程类型列表
     * @param themeId
     * @return
     */
    public List<WebBlocklyTypeVO> getTypeByThemeId(Long themeId) {

        //查询课程类型列表
        List<WebBlocklyTypeVO> list = webBlocklyMapper.getTypeByThemeId(new WebBlocklyTypeVO().setCtParentId(themeId));
        List<WebBlocklyTypeVO> blocklyTypeVoList = BeanUtils.toBean(list, WebBlocklyTypeVO.class);

        //课程小节进度
        List<WebBlocklyProgressDO> progressList = webBlocklyProgressService.getBlocklyProgressByThemeId(themeId);
        Map<Long, WebBlocklyProgressDO> progressMap = progressList.stream().collect(Collectors.toMap(WebBlocklyProgressDO::getBrpCtId, a -> a));

        //获得blockly数据权限
        Set<Long> blocklyAuthRoleVO = webAuthRoleService.getBlocklyAuthRoleVO();

        blocklyTypeVoList.forEach(blocklyType -> {

            //判断是否有数据权限
            if (blocklyAuthRoleVO.isEmpty()) {
                blocklyType.setDataReadonly(false);
            }else blocklyType.setDataReadonly(!blocklyAuthRoleVO.contains(blocklyType.getId()));


            if (progressMap.containsKey(blocklyType.getId())) {
                WebBlocklyProgressDO progress = progressMap.get(blocklyType.getId());
                Double brpProgress = progress.getBrpProgress();
                //向下取整
                double progressL = Math.floor(brpProgress / blocklyType.getSectionCount() * 5);
                blocklyType.setProgress((int) progressL);
            }else{
                blocklyType.setProgress(0);
            }
        });

        return blocklyTypeVoList;
    }
}