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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.AssignClazzParam;
import com.qmth.distributed.print.business.bean.params.TeachCourseParams;
import com.qmth.distributed.print.business.bean.params.TeachCourseSelectParam;
import com.qmth.distributed.print.business.bean.params.TeacherTeamParam;
import com.qmth.distributed.print.business.bean.result.ClazzDistributedResult;
import com.qmth.distributed.print.business.bean.result.DictionaryResult;
import com.qmth.distributed.print.business.bean.result.TeachCourseResult;
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.TeachCourseMapper;
import com.qmth.distributed.print.business.service.*;
import com.qmth.teachcloud.common.base.BaseEntity;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.bean.params.UserSaveParams;
import com.qmth.teachcloud.common.bean.result.TeacherSelectResult;
import com.qmth.teachcloud.common.bean.result.TeacherTeamResult;
import com.qmth.teachcloud.common.bean.result.UserRoleNameResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCourse;
import com.qmth.teachcloud.common.entity.SysRole;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.RoleTypeEnum;
import com.qmth.teachcloud.common.service.*;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 教学课程服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-02-07
 */
@Service
public class TeachCourseServiceImpl extends ServiceImpl<TeachCourseMapper, TeachCourse> implements TeachCourseService {

    @Resource
    private BasicCourseService basicCourseService;

    @Resource
    private SysOrgService sysOrgService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private TeachClazzService teachClazzService;

    @Resource
    private ObeCourseTargetService obeCourseTargetService;

    @Resource
    private ObeCourseEvaluationService obeCourseEvaluationService;

    @Resource
    private ObeCourseWeightService obeCourseWeightService;

    @Resource
    private ObeCourseDimensionService obeCourseDimensionService;

    @Resource
    private BasicTeachClazzService basicTeachClazzService;

    @Resource
    private TeachStudentService teachStudentService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Override
    public IPage<TeachCourseResult> teachCoursePage(Long examId, String courseName, int pageNumber, int pageSize) {
        courseName = SystemConstant.translateSpecificSign(courseName);
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(requestUser.getSchoolId(),
                requestUser.getId(), ServletUtil.getRequest().getServletPath());
        return this.baseMapper.findTeachCoursePage(new Page<>(pageNumber, pageSize), examId, courseName, requestUser.getSchoolId(), dpr);
    }

    @Deprecated
    @Transactional
    @Override
    public Boolean manualCreate(TeachCourseParams teachCourseParams, SysUser requestUser) {
        throw ExceptionResultEnum.ERROR.exception("废弃的方法");
        //        String courseCode = teachCourseParams.getCourseCode();
        //        String courseName = teachCourseParams.getCourseName();
        //        Long schoolId = requestUser.getSchoolId();
        //        Long userId = requestUser.getId();
        //        Long basicCourseId;
        //
        //        // 校验
        //        BasicCourse basicCourse = basicCourseService.getOne(
        //                new QueryWrapper<BasicCourse>().lambda().eq(BasicCourse::getSchoolId, schoolId).eq(BasicCourse::getCode, courseCode));
        //        if (Objects.nonNull(basicCourse)) {
        //            // 根据课程编号查询存在课程判断名称是否一致
        //            if (!courseName.equals(basicCourse.getName())) {
        //                throw ExceptionResultEnum.ERROR.exception("课程编号[" + courseCode + "]的课程名称错误");
        //            } else {
        //                basicCourseId = basicCourse.getId();
        //                // 判断重复教学课程
        //                if (this.count(new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getSchoolId, schoolId)
        //                        .eq(TeachCourse::getUserId, userId).eq(TeachCourse::getBasicCourseId, basicCourseId)) > 0) {
        //                    throw ExceptionResultEnum.ERROR.exception("课程[" + courseName + "]已经创建");
        //                }
        //            }
        //        } else {
        //            // 不存在课程,直接新增一个课程！
        //            BasicCourseParams basicCourseParams = new BasicCourseParams();
        //            basicCourseParams.setCourseCode(courseCode);
        //            basicCourseParams.setCourseName(courseName);
        //            basicCourseParams.setTeachingRoomId(requestUser.getOrgId());
        //            basicCourseId = basicCourseService.saveBasicCourse(basicCourseParams, requestUser);
        //        }
        //        TeachCourse teachCourse = new TeachCourse();
        //        teachCourse.setSchoolId(schoolId);
        //        teachCourse.setBasicCourseId(basicCourseId);
        //        teachCourse.setUserId(userId);
        //        teachCourse.setEnable(true);
        //        teachCourse.insertInfo(userId);
        //        return this.save(teachCourse);
    }

    @Transactional
    @Override
    public void selectCreate(TeachCourseSelectParam teachCourseSelectParam, SysUser requestUser) {
        Long schoolId = requestUser.getSchoolId();
        Long userId = requestUser.getId();
        Long examId = teachCourseSelectParam.getExamId();
        List<String> courseCodeList = teachCourseSelectParam.getCourseCodeList();

        if (CollectionUtils.isNotEmpty(courseCodeList)) {
            List<String> occupiedCourseCodeList = this.list(
                            new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getExamId, examId).eq(TeachCourse::getUserId, userId)).stream().map(TeachCourse::getCourseCode)
                    .collect(Collectors.toList());

            courseCodeList = courseCodeList.stream().filter(e -> !occupiedCourseCodeList.contains(e)).collect(Collectors.toList());

            TeachCourse tmp = new TeachCourse();
            tmp.setSchoolId(schoolId);
            tmp.setExamId(examId);
            tmp.setUserId(userId);
            tmp.setEnable(true);
            tmp.setWeightSetting(false);

            for (String courseCode : courseCodeList) {
                if (Objects.isNull(basicCourseService.findByCourseCode(courseCode, schoolId))) {
                    throw ExceptionResultEnum.ERROR.exception("课程不存在");
                }
                TeachCourse cell = new TeachCourse();
                BeanUtils.copyProperties(tmp, cell);
                cell.setCourseCode(courseCode);
                cell.insertInfo(userId);
                this.save(cell);

                // 创建默认评价方式
                obeCourseEvaluationService.createDefaultCourseEvaluation(cell.getId());
            }
        }
    }

    @Deprecated
    @Transactional
    @Override
    public void importTeachCourse(MultipartFile file, SysUser requestUser) {
        throw ExceptionResultEnum.ERROR.exception("废弃的方法");
        //        List<LinkedMultiValueMap<Integer, Object>> finalList = ExcelUtil.excelReader(file.getInputStream(), Lists.newArrayList(TeachCourseDto.class),
        //                (finalExcelList, finalColumnNameList, finalExcelErrorList) -> {
        //                    if (finalExcelErrorList.size() > 0) {
        //                        throw ExceptionResultEnum.ERROR.exception(JSONObject.toJSONString(finalExcelErrorList));
        //                    }
        //                    return finalExcelList;
        //                }, 2);
        //
        //        if (Objects.nonNull(finalList) && finalList.size() > 0) {
        //            for (int i = 0; i < finalList.size(); i++) {
        //                LinkedMultiValueMap<Integer, Object> map = finalList.get(i);
        //                List<Object> teachCourseImportDtoList = map.get(i);
        //                for (int y = 0; y < Objects.requireNonNull(teachCourseImportDtoList).size(); y++) {
        //                    if (teachCourseImportDtoList.get(y) instanceof TeachCourseDto) {
        //                        TeachCourseDto teachCourseDto = (TeachCourseDto) teachCourseImportDtoList.get(y);
        //                        String courseCode = teachCourseDto.getCourseCode();
        //                        String courseName = teachCourseDto.getCourseName();
        //                        TeachCourseParams teachCourseParams = new TeachCourseParams();
        //                        teachCourseParams.setCourseCode(courseCode);
        //                        teachCourseParams.setCourseName(courseName);
        //                        this.manualCreate(teachCourseParams, requestUser);
        //                    }
        //                }
        //            }
        //        }
    }

    @Override
    public List<DictionaryResult> findBasicCourseByUser(SysUser requestUser) {
        Long userId = requestUser.getId();
        Set<Long> orgIdSet = sysOrgService.findDeepOrgIdListByUserId(userId);
        QueryWrapper<BasicCourse> basicCourseQueryWrapper = new QueryWrapper<>();
        basicCourseQueryWrapper.lambda().eq(BasicCourse::getEnable, true);
        if (orgIdSet.size() > 0) {
            basicCourseQueryWrapper.lambda().in(BasicCourse::getTeachingRoomId, orgIdSet);
        }
        List<BasicCourse> basicCourseList = basicCourseService.list(basicCourseQueryWrapper);

        List<DictionaryResult> resultList = new ArrayList<>();
        for (BasicCourse basicCourse : basicCourseList) {
            DictionaryResult dictionaryResult = new DictionaryResult();
            BeanUtils.copyProperties(basicCourse, dictionaryResult);
            resultList.add(dictionaryResult);
        }
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTeachCourseBatch(List<Long> idList) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        Long requestUserId = requestUser.getId();
        List<TeachCourse> teachCourseList = this.listByIds(idList);
        List<String> cantDeleteCourseCodeList = teachCourseList.stream().filter(e -> !e.getCreateId().equals(requestUserId)).map(TeachCourse::getCourseCode)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(cantDeleteCourseCodeList)) {
            throw ExceptionResultEnum.ERROR.exception(
                    String.format("[%s]课程非本人创建,无法删除", String.join(",", cantDeleteCourseCodeList)));
        }
        List<TeachCourse> mainTeachCourseList = teachCourseList.stream().filter(e -> e.getCreateId().equals(e.getUserId())).collect(Collectors.toList());
        if (mainTeachCourseList.size() > 0) {
            for (TeachCourse mainTeachCourse : mainTeachCourseList) {
                List<TeachCourse> teamList = this.list(
                        new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getExamId, mainTeachCourse.getExamId())
                                .eq(TeachCourse::getCourseCode, mainTeachCourse.getCourseCode())
                                .eq(TeachCourse::getCreateId, requestUserId).ne(TeachCourse::getUserId, requestUserId));
                if (CollectionUtils.isNotEmpty(teamList)) {
                    throw ExceptionResultEnum.ERROR.exception(
                            String.format("请先删除课程(编号)[%s]下的教师团队，再删除课程", mainTeachCourse.getCourseCode()));
                }
            }
        }

        for (Long teachCourseId : idList) {
            // 删除教学学生
            teachStudentService.remove(
                    new QueryWrapper<TeachStudent>().lambda().eq(TeachStudent::getTeachCourseId, teachCourseId));
            // 删除教学班
            teachClazzService.remove(
                    new QueryWrapper<TeachClazz>().lambda().eq(TeachClazz::getTeachCourseId, teachCourseId).or()
                            .eq(TeachClazz::getBelongTeachCourseId, teachCourseId));

            // 删除教学课程
            this.removeById(teachCourseId);
        }
    }

    @Transactional
    @Override
    public void manualCreateTeacher(TeacherTeamParam teacherTeamParam, SysUser requestUser) throws IllegalAccessException {
        String name = teacherTeamParam.getTeacherName();
        String code = teacherTeamParam.getTeacherCode();
        Long teachCourseId = teacherTeamParam.getTeachCourseId();
        TeachCourse teachCourse = this.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        Long examId = teachCourse.getExamId();
        String courseCode = teachCourse.getCourseCode();

        Long requestUserId = requestUser.getId();
        Long schoolId = requestUser.getSchoolId();
        Long teacherId;

        SysUser dbUser = sysUserService.getOne(
                new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getCode, code));
        if (Objects.nonNull(dbUser)) {
            if (!name.equals(dbUser.getRealName())) {
                // 用户名称不一致
                throw ExceptionResultEnum.ERROR.exception("用户名/工号[" + code + "]的教师用户名称错误");
            } else {
                teacherId = dbUser.getId();
                // 判断在该教师团队下已经存在该教师
                if (this.count(new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getExamId, examId)
                        .eq(TeachCourse::getCourseCode, courseCode).eq(TeachCourse::getUserId, teacherId)) > 0) {
                    throw ExceptionResultEnum.ERROR.exception("教师[" + name + "]已经在教师团队中");
                }
            }
        } else {
            // 不存在用户，直接创建一个学校老师用户
            SysRole schoolTeacher = sysRoleService.getOne(
                    new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.SCHOOL_TEACHER));
            if (Objects.isNull(schoolTeacher)) {
                throw ExceptionResultEnum.ERROR.exception("缺少学校教师角色");
            }
            // 创建用户
            UserSaveParams userSaveParams = new UserSaveParams();
            userSaveParams.setSchoolId(schoolId);
            userSaveParams.setLoginName(code);
            userSaveParams.setRealName(name);
            userSaveParams.setCode(code);
            userSaveParams.setPassword(SystemConstant.DEFAULT_PASSWORD);
            userSaveParams.setOrgId(requestUser.getOrgId());
            userSaveParams.setEnable(true);
            userSaveParams.setRoleIds(new Long[] { schoolTeacher.getId() });
            teacherId = sysUserService.saveUser(userSaveParams);
        }
        // 添加教师团队
        TeachCourse tmp = new TeachCourse();
        tmp.setSchoolId(schoolId);
        tmp.setExamId(examId);
        tmp.setCourseCode(courseCode);
        tmp.setWeightSetting(false);
        tmp.setUserId(teacherId);
        tmp.setEnable(true);
        tmp.insertInfo(requestUserId);
        this.save(tmp);

        // 创建默认的评价方式
        obeCourseEvaluationService.createDefaultCourseEvaluation(tmp.getId());
    }

    @Transactional
    @Override
    public void selectCreateTeacher(Long teachCourseId, List<Long> userIdList, SysUser requestUser) {
        Long schoolId = requestUser.getSchoolId();
        Long requestUserId = requestUser.getId();

        TeachCourse teachCourse = this.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学班不存在");
        }
        Long examId = teachCourse.getExamId();
        String courseCode = teachCourse.getCourseCode();

        if (CollectionUtils.isNotEmpty(userIdList)) {
            // 过滤userIdList
            userIdList = sysUserService.listByIds(userIdList).stream().filter(SysUser::getEnable).map(BaseEntity::getId)
                    .distinct().collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(userIdList)) {
                List<Long> alreadyCreated = this.list(
                                new QueryWrapper<TeachCourse>().lambda().in(TeachCourse::getUserId, userIdList)
                                        .eq(TeachCourse::getCourseCode, courseCode)).stream().map(TeachCourse::getUserId)
                        .distinct().collect(Collectors.toList());

                // 去掉已经在该课程教师团队的老师
                userIdList.removeAll(alreadyCreated);

                // 创建教学课程
                List<TeachCourse> teachCourseList = userIdList.stream().flatMap(e -> {
                    TeachCourse tmp = new TeachCourse();
                    tmp.setSchoolId(schoolId);
                    tmp.setExamId(examId);
                    tmp.setCourseCode(courseCode);
                    tmp.setWeightSetting(false);
                    tmp.setUserId(e);
                    tmp.setEnable(true);
                    tmp.insertInfo(requestUserId);
                    return Stream.of(tmp);
                }).collect(Collectors.toList());

                // 新增课程
                this.saveBatch(teachCourseList);

                for (TeachCourse tmp : teachCourseList) {
                    // 创建默认评价方式
                    obeCourseEvaluationService.createDefaultCourseEvaluation(tmp.getId());
                }
            }
        }
    }

    @Deprecated
    @Transactional
    @Override
    public void importTeacherTeam(MultipartFile file, Long basicCourseId, SysUser requestUser) throws IOException, NoSuchFieldException, IllegalAccessException {
        throw ExceptionResultEnum.ERROR.exception("废弃的方法");
        //        List<LinkedMultiValueMap<Integer, Object>> finalList = ExcelUtil.excelReader(file.getInputStream(), Lists.newArrayList(TeacherTeamDto.class),
        //                (finalExcelList, finalColumnNameList, finalExcelErrorList) -> {
        //                    if (finalExcelErrorList.size() > 0) {
        //                        throw ExceptionResultEnum.ERROR.exception(JSONObject.toJSONString(finalExcelErrorList));
        //                    }
        //                    return finalExcelList;
        //                }, 2);
        //
        //        if (Objects.nonNull(finalList) && finalList.size() > 0) {
        //            for (int i = 0; i < finalList.size(); i++) {
        //                LinkedMultiValueMap<Integer, Object> map = finalList.get(i);
        //                List<Object> teacherTeamImportList = map.get(i);
        //                for (int y = 0; y < Objects.requireNonNull(teacherTeamImportList).size(); y++) {
        //                    if (teacherTeamImportList.get(y) instanceof TeacherTeamDto) {
        //                        TeacherTeamDto teacherTeamDto = (TeacherTeamDto) teacherTeamImportList.get(y);
        //                        TeacherTeamParam teacherTeamParam = new TeacherTeamParam();
        //                        teacherTeamParam.setTeacherCode(teacherTeamDto.getCode());
        //                        teacherTeamParam.setTeacherName(teacherTeamDto.getName());
        //                        teacherTeamParam.setBasicCourseId(basicCourseId);
        //                        this.manualCreateTeacher(teacherTeamParam, requestUser);
        //                    }
        //                }
        //            }
        //        }
    }

    @Override
    public IPage<TeacherTeamResult> findTeacherTeamPage(Long teachCourseId, String userInfo, int pageNumber,
            int pageSize) {
        TeachCourse teachCourse = this.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        // 教学课程主管责任人
        Long leaderId = teachCourse.getCreateId();
        String courseCode = teachCourse.getCourseCode();

        if (SystemConstant.strNotNull(userInfo)) {
            userInfo = SystemConstant.translateSpecificSign(userInfo);
        }
        IPage<TeacherTeamResult> page = this.baseMapper.findTeacherTeamPage(new Page<>(pageNumber, pageSize), courseCode, leaderId, userInfo);
        page.getRecords().forEach(e -> {
            Long userId = e.getUserId();
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(userId);
            List<UserRoleNameResult> roleNameList = sysUserService.selectRoleNames(userIdList);
            if (roleNameList.size() == 1) {
                e.setRoleName(roleNameList.get(0).getRoleNames());
            }
        });
        return page;
    }

    @Override
    public List<TeacherSelectResult> findUserByOrgId(Long orgId) {
        List<Long> temp = new ArrayList<>();
        temp.add(orgId);
        Set<Long> orgIdSet = sysOrgService.findDeepOrgIdListByOrgIdList(temp);
        return this.baseMapper.findTeacherByOrgIds(new ArrayList<>(orgIdSet));
    }

    /**
     * 插入老师和课程关联表
     *
     * @param basicCourseId
     * @param teachIdSet
     */
    @Override
    @Transactional
    public void updateByCourseIdAndTeacherList(Long basicCourseId, Set<Long> teachIdSet) {
        //        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        //        List<TeachCourse> teachCourseList = null;
        //        // 删除原有的全部
        //        this.remove(new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getBasicCourseId, basicCourseId).gt(TeachCourse::getId, 0));
        //        // 新增
        //        if (!CollectionUtils.isEmpty(teachIdSet)) {
        //            teachCourseList = new ArrayList<>();
        //            for (Long teachId : teachIdSet) {
        //                teachCourseList.add(new TeachCourse(sysUser, basicCourseId, teachId));
        //            }
        //            this.saveBatch(teachCourseList);
        //        }
    }

    @Override
    public TeachCourse findByExamIdCourseCodeAndUserId(Long examId, String courseCode, Long userId) {
        TeachCourse teachCourse = this.getOne(
                new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getExamId, examId).eq(TeachCourse::getCourseCode, courseCode).eq(TeachCourse::getUserId, userId)
                        .last(SystemConstant.LIMIT1));
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        return teachCourse;
    }

    @Override
    public List<ClazzDistributedResult> findClazzDistributedStatus(Long teachCourseId, String clazzName) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        Long requestUserId = requestUser.getId();
        clazzName = SystemConstant.translateSpecificSign(clazzName);

        TeachCourse teachCourse = this.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }

        if (!requestUserId.equals(teachCourse.getCreateId())) {
            throw ExceptionResultEnum.ERROR.exception("非课程创建人没有分配班级的权限");
        }
        Long leaderTeachCourseId = teachCourse.getId();
        if (!teachCourse.getUserId().equals(teachCourse.getCreateId())){
            // 管理员权限的科组长进入旗下教师团队的教学课程进行分配了 - 特殊处理
            leaderTeachCourseId = this.findByExamIdCourseCodeAndUserId(teachCourse.getExamId(),teachCourse.getCourseCode(),teachCourse.getCreateId()).getId();
        }

        // 所有教学班
        QueryWrapper<TeachClazz> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TeachClazz::getTeachCourseId, leaderTeachCourseId);
        if (SystemConstant.strNotNull(clazzName)) {
            queryWrapper.lambda().like(TeachClazz::getClazzName, clazzName);
        }
        List<TeachClazz> teachClazzList = teachClazzService.list(queryWrapper);

        // 该课程下所有教学班分配关系
        List<TeachClazz> distributedClazzDatasource = teachClazzService.list(
                new QueryWrapper<TeachClazz>().lambda().eq(TeachClazz::getBelongTeachCourseId, leaderTeachCourseId));

        List<ClazzDistributedResult> resultList = new ArrayList<>();
        for (TeachClazz teachClazz : teachClazzList) {
            Long basicTeachClazzId = teachClazz.getBasicTeachClazzId();
            List<DictionaryResult> teacherList = new ArrayList<>();
            List<TeachClazz> list = distributedClazzDatasource.stream().filter(e -> basicTeachClazzId.equals(e.getBasicTeachClazzId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                teacherList = sysUserService.listByIds(
                        list.stream().map(TeachClazz::getUserId).collect(Collectors.toList())).stream().flatMap(e -> {
                    DictionaryResult dictionaryResult = new DictionaryResult();
                    dictionaryResult.setId(e.getId());
                    dictionaryResult.setName(e.getRealName());
                    dictionaryResult.setCode(e.getCode());
                    return Stream.of(dictionaryResult);
                }).collect(Collectors.toList());
            }
            ClazzDistributedResult clazzDistributedResult = new ClazzDistributedResult();
            clazzDistributedResult.setClazzId(teachClazz.getBasicTeachClazzId());
            clazzDistributedResult.setClazzName(teachClazz.getClazzName());
            clazzDistributedResult.setTeacherList(teacherList);
            resultList.add(clazzDistributedResult);
        }
        return resultList;
    }

    @Transactional
    @Override
    public void assignClazz(AssignClazzParam assignClazzParam, SysUser requestUser) {
        Long requestUserId = requestUser.getId();
        Long teachCourseId = assignClazzParam.getTeachCourseId();
        Long teacherId = assignClazzParam.getTeacherId();
        List<Long> basicTeachClazzIdList = assignClazzParam.getClazzIdList();

        TeachCourse teachCourse = this.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学班不存在");
        }
        Long examId = teachCourse.getExamId();
        String courseCode = teachCourse.getCourseCode();
        if (!teachCourse.getCreateId().equals(requestUserId)) {
            throw ExceptionResultEnum.ERROR.exception("该用户没有分配教师班级的权限");
        }
        if (!teachCourse.getUserId().equals(teachCourse.getCreateId())) {
            // 管理员权限的科组长进入旗下教师团队的教学课程进行分配了 - 特殊处理
            teachCourse = this.findByExamIdCourseCodeAndUserId(examId, courseCode, teachCourse.getCreateId());
            teachCourseId = teachCourse.getId();
        }

        if (teacherId.equals(requestUserId)) {
            // 课程负责人分配自己的班级
            // 清除之前关联的班级
            UpdateWrapper<TeachClazz> clearUpdateWrapper = new UpdateWrapper<>();
            clearUpdateWrapper.lambda().set(TeachClazz::getBelongTeachCourseId, teachCourseId)
                    .set(TeachClazz::getBelongTeachCourseId, null).eq(TeachClazz::getTeachCourseId, teachCourseId);
            teachClazzService.update(clearUpdateWrapper);
            // 更新新关联班级
            UpdateWrapper<TeachClazz> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().set(TeachClazz::getBelongTeachCourseId, teachCourseId)
                    .set(TeachClazz::getUpdateId, requestUserId)
                    .set(TeachClazz::getUpdateTime, System.currentTimeMillis())
                    .set(TeachClazz::getUserId, requestUserId).eq(TeachClazz::getTeachCourseId, teachCourseId)
                    .in(TeachClazz::getBasicTeachClazzId, basicTeachClazzIdList);
            teachClazzService.update(updateWrapper);
        } else {
            // 课程负责人分配其他老师的班级
            TeachCourse teacherTeachCourse = this.findByExamIdCourseCodeAndUserId(examId, courseCode, teacherId);
            Long teacherTeachCourseId = teacherTeachCourse.getId();
            // 删除之前分配的班级数据
            teachClazzService.remove(
                    new QueryWrapper<TeachClazz>().lambda().eq(TeachClazz::getTeachCourseId, teacherTeachCourseId)
                            .eq(TeachClazz::getBelongTeachCourseId, teachCourseId));
            // 新增新班级分配数据
            for (Long clazzId : basicTeachClazzIdList) {
                TeachClazz teachClazz = new TeachClazz();
                teachClazz.setSchoolId(teachCourse.getSchoolId());
                teachClazz.setTeachCourseId(teacherTeachCourseId);
                teachClazz.setBasicTeachClazzId(clazzId);
                teachClazz.setUserId(teacherId);
                teachClazz.setClazzName(basicTeachClazzService.getById(clazzId).getClazzName());
                teachClazz.setBelongTeachCourseId(teachCourseId);
                teachClazz.insertInfo(requestUser.getId());
                teachClazzService.save(teachClazz);
            }
        }
    }

    @Override
    public List<DictionaryResult> findTeacherCourseInfo(Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if (Objects.isNull(sysUser)) {
            throw ExceptionResultEnum.ERROR.exception("用户不存在");
        }
        List<String> courseCodeList = this.list(
                new QueryWrapper<TeachCourse>().lambda().eq(TeachCourse::getUserId, userId)).stream().map(TeachCourse::getCourseCode).distinct().collect(Collectors.toList());
        return courseCodeList.stream().flatMap(e -> {
            BasicCourse basicCourse = basicCourseService.findByCourseCode(e, sysUser.getSchoolId());
            DictionaryResult dictionaryResult = new DictionaryResult();
            dictionaryResult.setCode(basicCourse.getCode());
            dictionaryResult.setName(basicCourse.getName());
            return Stream.of(dictionaryResult);
        }).collect(Collectors.toList());
    }
}
