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.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.bank.domain.Question;
import com.zhongzheng.modules.course.bo.CourseAddBo;
import com.zhongzheng.modules.course.bo.CourseEditBo;
import com.zhongzheng.modules.course.bo.CourseQueryBo;
import com.zhongzheng.modules.course.domain.Course;
import com.zhongzheng.modules.course.mapper.CourseMapper;
import com.zhongzheng.modules.course.mapper.CourseSectionMapper;
import com.zhongzheng.modules.course.service.ICourseSectionBusinessService;
import com.zhongzheng.modules.course.service.ICourseService;
import com.zhongzheng.modules.course.vo.CourseUserVo;
import com.zhongzheng.modules.course.vo.CourseVo;
import com.zhongzheng.modules.goods.vo.GoodsPeriodStatusVo;
import com.zhongzheng.modules.goods.vo.GoodsPeriodVo;
import com.zhongzheng.modules.goods.vo.GoodsUserVo;
import com.zhongzheng.modules.goods.vo.GoodsVo;
import com.zhongzheng.modules.grade.bo.ClassGradeUserQueryBo;
import com.zhongzheng.modules.grade.bo.UserPeriodStatusAddBo;
import com.zhongzheng.modules.grade.domain.UserPeriodStatus;
import com.zhongzheng.modules.grade.service.IUserPeriodStatusService;
import com.zhongzheng.modules.user.bo.SubjectStudyRecordQueryBo;
import com.zhongzheng.modules.user.bo.UserPlanQueryBo;
import com.zhongzheng.modules.user.domain.UserStudyRecordPhoto;
import com.zhongzheng.modules.user.service.IUserStudyRecordPhotoService;
import com.zhongzheng.modules.user.service.IUserStudyRecordService;
import com.zhongzheng.modules.user.vo.SubjectStudyRecordVo;
import com.zhongzheng.modules.user.vo.UserStudyRecordPhotoVo;
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.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程Service业务层处理
 *
 * @author hjl
 * @date 2021-10-09
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private IUserPeriodStatusService userPeriodStatusService;

    @Autowired
    private IUserStudyRecordPhotoService userStudyRecordPhotoService;

    @Autowired
    private IUserStudyRecordService iUserStudyRecordService;

    @Override
    public CourseVo queryById(Long courseId){
        Course db = this.baseMapper.selectById(courseId);
        return BeanUtil.toBean(db, CourseVo.class);
    }

    @Override
    public CourseVo selectById(Long id) {
        return courseMapper.selectDetailById(id);
    }

    @Override
    public List<CourseVo> queryList(CourseQueryBo bo) {
        LambdaQueryWrapper<Course> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getPrefixName()), Course::getPrefixName, bo.getPrefixName());
        lqw.eq(StrUtil.isNotBlank(bo.getCoverUrl()), Course::getCoverUrl, bo.getCoverUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduction()), Course::getIntroduction, bo.getIntroduction());
        lqw.eq(bo.getStatus() != null, Course::getStatus, bo.getStatus());
        lqw.eq(bo.getEducationTypeId() != null, Course::getEducationTypeId, bo.getEducationTypeId());
        lqw.eq(bo.getBusinessId() != null, Course::getBusinessId, bo.getBusinessId());
        lqw.eq(bo.getSchoolId() != null, Course::getSchoolId, bo.getSchoolId());
        lqw.like(StrUtil.isNotBlank(bo.getCourseName()), Course::getCourseName, bo.getCourseName());
        lqw.eq(bo.getPublishStatus() != null, Course::getPublishStatus, bo.getPublishStatus());
        lqw.eq(bo.getSort() != null, Course::getSort, bo.getSort());
        lqw.eq(StrUtil.isNotBlank(bo.getSuitableObject()), Course::getSuitableObject, bo.getSuitableObject());
        lqw.eq(StrUtil.isNotBlank(bo.getPcDetailHtml()), Course::getPcDetailHtml, bo.getPcDetailHtml());
        lqw.eq(StrUtil.isNotBlank(bo.getMobileDetailHtml()), Course::getMobileDetailHtml, bo.getMobileDetailHtml());
        lqw.eq(bo.getMajorId() != null, Course::getMajorId, bo.getMajorId());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), Course::getCode, bo.getCode());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<CourseVo> selectList(CourseQueryBo bo) {
        return courseMapper.selectCourseList(bo);
    }

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

    @Override
    public Long insertByAddBo(CourseAddBo bo) {
        Course add = BeanUtil.toBean(bo, Course.class);
        add.setCode(ServletUtils.getEncoded("KC"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        this.save(add);
        return add.getCourseId();
    }

    @Override
    public Boolean updateByEditBo(CourseEditBo bo) {
        Course update = BeanUtil.toBean(bo, Course.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

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

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

    @Override
    public List<GoodsPeriodVo> listGoodsPeriodVo(UserPlanQueryBo bo) {
        List<GoodsPeriodVo> goodsPeriodVos = baseMapper.listGoodsPeriodVo(bo);
        for (GoodsPeriodVo goodsPeriodVo : goodsPeriodVos) {
            Long secLong = 0L;
            Long studyLong = 0L;
            SubjectStudyRecordQueryBo subjectStudyRecordQueryBo = new SubjectStudyRecordQueryBo();
            subjectStudyRecordQueryBo.setGoodsId(goodsPeriodVo.getGoodsId());
            subjectStudyRecordQueryBo.setUserId(bo.getUserId());
            subjectStudyRecordQueryBo.setGradeId(goodsPeriodVo.getGradeId());
            List<SubjectStudyRecordVo> subjectStudyRecordVos = iUserStudyRecordService.listSubject(subjectStudyRecordQueryBo);
            if (!CollectionUtils.isEmpty(subjectStudyRecordVos)) {
                for (SubjectStudyRecordVo subjectStudyRecordVo : subjectStudyRecordVos) {
                    secLong = new BigDecimal(secLong.toString()).add(new BigDecimal(subjectStudyRecordVo.getSectionNum().toString())).longValue();
                    studyLong = new BigDecimal(studyLong.toString()).add(new BigDecimal(subjectStudyRecordVo.getRecordNum().toString())).longValue();
                }
                if (secLong.equals(studyLong) && goodsPeriodVo.getExamNum().equals(goodsPeriodVo.getRecordNum())) {
                    if (goodsPeriodVo.getCheat() != 0 || goodsPeriodVo.getExamCheat() != 0) {
                        goodsPeriodVo.setPeriodStatus(3L);
                    }else if (goodsPeriodVo.getPending() != 0 || goodsPeriodVo.getExamPending() != 0) {
                        goodsPeriodVo.setPeriodStatus(2L);
                    } else {
                        goodsPeriodVo.setPeriodStatus(1L);
                    }
                } else {
                    goodsPeriodVo.setPeriodStatus(-1L);
                }
            }
        }
        return goodsPeriodVos;
    }

    @Override
    public List<GoodsPeriodStatusVo> listSection(ClassGradeUserQueryBo bo) {
        List<GoodsPeriodStatusVo> goodsPeriodStatusVos = baseMapper.listSection(bo);
        for (GoodsPeriodStatusVo goodsPeriodStatusVo : goodsPeriodStatusVos) {
            LambdaQueryWrapper<UserStudyRecordPhoto> lqw = Wrappers.lambdaQuery();
            lqw.eq(UserStudyRecordPhoto::getPeriodId, goodsPeriodStatusVo.getId());
            goodsPeriodStatusVo.setUserStudyRecordPhoto(entity2PhotoVo(userStudyRecordPhotoService.list(lqw)));
        }
        return goodsPeriodStatusVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editRebuild(ClassGradeUserQueryBo bo) {
        List<GoodsPeriodStatusVo> goodsPeriodStatusVos = baseMapper.listSection(bo);
        for (GoodsPeriodStatusVo goodsPeriodStatusVo : goodsPeriodStatusVos) {
            UserPeriodStatus userPeriodStatus = new UserPeriodStatus();
            userPeriodStatus.setId(goodsPeriodStatusVo.getId());
            userPeriodStatus.setPeriodStatus(0);
            userPeriodStatusService.updateById(userPeriodStatus);
            UserPeriodStatusAddBo userPeriodStatusAddBo = new UserPeriodStatusAddBo();
            userPeriodStatusAddBo.setPeriodStatus(1);
            userPeriodStatusAddBo.setPeriodId(goodsPeriodStatusVo.getPeriodId());
            userPeriodStatusAddBo.setCreateTime(DateUtils.getNowTime());
            userPeriodStatusAddBo.setUpdateTime(DateUtils.getNowTime());
            userPeriodStatusAddBo.setStatus(3);
            userPeriodStatusService.insertByAddBo(userPeriodStatusAddBo);
        }
        return true;
    }

    @Override
    public List<GoodsUserVo> goodsList(CourseQueryBo bo) {
        return baseMapper.goodsList(bo);
    }

    @Override
    public List<CourseUserVo> courseList(CourseQueryBo bo) {
        return baseMapper.courseList(bo);
    }

    private List<UserStudyRecordPhotoVo> entity2PhotoVo(Collection<UserStudyRecordPhoto> collection) {
        List<UserStudyRecordPhotoVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, UserStudyRecordPhotoVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<UserStudyRecordPhoto> page = (Page<UserStudyRecordPhoto>)collection;
            Page<UserStudyRecordPhotoVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }
    private boolean checkNameUnique(Course entity) {
        Course info = getOne(new LambdaQueryWrapper<Course>()
                .eq(Course::getPrefixName,entity.getPrefixName()).eq(Course::getCourseName,entity.getCourseName()).last("limit 1"));
        if (Validator.isNotNull(info)) {
            if(Validator.isNotEmpty(entity.getCourseId())){
                if(entity.getCourseId() != info.getCourseId()){
                    return true;
                }
            }else{
                return true;
            }
        }
        return false;
    }
}
