package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.params.TeachClazzParams;
import com.qmth.distributed.print.business.bean.result.DictionaryResult;
import com.qmth.distributed.print.business.bean.result.TeachClazzResult;
import com.qmth.distributed.print.business.service.BasicTeachClazzService;
import com.qmth.teachcloud.common.entity.BasicTeachClazz;
import com.qmth.distributed.print.business.entity.TeachClazz;
import com.qmth.distributed.print.business.entity.TeachCourse;
import com.qmth.distributed.print.business.entity.TeachStudent;
import com.qmth.distributed.print.business.mapper.TeachClazzMapper;
import com.qmth.distributed.print.business.service.TeachClazzService;
import com.qmth.distributed.print.business.service.TeachCourseService;
import com.qmth.distributed.print.business.service.TeachStudentService;
import com.qmth.teachcloud.common.base.BaseEntity;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 教学班服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-02-09
 */
@Service
public class TeachClazzServiceImpl extends ServiceImpl<TeachClazzMapper,TeachClazz> implements TeachClazzService {

    @Resource
    private TeachStudentService teachStudentService;

    @Resource
    private TeachCourseService teachCourseService;

    @Resource
    private BasicTeachClazzService basicTeachClazzService;

    @Override
    public IPage<TeachClazzResult> teachClazzPage(Long teachCourseId, String teachClazzName, int pageNumber,
            int pageSize) {
        TeachCourse teachCourse = teachCourseService.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        Long examId = teachCourse.getExamId();
        String courseCode = teachCourse.getCourseCode();

        Long leaderId = teachCourse.getCreateId();
        TeachCourse leaderTeachCourse = teachCourseService.findByExamIdCourseCodeAndUserId(examId, courseCode, leaderId);
        Long leaderTeachCourseId = leaderTeachCourse.getId();

        teachClazzName = SystemConstant.translateSpecificSign(teachClazzName);
        IPage<TeachClazzResult> resultIPage;

        IPage<TeachClazzResult> selfPage = this.baseMapper.findTeachClazzPage(new Page<>(pageNumber, pageSize),
                teachCourseId, teachClazzName, leaderTeachCourseId);
        if (CollectionUtils.isEmpty(selfPage.getRecords())) {
            // 查询该教学课程下所有教学班
            resultIPage = this.baseMapper.findTeachClazzPage(new Page<>(pageNumber, pageSize), leaderTeachCourseId,
                    teachClazzName, null);
        } else {
            // 查找分配给自己的教学班 并且获取每个班映射的实际教学班信息
            selfPage.getRecords().forEach(e -> {
                Long basicTeachClazzId = e.getBasicTeachClazzId();
                Long belongTeachCourseId = e.getBelongTeachCourseId();

                TeachClazz mappingClazz = this.getOne(
                        new QueryWrapper<TeachClazz>().lambda().eq(TeachClazz::getTeachCourseId, belongTeachCourseId).eq(TeachClazz::getBasicTeachClazzId, basicTeachClazzId).last(SystemConstant.LIMIT1));
                e.setId(mappingClazz.getId());
                e.setTeachCourseId(mappingClazz.getTeachCourseId());
            });
            resultIPage = selfPage;
        }

        List<TeachClazzResult> teachClazzResultList = resultIPage.getRecords();

        for (TeachClazzResult teachClazzResult : teachClazzResultList) {
            Long id = teachClazzResult.getId();
            int count = teachStudentService.count(
                    new QueryWrapper<TeachStudent>().lambda().eq(TeachStudent::getTeachClazzId, id));
            teachClazzResult.setTeachStudentCount(count);
        }
        return resultIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void selectTeachClazz(TeachClazzParams teachClazzParams, SysUser requestUser) {
        Long teachCourseId = teachClazzParams.getTeachCourseId();
        TeachCourse teachCourse = teachCourseService.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }

        List<Long> dbIdList = this.list(
                new QueryWrapper<TeachClazz>().lambda().eq(TeachClazz::getTeachCourseId, teachCourseId)).stream().map(TeachClazz::getBasicTeachClazzId).collect(Collectors.toList());

        List<TeachClazz> teachClazzList = new ArrayList<>();
        List<Long> idList = teachClazzParams.getIdList().stream().filter(e -> !dbIdList.contains(e)).collect(Collectors.toList());
        for (Long basicTeachClazzId : idList) {
            BasicTeachClazz basicTeachClazz = basicTeachClazzService.getById(basicTeachClazzId);
            if (Objects.isNull(basicTeachClazz)) {
                throw ExceptionResultEnum.ERROR.exception("课程字典不存在");
            }

            TeachClazz teachClazz = new TeachClazz();
            teachClazz.setSchoolId(basicTeachClazz.getSchoolId());
            teachClazz.setTeachCourseId(teachCourseId);
            teachClazz.setBasicTeachClazzId(basicTeachClazzId);
            teachClazz.setUserId(teachCourse.getUserId());
            teachClazz.setClazzName(basicTeachClazz.getClazzName());
            teachClazz.insertInfo(requestUser.getId());
            teachClazzList.add(teachClazz);
        }
        this.saveBatch(teachClazzList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteTeachClazzBatch(List<Long> idList) {
        // 删除班级时、同步删除学生
        List<TeachStudent> teachStudentList = teachStudentService.list(
                new QueryWrapper<TeachStudent>().lambda().in(TeachStudent::getTeachClazzId, idList));
        // 删除教学学生
        teachStudentService.deleteTeachStudentBatch(
                teachStudentList.stream().map(BaseEntity::getId).distinct().collect(Collectors.toList()));
        return this.removeByIds(idList);
    }

    @Override
    public List<DictionaryResult> findTeachCourseByUserId(Long userId) {
        Long schoolId = SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId()));
        List<TeachCourse> teachCourseList = teachCourseService.list(
                new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getUserId, userId).eq(TeachCourse::getSchoolId, schoolId).orderByDesc(TeachCourse::getCreateTime));
        List<DictionaryResult> dictionaryResultList = new ArrayList<>();
        //        for (TeachCourse teachCourse : teachCourseList) {
        //            BasicCourse basicCourse = basicCourseService.getById(teachCourse.getBasicCourseId());
        //            if (basicCourse.getEnable()) {
        //                DictionaryResult dictionaryResult = new DictionaryResult();
        //                dictionaryResult.setId(teachCourse.getId());
        //                dictionaryResult.setCode(basicCourse.getCode());
        //                dictionaryResult.setName(basicCourse.getName());
        //                dictionaryResultList.add(dictionaryResult);
        //            }
        //        }
        return dictionaryResultList;
    }
}
