package com.ynfy.buss.course.coursecatalog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.course.coursecatalog.entity.CourseCatalog;
import com.ynfy.buss.course.coursecatalog.enums.CatalogType;
import com.ynfy.buss.course.coursecatalog.enums.ResourceType;
import com.ynfy.buss.course.coursecatalog.mapper.CourseCatalogMapper;
import com.ynfy.buss.course.coursecatalog.service.ICourseCatalogService;
import com.ynfy.buss.course.usercoursecatalog.entity.UserCourseCatalog;
import com.ynfy.buss.course.usercoursecatalog.service.IUserCourseCatalogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * @Description: course_catalog
 * @Author: jeecg-boot
 * @Date: 2023-10-24
 * @Version: V1.0
 */
@Service
public class CourseCatalogServiceImpl extends ServiceImpl<CourseCatalogMapper, CourseCatalog> implements ICourseCatalogService {

    @Autowired
    private IUserCourseCatalogService userCourseCatalogService;


    /**
     * 删除
     *
     * @param courseId
     */
    @Override
    public void remove(String courseId) {
        QueryWrapper<CourseCatalog> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseCatalog::getCourseId, courseId);
        this.remove(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAll(String courseId, List<CourseCatalog> catalogList) {
        remove(courseId);
        List<CourseCatalog> newCatalogList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(catalogList)) {
            int sort = 1;
            for (CourseCatalog item : catalogList) {
                //根节点
                item.setCourseId(courseId);
                item.setSort(sort);
                if (ResourceType.FILE.getCode().equals(item.getResourceType())) {//如果是文档
                    item.setVideoHour(null);
                }
                sort++;
                newCatalogList.add(item);

                //子节点
                if (!CollectionUtils.isEmpty(item.getChildList())) {
                    int index = 1;
                    for (CourseCatalog child : item.getChildList()) {
                        child.setCourseId(courseId);
                        child.setSort(index);
                        if (ResourceType.FILE.getCode().equals(child.getResourceType())) {
                            child.setVideoHour(null);
                        }
                        newCatalogList.add(child);
                        index++;
                    }
                }
            }
            saveBatch(newCatalogList);
        }
    }

    /**
     * 根据课程id获取目录
     *
     * @param courseId
     * @return
     */
    @Override
    public List<CourseCatalog> listByCourseId(String courseId) {
        QueryWrapper<CourseCatalog> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseCatalog::getCourseId, courseId);
        List<CourseCatalog> courseCatalogList = list(wrapper);
        if (!CollectionUtils.isEmpty(courseCatalogList)) {
            //获取根节点
            List<CourseCatalog> rootList = courseCatalogList.stream().filter(courseCatalog ->
                            StringUtils.isBlank(courseCatalog.getParentId())).sorted(Comparator.comparing(CourseCatalog::getSort))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(rootList)) {
                rootList.forEach(root -> {
                    //如果根节点是目录，获取任务子节点
                    if (CatalogType.CATALOG.getCode().equals(root.getType())) {
                        List<CourseCatalog> childList = courseCatalogList.stream().filter(courseCatalog ->
                                StringUtils.isNotBlank(courseCatalog.getParentId()) && courseCatalog.getParentId().equals(root.getId())
                        ).sorted(Comparator.comparing(CourseCatalog::getSort)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(childList)) {
                            if (CollectionUtils.isEmpty(root.getChildList())) {
                                root.setChildList(new ArrayList<>());
                            }
                            root.getChildList().addAll(childList);
                        }
                    }
                });
            }
            return rootList;
        }
        return Collections.emptyList();
    }


    /**
     * 检查上一个任务是否完成
     *
     * @param id
     * @return
     */
    @Override
    public boolean checkPreTaskComplete(String id) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        CourseCatalog courseCatalog = getById(id);
        if (!Objects.isNull(courseCatalog)) {
            if (StringUtils.isNotBlank(courseCatalog.getParentId())) { //点击了目录下的任务
                if (courseCatalog.getSort() > 1) { //如果点击的是目录下的第n(n>1)个任务，获取本目录下的点击任务的前一个任务
                    return isComplete(user, getPre(courseCatalog.getParentId(), courseCatalog.getSort() - 1).getId());
                } else { //sort == 1 //如果点击的是目录下的第一个任务
                    CourseCatalog parent = getParent(courseCatalog.getParentId()); //获取父节点
                    if (!Objects.isNull(parent) && parent.getSort() > 1) {//不是第一个根节点，获取前一个根节点
                        return calcIsFinish(user, courseCatalog.getCourseId(), parent.getSort() - 1);
                    } else { //是第一个根节点
                        return true;
                    }
                }
            } else { //点击了根节点的任务
                if (courseCatalog.getSort() > 1) {
                    return calcIsFinish(user, courseCatalog.getCourseId(), courseCatalog.getSort() - 1);
                } else {
                    return true;
                }
            }
        }
        return false;
    }

    public CourseCatalog getPre(String parentId, Integer sort) {
        LambdaQueryWrapper<CourseCatalog> query = new LambdaQueryWrapper<CourseCatalog>().eq(CourseCatalog::getParentId, parentId)
                .eq(CourseCatalog::getSort, sort);
        return getOne(query);
    }

    public CourseCatalog getParent(String id) {
        LambdaQueryWrapper<CourseCatalog> query = new LambdaQueryWrapper<CourseCatalog>().eq(CourseCatalog::getId, id);
        return getOne(query);
    }

    public CourseCatalog getRootPre(String courseId, Integer sort) {
        LambdaQueryWrapper<CourseCatalog> query = new LambdaQueryWrapper<CourseCatalog>()
                .eq(CourseCatalog::getCourseId, courseId).eq(CourseCatalog::getSort, sort).isNull(CourseCatalog::getParentId);
        return getOne(query);
    }

    public CourseCatalog getLastTaskOfCatalog(String id) {
        LambdaQueryWrapper<CourseCatalog> query = new LambdaQueryWrapper<CourseCatalog>().eq(CourseCatalog::getParentId, id)
                .orderByDesc(CourseCatalog::getSort);
        List<CourseCatalog> courseCatalogList = list(query);
        return !CollectionUtils.isEmpty(courseCatalogList) ? courseCatalogList.get(0) : null;
    }

    public boolean isComplete(LoginUser user, String courseCatalogId) {
        UserCourseCatalog rootUCC = userCourseCatalogService.findUserCatalog(user.getId(), courseCatalogId);
        if (!Objects.isNull(rootUCC) && !Objects.isNull(rootUCC.getLearnProcess()) && rootUCC.getLearnProcess() >= 1) {
            return true;
        } else {
            return false;
        }
    }

    public boolean calcIsFinish(LoginUser user, String courseId, Integer sort) {
        CourseCatalog rootPre = getRootPre(courseId, sort);
        if (!Objects.isNull(rootPre)) {
            if (CatalogType.TASK.getCode().equals(rootPre.getType())) {//前一个根节点是任务类型
                return isComplete(user, rootPre.getId());
            } else { //前一个根节点是目录类型，获取目录下的最后一个任务
                CourseCatalog lastTaskOfCatalog = getLastTaskOfCatalog(rootPre.getId());
                return isComplete(user, lastTaskOfCatalog.getId());
            }
        }
        return false;
    }


    /**
     * 获取课程任务
     *
     * @param courseId
     * @return
     */
    @Override
    public List<CourseCatalog> listCourseCatalog(String courseId) {
        LambdaQueryWrapper<CourseCatalog> query = new LambdaQueryWrapper<CourseCatalog>().eq(CourseCatalog::getCourseId, courseId)
                .eq(CourseCatalog::getType, CatalogType.TASK.getCode());
        return list(query);
    }
}
