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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.SecurityUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.course.bo.CourseBusinessQueryBo;
import com.zhongzheng.modules.course.bo.CourseEducationTypeQueryBo;
import com.zhongzheng.modules.course.bo.CourseProjectTypeQueryBo;
import com.zhongzheng.modules.course.service.ICourseBusinessService;
import com.zhongzheng.modules.course.service.ICourseEducationTierService;
import com.zhongzheng.modules.course.service.ICourseEducationTypeService;
import com.zhongzheng.modules.course.service.ICourseProjectTypeService;
import com.zhongzheng.modules.course.vo.*;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.goods.vo.GoodsVo;
import com.zhongzheng.modules.grade.bo.*;
import com.zhongzheng.modules.grade.domain.ClassGradeGoods;
import com.zhongzheng.modules.grade.domain.ClassGradeSys;
import com.zhongzheng.modules.grade.service.IClassGradeGoodsService;
import com.zhongzheng.modules.grade.service.IClassGradeSysService;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import com.zhongzheng.modules.grade.vo.ClassGradeStudentVo;
import com.zhongzheng.modules.grade.vo.ClassGradeUserListVo;
import com.zhongzheng.modules.grade.vo.ClassGradeUserVo;
import com.zhongzheng.modules.system.domain.SysConfig;
import com.zhongzheng.modules.user.bo.SubjectStudyRecordQueryBo;
import com.zhongzheng.modules.user.bo.UserUpdateQueryBo;
import com.zhongzheng.modules.user.domain.SchoolProject;
import com.zhongzheng.modules.user.domain.UserUpdate;
import com.zhongzheng.modules.user.service.IUserStudyRecordService;
import com.zhongzheng.modules.user.service.IUserUpdateService;
import com.zhongzheng.modules.user.vo.SubjectStudyRecordVo;
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 com.zhongzheng.modules.grade.domain.ClassGrade;
import com.zhongzheng.modules.grade.mapper.ClassGradeMapper;
import com.zhongzheng.modules.grade.vo.ClassGradeVo;
import com.zhongzheng.modules.grade.service.IClassGradeService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 班级Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-10
 */
@Service
public class ClassGradeServiceImpl extends ServiceImpl<ClassGradeMapper, ClassGrade> implements IClassGradeService {

    @Autowired
    private  IGoodsService iGoodsService;

    @Autowired
    private ICourseEducationTypeService courseEducationTypeService;

    @Autowired
    private ICourseProjectTypeService courseProjectTypeService;

    @Autowired
    private ICourseBusinessService courseBusinessService;

    @Autowired
    private IClassGradeSysService classGradeSysService;

    @Autowired
    private IClassGradeGoodsService classGradeGoodsService;

    @Autowired
    private IUserStudyRecordService iUserStudyRecordService;

    @Autowired
    private IClassGradeUserService iClassGradeUserService;

    @Autowired
    private IUserUpdateService iUserUpdateService;

    @Override
    public ClassGradeVo queryById(Long gradeId){
        ClassGradeQueryBo classGradeQueryBo = new ClassGradeQueryBo();
        classGradeQueryBo.setGradeId(gradeId);
        return entity2Vo(baseMapper.queryList(classGradeQueryBo)).get(0);
    }

    @Override
    public List<ClassGradeVo> queryList(ClassGradeQueryBo bo) {
        return entity2Vo(baseMapper.queryList(bo));
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(ClassGradeAddBo bo) {
        ClassGrade add = BeanUtil.toBean(bo, ClassGrade.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        add.setGradeCode(ServletUtils.getEncoded("BJ"));
        LambdaQueryWrapper<ClassGrade> lqw = Wrappers.lambdaQuery();
        lqw.eq(ClassGrade::getClassName, add.getClassName());
        lqw.eq(ClassGrade::getStatus, 1);
        List<ClassGrade> list = this.list(lqw);
        if (CollectionUtils.isNotEmpty(list)){
            throw new RuntimeException("班级名称不能重复");
        }
        boolean save = this.save(add);
        if (bo.getClassGradeGoodsAddBos() != null){
            for (Long classGradeGoodsAddBo : bo.getClassGradeGoodsAddBos()) {
                ClassGradeGoods classGradeGoods = new ClassGradeGoods();
                classGradeGoods.setGradeId(add.getGradeId());
                classGradeGoods.setGoodsId(classGradeGoodsAddBo);
                classGradeGoods.setCreateTime(DateUtils.getNowTime());
                classGradeGoods.setUpdateTime(DateUtils.getNowTime());
                classGradeGoodsService.save(classGradeGoods);
            }
        }
        if (bo.getSysUserId() != null){
            ClassGradeSys classGradeSys = new ClassGradeSys();
            classGradeSys.setGradeId(add.getGradeId());
            classGradeSys.setCreateBy(SecurityUtils.getUsername());
            classGradeSys.setStartTime(DateUtils.getNowTime());
            classGradeSys.setSysUserId(bo.getSysUserId());
            classGradeSys.setStatus(1);

            classGradeSys.setCreateTime(DateUtils.getNowTime());
            classGradeSys.setUpdateTime(DateUtils.getNowTime());
            classGradeSysService.save(classGradeSys);
        }

        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(ClassGradeEditBo bo) {
        ClassGrade update = BeanUtil.toBean(bo, ClassGrade.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if (bo.getStatus() != -1) {
            LambdaQueryWrapper<ClassGrade> lqw = Wrappers.lambdaQuery();
            lqw.eq(ClassGrade::getClassName, update.getClassName());
            lqw.eq(ClassGrade::getStatus, 1);
            lqw.eq(ClassGrade::getGradeId, update.getGradeId());
            List<ClassGrade> list = this.list(lqw);
            if (CollectionUtils.isEmpty(list)) {
                lqw.clear();
                lqw.eq(ClassGrade::getClassName, update.getClassName());
                lqw.eq(ClassGrade::getStatus, 1);
                List<ClassGrade> classList = this.list(lqw);
                if (CollectionUtils.isNotEmpty(classList)){
                    throw new RuntimeException("班级名称不能重复");
                }
            }
        }
        if (bo.getSysUserId() != null){
            LambdaQueryWrapper<ClassGradeSys> lqw = new LambdaQueryWrapper<>();
            lqw.like(ClassGradeSys::getGradeId,bo.getGradeId());
            lqw.like(ClassGradeSys::getSysUserId,bo.getSysUserId());
            lqw.like(ClassGradeSys::getStatus,1);
            if (CollectionUtils.isEmpty(classGradeSysService.list(lqw))){
                lqw.clear();
                lqw.like(ClassGradeSys::getGradeId,bo.getGradeId());
                lqw.like(ClassGradeSys::getStatus,1);
                ClassGradeSys classGradeSys1 = new ClassGradeSys();
                classGradeSys1.setStatus(0);
                classGradeSys1.setEndTime(DateUtils.getNowTime());
                classGradeSys1.setUpdateTime(DateUtils.getNowTime());
                classGradeSysService.update(classGradeSys1,lqw);

                ClassGradeSys classGradeSys = new ClassGradeSys();
                classGradeSys.setGradeId(bo.getGradeId());
                classGradeSys.setCreateBy(SecurityUtils.getUsername());
                classGradeSys.setStartTime(DateUtils.getNowTime());
                classGradeSys.setSysUserId(bo.getSysUserId());
                classGradeSys.setStatus(1);
                classGradeSys.setCreateTime(DateUtils.getNowTime());
                classGradeSys.setUpdateTime(DateUtils.getNowTime());
                classGradeSysService.save(classGradeSys);
            }
        }
        return this.updateById(update);
    }

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

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

    @Override
    public List<ClassGradeStudentVo> listGrade(ClassGradeUserQueryBo bo) {
        List<ClassGradeStudentVo> classGradeStudentVos = baseMapper.listGrade(bo);
        for (ClassGradeStudentVo classGradeStudentVo : classGradeStudentVos) {
            Long secLong = 0L;
            Long studyLong = 0L;

            SubjectStudyRecordQueryBo subjectStudyRecordQueryBo = new SubjectStudyRecordQueryBo();
            subjectStudyRecordQueryBo.setGoodsId(classGradeStudentVo.getGoodsId());
            subjectStudyRecordQueryBo.setUserId(classGradeStudentVo.getUserId());
            List<SubjectStudyRecordVo> subjectStudyRecordVos = iUserStudyRecordService.listSubject(subjectStudyRecordQueryBo);
            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();

            }
            //BigDecimal divide = new BigDecimal(studyLong.toString()).divide(new BigDecimal(secLong.toString()),2,BigDecimal.ROUND_HALF_UP);
            //classGradeStudentVo.setStudyNum(divide.multiply(new BigDecimal("100")).longValue());
            classGradeStudentVo.setSecAllNum(secLong);
            classGradeStudentVo.setStuAllNum(studyLong);
            UserUpdateQueryBo userUpdateQueryBo = new UserUpdateQueryBo();
            userUpdateQueryBo.setUserId(classGradeStudentVo.getUserId());
            classGradeStudentVo.setUserUpdates(iUserUpdateService.queryList(userUpdateQueryBo));
        }
        return classGradeStudentVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editUserGrade(ClassGradeUserAddQueryBo bo) {
        ClassGradeQueryBo classGradeQueryBo = new ClassGradeQueryBo();
        classGradeQueryBo.setGradeId(bo.getGradeId());
        ClassGradeVo classGradeVo = entity2Vo(baseMapper.queryList(classGradeQueryBo)).get(0);
        if ((classGradeVo.getStudentUpper() - classGradeVo.getStudentNum()) < bo.getUserId().length){
            throw new IllegalArgumentException("当前班级超出上限，不允许添加这么多学员");
        }
        for (Long aLong : bo.getUserId()) {
            //防止再次进入相同班级，不可进入已经在有效期内班级进入另外一个班级
            ClassGradeUserQueryBo classGradeUserQueryBo = new ClassGradeUserQueryBo();
            classGradeUserQueryBo.setUserId(aLong);
            classGradeUserQueryBo.setGradeId(bo.getGradeId());
            List<Integer> status = new ArrayList<>();
            status.add(1);
            classGradeUserQueryBo.setStatus(status);
            List<ClassGradeUserVo> classGradeUserVos = iClassGradeUserService.queryList(classGradeUserQueryBo);
            if (CollectionUtils.isNotEmpty(classGradeUserVos)){
                continue;
            }
            //进入班级
            ClassGradeUserAddBo classGradeUserAddBo = new ClassGradeUserAddBo();
            classGradeUserAddBo.setUserId(aLong);
            classGradeUserAddBo.setGradeId(bo.getGradeId());
            classGradeUserAddBo.setCreateBy(SecurityUtils.getUsername());
            classGradeUserAddBo.setStatus(1);
            classGradeUserAddBo.setCreateTime(DateUtils.getNowTime());
            classGradeUserAddBo.setUpdateTime(DateUtils.getNowTime());
            classGradeUserAddBo.setFromType(2);
            iClassGradeUserService.insertByAddBo(classGradeUserAddBo);
        }

        return true;
    }

    @Override
    public List<ClassGradeUserListVo> listGradeInform(ClassGradeQueryBo bo) {
        List<ClassGradeUserListVo> classGradeVos = baseMapper.listGradeInform(bo);
        for (ClassGradeUserListVo classGradeVo : classGradeVos) {
            ClassGradeUserQueryBo classGradeUserQueryBo = new ClassGradeUserQueryBo();
            classGradeUserQueryBo.setGradeId(classGradeVo.getGradeId());
            classGradeVo.setClassGradeStudentVos(baseMapper.listGrade(classGradeUserQueryBo));
        }
        return classGradeVos;
    }

    @Override
    public List<ClassGradeStudentVo> listGradeStudy(ClassGradeQueryBo bo) {
        return baseMapper.listGradeStudy(bo);
    }

    @Override
    public List<CourseUserEducationTypeVo> listGradeService(ClassGradeQueryBo bo) {
        CourseEducationTypeQueryBo courseEducationTypeQueryBo = new CourseEducationTypeQueryBo();
        courseEducationTypeQueryBo.setStatus(bo.getStatus());
        List<CourseUserEducationTypeVo> courseUserEducationTypeVos = entity2EducationVo(courseEducationTypeService.queryList(courseEducationTypeQueryBo));
        for (CourseUserEducationTypeVo courseUserEducationTypeVo : courseUserEducationTypeVos) {
            CourseProjectTypeQueryBo courseProjectTypeQueryBo = new CourseProjectTypeQueryBo();
            courseProjectTypeQueryBo.setStatus(bo.getStatus());
            courseProjectTypeQueryBo.setEducationId(Convert.toInt(courseUserEducationTypeVo.getId()));
            List<CourseUserProjectTypeVo> courseUserProjectTypeVos = entity2ServiceProjectVo(courseProjectTypeService.queryList(courseProjectTypeQueryBo));
            if (CollectionUtils.isNotEmpty(courseUserProjectTypeVos)) {
                for (CourseUserProjectTypeVo courseUserProjectTypeVo : courseUserProjectTypeVos) {
                    CourseBusinessQueryBo courseBusinessQueryBo = new CourseBusinessQueryBo();
                    courseBusinessQueryBo.setStatus(bo.getStatus());
                    courseBusinessQueryBo.setProjectId(Convert.toInt(courseUserProjectTypeVo.getId()));
                    List<CourseUserBusinessVo> courseUserBusinessVos = entity2ServiceBusinessVo(courseBusinessService.queryList(courseBusinessQueryBo));
                    if (CollectionUtils.isNotEmpty(courseUserBusinessVos)) {
                        for (CourseUserBusinessVo courseUserBusinessVo : courseUserBusinessVos) {
                            List<ClassGradeStudentVo> classGradeStudentVos = baseMapper.listGradeService(courseUserBusinessVo.getId());
                            courseUserBusinessVo.setClassGradeStudentVos(classGradeStudentVos);
                        }
                    }
                    courseUserProjectTypeVo.setCourseUserBusiness(courseUserBusinessVos);
                }
            }
            courseUserEducationTypeVo.setCourseUserProjectTypeVo(courseUserProjectTypeVos);
        }
        return courseUserEducationTypeVos;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<CourseUserEducationTypeVo> entity2EducationVo(Collection<CourseEducationTypeVo> collection) {
        List<CourseUserEducationTypeVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseUserEducationTypeVo.class))
                .collect(Collectors.toList());
        return voList;
    }

    private List<CourseUserProjectTypeVo> entity2ServiceProjectVo(Collection<CourseProjectTypeVo> collection) {
        List<CourseUserProjectTypeVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseUserProjectTypeVo.class))
                .collect(Collectors.toList());
        return voList;
    }

    private List<CourseUserBusinessVo> entity2ServiceBusinessVo(Collection<CourseBusinessVo> collection) {
        List<CourseUserBusinessVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseUserBusinessVo.class))
                .collect(Collectors.toList());
        return voList;
    }
}
