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.CourseSectionAddBo;
import com.zhongzheng.modules.course.bo.CourseSectionBusinessAddBo;
import com.zhongzheng.modules.course.bo.CourseSectionEditBo;
import com.zhongzheng.modules.course.bo.CourseSectionQueryBo;
import com.zhongzheng.modules.course.domain.Course;
import com.zhongzheng.modules.course.domain.CourseSection;
import com.zhongzheng.modules.course.domain.CourseSectionBusiness;
import com.zhongzheng.modules.course.mapper.CourseSectionMapper;
import com.zhongzheng.modules.course.service.ICourseSectionBusinessService;
import com.zhongzheng.modules.course.service.ICourseSectionService;
import com.zhongzheng.modules.course.service.IMajorProjectService;
import com.zhongzheng.modules.course.vo.CourseSectionVo;
import com.zhongzheng.modules.system.domain.SysRoleMenu;
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 java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程小节Service业务层处理
 *
 * @author hjl
 * @date 2021-10-11
 */
@Service
public class CourseSectionServiceImpl extends ServiceImpl<CourseSectionMapper, CourseSection> implements ICourseSectionService {

    @Autowired
    private ICourseSectionBusinessService iCourseSectionBusinessService;

    @Autowired
    private CourseSectionMapper courseSectionMapper;

    @Override
    public CourseSectionVo queryById(Long sectionId){
        CourseSection db = this.baseMapper.selectById(sectionId);
        return BeanUtil.toBean(db, CourseSectionVo.class);
    }

    @Override
    public List<CourseSectionVo> selectSectionList(CourseSectionQueryBo bo) {
        return courseSectionMapper.selectSectionList(bo);
    }

    @Override
    public List<CourseSectionVo> queryList(CourseSectionQueryBo bo) {
        LambdaQueryWrapper<CourseSection> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), CourseSection::getName, bo.getName());
        lqw.eq(bo.getSort() != null, CourseSection::getSort, bo.getSort());
        lqw.like(StrUtil.isNotBlank(bo.getPrefixName()), CourseSection::getPrefixName, bo.getPrefixName());
        lqw.eq(bo.getStatus() != null, CourseSection::getStatus, bo.getStatus());
        lqw.eq(bo.getSectionType() != null, CourseSection::getSectionType, bo.getSectionType());
        lqw.eq(bo.getPublishStatus() != null, CourseSection::getPublishStatus, bo.getPublishStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getLiveUrl()), CourseSection::getLiveUrl, bo.getLiveUrl());
        lqw.eq(bo.getLiveStartTime() != null, CourseSection::getLiveStartTime, bo.getLiveStartTime());
        lqw.eq(bo.getLiveEndTime() != null, CourseSection::getLiveEndTime, bo.getLiveEndTime());
        lqw.eq(StrUtil.isNotBlank(bo.getRecordingUrl()), CourseSection::getRecordingUrl, bo.getRecordingUrl());
        lqw.eq(bo.getDurationTime() != null, CourseSection::getDurationTime, bo.getDurationTime());
        return entity2Vo(this.list(lqw));
    }

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

    @Override
    public Boolean insertByAddBo(CourseSectionAddBo bo) {
        CourseSection add = BeanUtil.toBean(bo, CourseSection.class);
        add.setCode(ServletUtils.getEncoded("J"));
        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++){
                CourseSectionBusinessAddBo item = bo.getBusinessList().get(i);
                item.setSectionId(add.getSectionId());
                iCourseSectionBusinessService.insertByAddBo(item);
            }
        }
        return result;
    }

    @Override
    public Boolean updateByEditBo(CourseSectionEditBo bo) {
        CourseSection update = BeanUtil.toBean(bo, CourseSection.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!= null){
            iCourseSectionBusinessService.remove(new LambdaQueryWrapper<CourseSectionBusiness>().eq(CourseSectionBusiness::getSectionId, bo.getSectionId()));
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseSectionBusinessAddBo item = bo.getBusinessList().get(i);
                item.setSectionId(bo.getSectionId());
                iCourseSectionBusinessService.insertByAddBo(item);
            }
        }

        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CourseSection 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(CourseSection entity) {
        CourseSection info = getOne(new LambdaQueryWrapper<CourseSection>()
                .eq(CourseSection::getPrefixName,entity.getPrefixName()).eq(CourseSection::getName,entity.getName()).last("limit 1"));
        if (Validator.isNotNull(info)) {
            if(Validator.isNotEmpty(entity.getSectionId())){
                if(entity.getSectionId() != info.getSectionId()){
                    return true;
                }
            }else{
                return true;
            }
        }
        return false;
    }
}
