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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.course.bo.*;
import com.zhongzheng.modules.course.domain.*;
import com.zhongzheng.modules.course.mapper.CourseModuleMapper;
import com.zhongzheng.modules.course.service.*;
import com.zhongzheng.modules.course.vo.CourseModuleVo;
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 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-09
 */
@Service
public class CourseModuleServiceImpl extends ServiceImpl<CourseModuleMapper, CourseModule> implements ICourseModuleService {

    @Autowired
    private ICourseModuleBusinessService iCourseModuleBusinessService;

    @Autowired
    private ICourseModuleChapterService iCourseModuleChapterService;

    @Autowired
    private CourseModuleMapper courseModuleMapper;

    @Override
    public CourseModuleVo queryById(Long moduleId){
        CourseModule db = this.baseMapper.selectById(moduleId);
        return BeanUtil.toBean(db, CourseModuleVo.class);
    }

    @Override
    public List<CourseModuleVo> selectList(CourseModuleQueryBo bo) {
        return courseModuleMapper.selectList(bo);
    }

    @Override
    public List<CourseModuleVo> queryList(CourseModuleQueryBo bo) {
        LambdaQueryWrapper<CourseModule> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getPrefixName()), CourseModule::getPrefixName, bo.getPrefixName());
        lqw.like(StrUtil.isNotBlank(bo.getModuleName()), CourseModule::getModuleName, bo.getModuleName());
        lqw.eq(StrUtil.isNotBlank(bo.getCoverUrl()), CourseModule::getCoverUrl, bo.getCoverUrl());
        lqw.eq(bo.getPublishStatus() != null, CourseModule::getPublishStatus, bo.getPublishStatus());
        lqw.in(bo.getStatus() != null, CourseModule::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), CourseModule::getCode, bo.getCode());
        return entity2Vo(this.list(lqw));
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(CourseModuleAddBo bo) {
        CourseModule add = BeanUtil.toBean(bo, CourseModule.class);
        add.setCode(ServletUtils.getEncoded("MK"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean result = this.save(add);
        if(result){
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseModuleBusinessAddBo item = bo.getBusinessList().get(i);
                item.setModuleId(add.getModuleId());
                iCourseModuleBusinessService.insertByAddBo(item);
            }
            if(bo.getChapterIdList()!=null){
                Collection<CourseModuleChapter> coll = new HashSet<>();
                for(int i=0;i<bo.getChapterIdList().size();i++){
                    CourseModuleChapterListAddBo item = bo.getChapterIdList().get(i);
                    CourseModuleChapter addItem = new CourseModuleChapter();
                    addItem.setChapterId(item.getChapterId());
                    addItem.setModuleId(add.getModuleId());
                    addItem.setSort(item.getSort());
                    coll.add(addItem);
                }
                iCourseModuleChapterService.saveBatch(coll);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(CourseModuleEditBo bo) {
        CourseModule update = BeanUtil.toBean(bo, CourseModule.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!= null){
            iCourseModuleBusinessService.remove(new LambdaQueryWrapper<CourseModuleBusiness>().eq(CourseModuleBusiness::getModuleId, bo.getModuleId()));
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseModuleBusinessAddBo item = bo.getBusinessList().get(i);
                item.setModuleId(bo.getModuleId());
                iCourseModuleBusinessService.insertByAddBo(item);
            }
        }
        if(bo.getChapterIdList()!=null){
            iCourseModuleChapterService.remove(new LambdaQueryWrapper<CourseModuleChapter>().eq(CourseModuleChapter::getModuleId, bo.getModuleId()));
            Collection<CourseModuleChapter> coll = new HashSet<>();
            for(int i=0;i<bo.getChapterIdList().size();i++){
                CourseModuleChapterListAddBo item = bo.getChapterIdList().get(i);
                CourseModuleChapter addItem = new CourseModuleChapter();
                addItem.setChapterId(item.getChapterId());
                addItem.setModuleId(bo.getModuleId());
                addItem.setSort(item.getSort());
                coll.add(addItem);
            }
            iCourseModuleChapterService.saveBatch(coll);
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CourseModule entity){
        //TODO 做一些数据校验,如唯一约束
        if(checkNameUnique(entity)){
            throw new CustomException("名称重复");
        }
    }

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

    private boolean checkNameUnique(CourseModule entity) {
        CourseModule info = getOne(new LambdaQueryWrapper<CourseModule>()
                .eq(CourseModule::getPrefixName,entity.getPrefixName()).eq(CourseModule::getModuleName,entity.getModuleName()).last("limit 1"));
        if (Validator.isNotNull(info)) {
            if(Validator.isNotEmpty(entity.getModuleId())){
                if(entity.getModuleId() != info.getModuleId()){
                    return true;
                }
            }else{
                return true;
            }
        }
        return false;
    }
}
