package com.zhongzheng.modules.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.course.bo.*;
import com.zhongzheng.modules.course.domain.CourseMenu;
import com.zhongzheng.modules.course.domain.CourseMenuExam;
import com.zhongzheng.modules.course.domain.CourseModuleBusiness;
import com.zhongzheng.modules.course.domain.CourseModuleChapter;
import com.zhongzheng.modules.course.mapper.CourseChapterMapper;
import com.zhongzheng.modules.course.mapper.CourseMenuMapper;
import com.zhongzheng.modules.course.service.ICourseMenuExamService;
import com.zhongzheng.modules.course.service.ICourseMenuService;
import com.zhongzheng.modules.course.vo.CourseMenuVo;
import com.zhongzheng.modules.course.vo.CourseUserChapterSectionVo;
import com.zhongzheng.modules.course.vo.CourseUserMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程目录结构Service业务层处理
 *
 * @author hjl
 * @date 2021-10-12
 */
@Service
public class CourseMenuServiceImpl extends ServiceImpl<CourseMenuMapper, CourseMenu> implements ICourseMenuService {

    @Autowired
    private CourseMenuMapper courseMenuMapper;

    @Autowired
    private ICourseMenuExamService iCourseMenuExamService;

    @Override
    public CourseMenuVo queryById(Long id){
        CourseMenu db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, CourseMenuVo.class);
    }

    @Override
    public List<CourseMenuVo> selectList(CourseMenuQueryBo bo) {
        return courseMenuMapper.selectList(bo);
    }

    @Override
    public List<CourseMenuVo> queryList(CourseMenuQueryBo bo) {
        LambdaQueryWrapper<CourseMenu> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCourseId() != null, CourseMenu::getCourseId, bo.getCourseId());
        lqw.eq(bo.getMenuId() != null, CourseMenu::getMenuId, bo.getMenuId());
        lqw.eq(bo.getType() != null, CourseMenu::getType, bo.getType());
        lqw.eq(bo.getParentId() != null, CourseMenu::getParentId, bo.getParentId());
        lqw.eq(bo.getStatus() != null, CourseMenu::getStatus, bo.getStatus());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<CourseMenuVo> entity2Vo(Collection<CourseMenu> collection) {
        List<CourseMenuVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseMenuVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<CourseMenu> page = (Page<CourseMenu>)collection;
            Page<CourseMenuVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(CourseMenuListAddBo bo) {
        boolean result = false;
        for(int i=0;i<bo.getMenuList().size();i++){
            CourseMenu add = BeanUtil.toBean(bo.getMenuList().get(i), CourseMenu.class);
            validEntityBeforeSave(add);
            add.setCourseId(bo.getCourseId());
            add.setCreateTime(DateUtils.getNowTime());
            add.setUpdateTime(DateUtils.getNowTime());
            result = this.save(add);
        }
        if(result){
            if(bo.getMenuExamList()!=null){
                Collection<CourseMenuExam> coll = new HashSet<>();
                for(int i=0;i<bo.getMenuExamList().size();i++){
                    CourseMenuExam addItem = BeanUtil.toBean(bo.getMenuExamList().get(i), CourseMenuExam.class);
                    addItem.setType(1);
                    addItem.setCourseId(bo.getCourseId());
                    addItem.setCreateTime(DateUtils.getNowTime());
                    addItem.setUpdateTime(DateUtils.getNowTime());
                    coll.add(addItem);
                }
                iCourseMenuExamService.saveBatch(coll);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(CourseMenuListAddBo bo) {
        boolean result = false;
        remove(new LambdaQueryWrapper<CourseMenu>().eq(CourseMenu::getCourseId, bo.getCourseId()));
        for(int i=0;i<bo.getMenuList().size();i++){
            CourseMenu add = BeanUtil.toBean(bo.getMenuList().get(i), CourseMenu.class);
            validEntityBeforeSave(add);
            add.setCourseId(bo.getCourseId());
            add.setCreateTime(DateUtils.getNowTime());
            add.setUpdateTime(DateUtils.getNowTime());
            result = this.save(add);
        }
        if(bo.getMenuExamList()!=null){
            iCourseMenuExamService.remove(new LambdaQueryWrapper<CourseMenuExam>().eq(CourseMenuExam::getCourseId, bo.getCourseId()));
            Collection<CourseMenuExam> coll = new HashSet<>();
            for(int i=0;i<bo.getMenuExamList().size();i++){
                CourseMenuExam addItem = BeanUtil.toBean(bo.getMenuExamList().get(i), CourseMenuExam.class);
                addItem.setType(1);
                addItem.setCourseId(bo.getCourseId());
                addItem.setCreateTime(DateUtils.getNowTime());
                addItem.setUpdateTime(DateUtils.getNowTime());
                coll.add(addItem);
            }
            iCourseMenuExamService.saveBatch(coll);
        }
        return result;
       /* CourseMenu update = BeanUtil.toBean(bo, CourseMenu.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);*/
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CourseMenu entity){
        //TODO 做一些数据校验,如唯一约束

    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<CourseUserMenuVo> menuList(CourseMenuQueryBo bo) {
        List<CourseUserMenuVo> courseMenuVos = baseMapper.menuList(bo);
        if (bo.getUserId() != null) {
            for (CourseUserMenuVo courseMenuVo : courseMenuVos) {
                if (courseMenuVo.getType().equals(3)) {
                    Integer rebuild = baseMapper.rebuildCheck(courseMenuVo.getMenuId(), courseMenuVo.getGradeId(), bo.getUserId());
                    if (rebuild > 0) {
                        courseMenuVo.setRebuild(1);
                    }
                }
                if (courseMenuVo.getType().equals(2)){
                    Integer rebuild = baseMapper.rebuildChapterCheck(courseMenuVo.getMenuId(), courseMenuVo.getGradeId(), bo.getUserId());
                    if (rebuild > 0) {
                        courseMenuVo.setRebuild(1);
                    }
                }
                if (courseMenuVo.getType().equals(1)){
                    Integer rebuild = baseMapper.rebuildModuleCheck(courseMenuVo.getMenuId(), courseMenuVo.getGradeId(), bo.getUserId());
                    if (rebuild > 0) {
                        courseMenuVo.setRebuild(1);
                    }
                }
            }
        }
        if (bo.getRebuild() != null && bo.getRebuild() == 1) {
            List<CourseUserMenuVo> courseMenuVoss = courseMenuVos.stream().filter(s ->
                    s.getRebuild() != null && s.getRebuild().equals(1)
            ).collect(Collectors.toList());
            return courseMenuVoss;
        }
        return courseMenuVos;
    }
}
