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.bank.domain.QuestionModuleChapter;
import com.zhongzheng.modules.bank.service.IQuestionModuleChapterService;
import com.zhongzheng.modules.course.bo.*;
import com.zhongzheng.modules.course.domain.*;
import com.zhongzheng.modules.course.mapper.CourseChapterMapper;
import com.zhongzheng.modules.course.mapper.CourseSectionMapper;
import com.zhongzheng.modules.course.service.*;
import com.zhongzheng.modules.course.vo.CourseChapterVo;
import com.zhongzheng.modules.goods.domain.GoodsAttached;
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 CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements ICourseChapterService {

    @Autowired
    private ICourseChapterBusinessService iCourseChapterBusinessService;

    @Autowired
    private CourseChapterMapper courseChapterMapper;

    @Autowired
    private ICourseChapterSectionService iCourseChapterSectionService;

    @Autowired
    private ICourseMenuService iCourseMenuService;

    @Autowired
    private ICourseModuleChapterService iCourseModuleChapterService;

    @Override
    public CourseChapterVo queryById(Long chapterId){
        CourseChapter db = this.baseMapper.selectById(chapterId);
        return BeanUtil.toBean(db, CourseChapterVo.class);
    }

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

    @Override
    public List<CourseChapterVo> selectList(CourseChapterQueryBo bo) {
        return courseChapterMapper.selectList(bo);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByAddBo(CourseChapterAddBo bo) {
        CourseChapter add = BeanUtil.toBean(bo, CourseChapter.class);
        add.setCode(ServletUtils.getEncoded("Z"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean result = this.save(add);
        if(result){
            if(bo.getBusinessList()!=null){
                for(int i=0;i<bo.getBusinessList().size();i++){
                    CourseChapterBusinessAddBo item = bo.getBusinessList().get(i);
                    item.setChapterId(add.getChapterId());
                    iCourseChapterBusinessService.insertByAddBo(item);
                }
            }
            if(bo.getSectionIdList()!=null){
                Collection<CourseChapterSection> coll = new HashSet<>();
                for(int i=0;i<bo.getSectionIdList().size();i++){
                    CourseChapterSectionListAddBo item = bo.getSectionIdList().get(i);
                    CourseChapterSection addItem = new CourseChapterSection();
                    addItem.setChapterId(add.getChapterId());
                    addItem.setSectionId(item.getSectionId());
                    addItem.setSort(item.getSort());
                    coll.add(addItem);
                }
                iCourseChapterSectionService.saveBatch(coll);
            }

        }
        return add.getChapterId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(CourseChapterEditBo bo) {
        CourseChapter update = BeanUtil.toBean(bo, CourseChapter.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!= null){
            iCourseChapterBusinessService.remove(new LambdaQueryWrapper<CourseChapterBusiness>().eq(CourseChapterBusiness::getChapterId, bo.getChapterId()));
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseChapterBusinessAddBo item = bo.getBusinessList().get(i);
                item.setChapterId(bo.getChapterId());
                iCourseChapterBusinessService.insertByAddBo(item);
            }
        }
        if(bo.getSectionIdList()!=null){
            iCourseChapterSectionService.remove(new LambdaQueryWrapper<CourseChapterSection>().eq(CourseChapterSection::getChapterId, bo.getChapterId()));
            Collection<CourseChapterSection> coll = new HashSet<>();
            for(int i=0;i<bo.getSectionIdList().size();i++){
                Long sectionId = bo.getSectionIdList().get(i).getSectionId();
                Long sort = bo.getSectionIdList().get(i).getSort();
                CourseChapterSection add = new CourseChapterSection();
                add.setChapterId(bo.getChapterId());
                add.setSectionId(sectionId);
                add.setSort(sort);
                coll.add(add);
            }
            iCourseChapterSectionService.saveBatch(coll);
        }

        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CourseChapter entity){
        //TODO 做一些数据校验,如唯一约束
       /* if(checkNameUnique(entity)){
            throw new CustomException("名称重复");
        }*/
        if(entity.getChapterId()!=null&&entity.getPublishStatus()!=null&&entity.getPublishStatus()==0){
            CourseMenu one = iCourseMenuService.getOne(new LambdaQueryWrapper<CourseMenu>().eq(CourseMenu::getMenuId, entity.getChapterId()).eq(CourseMenu::getType,2).last("limit 1"));
            if(one!=null){
                throw new CustomException("该章已被绑定，不允许修改发布状态为未发布");
            }
            if(iCourseModuleChapterService.getOne(new LambdaQueryWrapper<CourseModuleChapter>().eq(CourseModuleChapter::getChapterId,entity.getChapterId()).last("limit 1"))!=null){
                throw new CustomException("该章已被绑定，不允许修改发布状态为未发布");
            }
        }
    }

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

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