package org.xyzh.study.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.study.TbCourse;
import org.xyzh.common.dto.study.TbCourseChapter;
import org.xyzh.common.dto.study.TbCourseNode;
import org.xyzh.common.dto.study.TbCourseTag;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.common.vo.ChapterVO;
import org.xyzh.common.vo.CourseVO;
import org.xyzh.study.mapper.CourseMapper;
import org.xyzh.study.mapper.CourseTagMapper;
import org.xyzh.study.mapper.CourseChapterMapper;
import org.xyzh.study.mapper.CourseNodeMapper;
import org.xyzh.study.service.SCCourseService;
import org.xyzh.system.utils.LoginUtil;

/**
 * @description 课程服务实现类
 * @filename SCCourseServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class SCCourseServiceImpl implements SCCourseService {

    private static final Logger logger = LoggerFactory.getLogger(SCCourseServiceImpl.class);

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseChapterMapper courseChapterMapper;

    @Autowired
    private CourseTagMapper courseTagMapper;

    @Autowired
    private CourseNodeMapper courseNodeMapper;

    @Override
    public ResultDomain<TbCourse> getCourseList(TbCourse filter) {
        // TODO: 实现获取课程列表
        return null;
    }

    @Override
    public ResultDomain<TbCourse> getCoursePage(PageRequest<TbCourse> pageRequest) {
        ResultDomain<TbCourse> resultDomain = new ResultDomain<>();
        TbCourse filter = pageRequest.getFilter();
        PageParam pageParam = pageRequest.getPageParam();
        List<TbCourse> courses = courseMapper.selectCoursesPage(filter, pageParam);
        int total = (int) courseMapper.countCourses(filter);
        int totalPages = (int) Math.ceil((double) total / pageParam.getPageSize());
        pageParam.setTotalPages(totalPages);
        pageParam.setTotalElements(total);
        PageDomain<TbCourse> pageDomain = new PageDomain<>(pageParam, courses);
        resultDomain.success("获取课程列表成功", pageDomain);
        return resultDomain;
    }

    @Override
    public ResultDomain<CourseVO> getCourseById(String courseID) {
        ResultDomain<CourseVO> resultDomain = new ResultDomain<>();
        // 查询课程
        TbCourse course = courseMapper.selectByCourseId(courseID);
        // 查询标签
        List<TbCourseTag> tags = courseTagMapper.selectByCourseId(courseID);
        CourseVO courseVO = new CourseVO();
        courseVO.setCourse(course);
        courseVO.setCourseTags(tags);

        // 查询课程章节
        TbCourseChapter filter = new TbCourseChapter();
        filter.setCourseID(courseID);
        List<TbCourseChapter> chapters = courseChapterMapper.selectCourseChapters(filter);
        // 查询子节点
        if (chapters.size() > 0) {
            List<String> chapterIDs = chapters.stream().map(TbCourseChapter::getChapterID).collect(Collectors.toList());
            List<TbCourseNode> nodes = courseNodeMapper.selectCourseNodesByChapterIDs(chapterIDs);
            Map<String, List<TbCourseNode>> nodesMap = nodes.stream().collect(Collectors.groupingBy(TbCourseNode::getChapterID));
            List<ChapterVO> chapterVOs = chapters.stream().map(chapter -> {
                ChapterVO chapterVO = new ChapterVO();
                chapterVO.setChapter(chapter);
                chapterVO.setNodes(nodesMap.get(chapter.getChapterID()));
                return chapterVO;
            }).collect(Collectors.toList());
            courseVO.setCourseChapters(chapterVOs);
        }
        resultDomain.success("获取课程详情成功", courseVO);
        return resultDomain;
    }

    @Override
    public ResultDomain<CourseVO> createCourse(CourseVO courseVO) {
        ResultDomain<CourseVO> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        TbCourse course = courseVO.getCourse();
        String courseID = IDUtils.generateID();
        course.setCreator(user.getID());
        course.setCourseID(courseID);
        Date now = new Date();
        course.setCreateTime(now);
        course.setStatus(0);


        courseMapper.insertCourse(course);

        List<ChapterVO> courseChapters = courseVO.getCourseChapters();
        List<TbCourseChapter> chapters = new ArrayList<>();
        List<TbCourseNode> nodes = new ArrayList<>();
        int length = courseChapters.size();
        for (int i=0; i<length; i++) {
            ChapterVO chapterVO = courseChapters.get(i);
            TbCourseChapter chapter = chapterVO.getChapter();
            List<TbCourseNode> nodesList = chapterVO.getNodes();

            chapter.setCourseID(courseID);
            String chapterID = IDUtils.generateID();
            chapter.setID(IDUtils.generateID());
            chapter.setChapterID(chapterID);
            chapter.setCreator(user.getID());
            chapter.setCreateTime(now);
            chapter.setOrderNum(i);
            chapters.add(chapter);

            for (int j=0; j<nodesList.size(); j++) {
                TbCourseNode node = nodesList.get(j);
                node.setNodeID(IDUtils.generateID());
                node.setChapterID(chapterID);
                node.setCreator(user.getID());
                node.setCreateTime(now);
                nodes.add(node);
            }
        }
        courseChapterMapper.batchInsertCourseChapters(chapters);
        courseNodeMapper.batchInsertCourseNodes(nodes);

        List<TbCourseTag> courseTags = courseVO.getCourseTags();
        length = courseTags.size();
        if (length > 0) {
            for (int i=0; i<length; i++) {
                TbCourseTag tag = courseTags.get(i);
                tag.setCourseID(courseID);
                tag.setTagID(IDUtils.generateID());
                tag.setCreator(user.getID());
                tag.setCreateTime(now);
            }
            courseTagMapper.batchInsertCourseTags(courseTags);
        }

        
        resultDomain.success("创建课程成功",courseVO);
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCourse> updateCourse(TbCourse course) {
        // TODO: 实现更新课程
        return null;
    }

    @Override
    public ResultDomain<Boolean> deleteCourse(String courseID) {
        // TODO: 实现删除课程
        return null;
    }

    @Override
    public ResultDomain<TbCourse> updateCourseStatus(String courseID, Integer status) {
        // TODO: 实现更新课程状态
        return null;
    }

    @Override
    public ResultDomain<TbCourse> incrementViewCount(String courseID) {
        // TODO: 实现增加课程浏览次数
        return null;
    }

    @Override
    public ResultDomain<TbCourse> incrementLearnCount(String courseID) {
        // TODO: 实现增加课程学习人数
        return null;
    }

    @Override
    public ResultDomain<TbCourseChapter> getCourseChapters(String courseID) {
        // TODO: 实现获取课程章节列表
        return null;
    }

    @Override
    public ResultDomain<TbCourseChapter> getChapterById(String chapterID) {
        // TODO: 实现根据ID获取章节详情
        return null;
    }

    @Override
    public ResultDomain<TbCourseChapter> createChapter(TbCourseChapter chapter) {
        // TODO: 实现创建课程章节
        return null;
    }

    @Override
    public ResultDomain<TbCourseChapter> updateChapter(TbCourseChapter chapter) {
        // TODO: 实现更新课程章节
        return null;
    }

    @Override
    public ResultDomain<Boolean> deleteChapter(String chapterID) {
        // TODO: 实现删除课程章节
        return null;
    }

    @Override
    public ResultDomain<TbCourseChapter> updateChapterOrder(String chapterID, Integer orderNum) {
        // TODO: 实现更新章节排序
        return null;
    }
}
