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

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.bjdx.controller.admin.course.vo.CoursePageReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.courseconfig.vo.CourseConfigRespVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursetype.vo.CourseTypeSaveReqVO;
import cn.iocoder.byzs.module.bjdx.service.course.CourseService;
import cn.iocoder.byzs.module.bjdx.service.courseconfig.CourseConfigService;
import cn.iocoder.byzs.module.bjdx.service.coursetype.CourseTypeService;
import cn.iocoder.byzs.module.web.controller.admin.course.vo.WebCourseAIGenerateVO;
import cn.iocoder.byzs.module.web.controller.admin.course.vo.WebCourseVO;
import cn.iocoder.byzs.module.web.dal.mysql.course.WebCourseMapper;
import cn.iocoder.byzs.module.web.service.role.WebAuthRoleServiceImpl;
import cn.iocoder.byzs.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.byzs.module.bjdx.controller.admin.course.vo.CourseSaveReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursetype.vo.CourseTypeListReqVO;
import cn.iocoder.byzs.module.bjdx.dal.dataobject.coursetype.CourseTypeDO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

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

    @Resource
    private CourseService courseService;
    @Resource
    private CourseTypeService courseTypeService;
    @Resource
    private CourseConfigService courseConfigService;
    @Resource
    private WebCourseMapper webCourseMapper;
    @Resource
    private WebAuthRoleServiceImpl webAuthRoleService;


    public List<WebCourseVO> getCourseVoByTypeId(Long typeId) {
        List<CoursePageReqVO> courseList = courseService.getCourseList(new CoursePageReqVO().setCourseType(typeId).setCourseStatus(String.valueOf(CommonStatusEnum.ENABLE.getStatus())));

        List<Long> idList = courseList.stream()
                .map(CoursePageReqVO::getId)
                .collect(Collectors.toList());

        // 获得课程配置-试题列表
        List<CourseConfigRespVO> courseConfigQuestionList = courseConfigService.getCourseConfigQuestionByCourseIds(idList);
        // 转换为 Map，以 ccCourseId 为键
        Map<Long, List<CourseConfigRespVO>> configMap = courseConfigQuestionList.stream()
                .collect(Collectors.groupingBy(CourseConfigRespVO::getCcCourseId));

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

        //重新组装
        List<WebCourseVO> courseVoList = new ArrayList<>();
        for (CoursePageReqVO course : courseList) {

            WebCourseVO webCourseVo = BeanUtils.toBean(course, WebCourseVO.class);


            //根据课程id获得课程配置-试题列表
            List<CourseConfigRespVO> courseConfigQuestion = configMap.get(course.getId());
            List<CourseConfigRespVO> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(courseConfigQuestion)) {
                // 根据 ccTime 升序排序（提示时间）
                list = courseConfigQuestion.stream().sorted(Comparator.comparing(CourseConfigRespVO::getCcTime)).toList();
            }
            webCourseVo.setCourseConfigList(list);

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

            courseVoList.add(webCourseVo);
        }

        return courseVoList;
    }

     /**
      * AI生成课程
      */
    @Transactional(rollbackFor = Exception.class)
    public Boolean generateCourseByAI(WebCourseAIGenerateVO aiGenerateVO) {

        // 1. 获取登录用户ID
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId == null) {
            return false;
        }

        // 2. 获取课程类型的最大排序数
        CourseTypeListReqVO listReqVO = new CourseTypeListReqVO();
        listReqVO.setCtParentId(aiGenerateVO.getGrade());
        listReqVO.setCtTypeNode("4");
        listReqVO.setCreator(loginUserId);
        List<CourseTypeDO> courseTypeList = courseTypeService.getCourseTypeSimpleList(listReqVO);
        int maxSort = 0;
        if (courseTypeList != null && !courseTypeList.isEmpty()) {
            maxSort = courseTypeList.stream()
                    .map(CourseTypeDO::getCtTypeSort)
                    .filter(Objects::nonNull)
                    .max(Integer::compare)
                    .orElse(0);
        }

        // 3. 创建课程类型
        CourseTypeSaveReqVO courseTypeSaveReqVO = new CourseTypeSaveReqVO();
        courseTypeSaveReqVO.setCtParentId(Long.valueOf(aiGenerateVO.getGrade()));
        courseTypeSaveReqVO.setCtType(aiGenerateVO.getCourseName());
        courseTypeSaveReqVO.setCtTypeImage(aiGenerateVO.getCoverImage());
        courseTypeSaveReqVO.setCtTypeNode("4"); // 设置 ctTypeNode 类型为4
        courseTypeSaveReqVO.setCtTypeSort(maxSort + 1); // 最大排序加1
        Long courseTypeId = courseTypeService.createCourseType(courseTypeSaveReqVO);

        // 4. 循环创建课程
        if (aiGenerateVO.getCourseList() != null && !aiGenerateVO.getCourseList().isEmpty()) {
            int courseOrder = 1; // 课程排序从1开始
            for (WebCourseAIGenerateVO.CourseVO courseVO : aiGenerateVO.getCourseList()) {
                CourseSaveReqVO courseSaveReqVO = new CourseSaveReqVO();
                courseSaveReqVO.setCourseName(courseVO.getCourseName());
                courseSaveReqVO.setCourseLabel(courseVO.getCourseLabel());
                courseSaveReqVO.setCourseContentType("ailab");
                courseSaveReqVO.setCourseContent(courseVO.getCourseContent());
                courseSaveReqVO.setCourseType(courseTypeId); // 补充课程类型id
                courseSaveReqVO.setCourseOrder(courseOrder++); // 排序从1开始递增
                courseSaveReqVO.setCourseStatus("0"); // 设置课程状态为启用
                courseService.createCourse(courseSaveReqVO);
            }
        }

        return true;
    }

}