package com.yida.data.user.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.common.ResultStatusType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.entity.school.EduSchoolStudentInformation;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.common.core.entity.system.SystemUser;
import com.yida.data.common.core.entity.system.enums.DeptTypeEnum;
import com.yida.data.common.core.entity.system.enums.RoleEnum;
import com.yida.data.common.core.entity.user.*;
import com.yida.data.common.core.entity.user.enums.UserDeptTypeEnum;
import com.yida.data.common.core.enums.RoleName;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.*;
import com.yida.data.common.core.vo.NameValueVO;
import com.yida.data.common.service.CommonService;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.system.feign.RemoteRoleService;
import com.yida.data.system.feign.RemoteUserService;
import com.yida.data.user.dto.DelFaceGroupUserDTO;
import com.yida.data.user.dto.ListStaffDTO;
import com.yida.data.user.dto.PageTeacherDTO;
import com.yida.data.user.dto.StaffExportDTO;
import com.yida.data.user.dto.StaffImportDTO;
import com.yida.data.user.dto.WelcomeStudentImportDTO;
import com.yida.data.user.excel.StaffDataExcelListener;
import com.yida.data.user.excel.WelcomeStudentDataExcelListener;
import com.yida.data.user.feign.RemoteUserDeptService;
import com.yida.data.user.mapper.EduCourseMapper;
import com.yida.data.user.mapper.EduStaffDeptMapper;
import com.yida.data.user.mapper.EduStaffMapper;
import com.yida.data.user.mapper.EduTeacherDeptMapper;
import com.yida.data.user.service.*;
import com.yida.data.user.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import java.io.InputStream;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduStaffServiceImpl extends ServiceImpl<EduStaffMapper, EduStaff> implements EduStaffService {

    private final EduTeacherDeptService eduTeacherDeptService;
    private final EduStaffDeptService eduStaffDeptService;
    private final EduUserFaceService eduUserFaceService;
    private final EduUserDeptService eduUserDeptService;
    private final EduFaceGroupUserService eduFaceGroupUserService;

    private final EduCourseMapper eduCourseMapper;
    private final EduStaffDeptMapper eduStaffDeptMapper;

    private final RemoteDeptService remoteDeptService;

    private final RemoteUserDeptService remoteUserDeptService;
    private final RemoteUserService remoteUserService;
    private final RemoteRoleService remoteRoleService;

    private final PasswordEncoder passwordEncoder;
    private final RedisService redisService;
    private final WxUtil wxUtil;
    private final WxServiceProviderUtil wxServiceProviderUtil;
    private final EduTeacherDeptMapper eduTeacherDeptMapper;

    private final CommonService commonService;

    @Override
    public IPage<TeacherListVO> listTeacherPage(PageTeacherDTO dto) {
        Page<TeacherListVO> teacherPage = dto.toPage();
        List<TeacherListVO> teacherList = baseMapper.listTeacher(teacherPage, dto);
        if (CollUtil.isNotEmpty(teacherList)) {
            // 查询系统用户
            List<SystemUser> systemUsers = null;
            List<Long> sysUserIds = new ArrayList<>();
            for (TeacherListVO teacherListVO : teacherList) {
                Long sysUserId = teacherListVO.getSysUserId();
                if (sysUserId != null) {
                    sysUserIds.add(sysUserId);
                }
            }
            if (CollUtil.isNotEmpty(sysUserIds)) {
                systemUsers = remoteUserService.listInfoById(sysUserIds.toArray(new Long[0])).getData();
            }
            for (TeacherListVO teacherDeptVO : teacherList) {
                // 教师部门信息
                for (TeacherDeptVO deptVO : teacherDeptVO.getDeptVOList()) {
                    if (deptVO.getCampusId() != null) {
                        EduUserDept campus = eduUserDeptService.getById(deptVO.getCampusId());
                        deptVO.setCampusName(campus != null ? campus.getDeptName() : deptVO.getCampusName());
                    }
                    if (deptVO.getSectionId() != null) {
                        EduUserDept section = eduUserDeptService.getById(deptVO.getSectionId());
                        deptVO.setSectionName(section != null ? section.getDeptName() : deptVO.getSectionName());
                    }
                    if (deptVO.getGradeId() != null) {
                        EduUserDept grade = eduUserDeptService.getById(deptVO.getGradeId());
                        deptVO.setGradeName(grade != null ? grade.getDeptName() : deptVO.getGradeName());
                    }
                    if (CollUtil.isNotEmpty(deptVO.getClassList())) {
                        for (TeacherClassVO classVO : deptVO.getClassList()) {
                            EduUserDept clazz = eduUserDeptService.getById(classVO.getClassId());
                            classVO.setClassName(clazz != null ? clazz.getDeptName() : classVO.getClassName());
                            EduUserDept campus = eduUserDeptService.getById(deptVO.getCampusId());
                            deptVO.setCampusName(campus != null ? campus.getDeptName() : deptVO.getCampusName());
                        }
                        if (deptVO.getSectionId() != null) {
                            EduUserDept section = eduUserDeptService.getById(deptVO.getSectionId());
                            deptVO.setSectionName(section != null ? section.getDeptName() : deptVO.getSectionName());
                        }
                        if (deptVO.getGradeId() != null) {
                            EduUserDept grade = eduUserDeptService.getById(deptVO.getGradeId());
                            deptVO.setGradeName(grade != null ? grade.getDeptName() : deptVO.getGradeName());
                        }
                        if (CollUtil.isNotEmpty(deptVO.getClassList())) {
                            for (TeacherClassVO classVO : deptVO.getClassList()) {
                                EduUserDept clazz = eduUserDeptService.getById(classVO.getClassId());
                                classVO.setClassName(clazz != null ? clazz.getDeptName() : classVO.getClassName());
                            }
                        }
                    }
                    // 填充系统账号状态
                    if (CollUtil.isNotEmpty(systemUsers)) {
                        for (SystemUser systemUser : systemUsers) {
                            if (ObjectUtil.equal(teacherDeptVO.getSysUserId(), systemUser.getUserId())) {
                                teacherDeptVO.setStatus(Integer.valueOf(systemUser.getStatus()));
                            }
                        }
                    }
                }
            }
        }
        teacherPage.setRecords(teacherList);
        return teacherPage;
    }

    @Override
    public int checkTeacherTelephone(EduStaff eduStaff) {
        return baseMapper.checkTeacherTelephone(eduStaff);
    }


    @Override
    @GlobalTransactional
    public void saveTeacher(Integer operation, EduStaff eduStaff) {
        List<EduTeacherDept> existDeptList = eduTeacherDeptService.list(
            Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, eduStaff.getId()));
        if (operation == 0) {
            Asserts.isTrue(CollUtil.isEmpty(existDeptList), "该教师已存在");
        }
        List<EduTeacherDept> teacherDeptList = eduStaff.getTeacherDept();
        EduStaff staff = getById(eduStaff.getId());
        Dept school = commonService.getDept(staff.getSchoolId());
        // 绑定了微信
        String accessToken = null;
        // 明文userId
        // 当代开发情况下，此处的职工(教师id)需要转换成明文才能调用
        String plainUserId = null;
        EduApp appSelect = commonService.getAppContactUsedBySelect(staff.getSchoolId());

        if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SCHOOL, null, staff.getSchoolId());
            accessToken = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());
            if (CollUtil.isNotEmpty(existDeptList)) {
                for (EduTeacherDept eduTeacherDept : existDeptList) {
                    Long deptId = null;
                    switch (eduTeacherDept.getType()) {
                        case 1:
                            deptId = eduTeacherDept.getCampusId();
                            break;
                        case 2:
                            deptId = eduTeacherDept.getGradeId();
                            break;
                        case 3:
                        case 4:
                            deptId = eduTeacherDept.getClassId();
                            break;
                        case 5:
                            deptId = eduTeacherDept.getSectionId();
                            break;
                        default:
                            break;
                    }
                    if (deptId != null) {
                        EduUserDept userDept = eduUserDeptService.getById(deptId);
                        if (Objects.nonNull(userDept)) {
                            // 删除企业微信已有关联部门数据
                            eduTeacherDept.setDeptWxId(userDept.getWxId());
                            plainUserId = commonService.getPlainUserId(staff.getWxId(), school.getDeptId(), appSelect);
                            eduTeacherDept.setTeacherWxId(plainUserId);
                            wxUtil.deleteSchoolDeptUser(accessToken, eduTeacherDept);
                        }
                    }
                }
            }
        }
        // 删除教师部门关联关系
        eduTeacherDeptService.remove(Wrappers.<EduTeacherDept>lambdaQuery().eq(EduTeacherDept::getTeacherId, staff.getId()));
        // 添加新的对应关系
        List<String> roleNames = new ArrayList<>();
        roleNames.add(RoleName.TEACHER.getName());
        roleNames.add(RoleName.STAFF.getName());
        if (CollUtil.isNotEmpty(teacherDeptList)) {
            for (EduTeacherDept teacherDept : teacherDeptList) {
                if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
                    Long deptId = null;
                    switch (teacherDept.getType()) {
                        case 1:
                            deptId = teacherDept.getCampusId();
                            roleNames.add(RoleName.CAMPUS.getName());
                            break;
                        case 2:
                            deptId = teacherDept.getGradeId();
                            roleNames.add(RoleName.GRADE.getName());
                            break;
                        case 3:
                            roleNames.add(RoleName.MASTER.getName());
                        case 4:
                            deptId = teacherDept.getClassId();
                            roleNames.add(RoleName.COURSE.getName());
                            break;
                        case 5:
                            deptId = teacherDept.getSectionId();
                            roleNames.add(RoleName.SECTION.getName());
                            break;
                        default:
                            break;
                    }
                    teacherDept.setDeptWxId(eduUserDeptService.getById(deptId).getWxId());
                    if (StringUtils.isEmpty(plainUserId)) {
                        plainUserId = commonService.getPlainUserId(staff.getWxId(), school.getDeptId(), appSelect);
                    }
                    teacherDept.setTeacherWxId(plainUserId);
                    wxUtil.updateUserDeptTeacherInfo(accessToken, teacherDept);
                }
                teacherDept.setTeacherId(staff.getId());
                teacherDept.setSchoolId(staff.getSchoolId());
                //todo 添加对应角色
            }
            eduTeacherDeptService.saveBatch(teacherDeptList);
        }
        remoteUserService.updateUserRoleByRoleName(staff.getSysUserId(), roleNames);
    }

    @Override
    public TeacherDetailVO findTeacher(Long teacherId) {
        TeacherDetailVO vo = baseMapper.getTeacherById(teacherId);
        if (vo != null) {
            vo.setMenu(remoteRoleService.listMenuByRoleName(vo.getType().stream().map(x -> {
                String s = null;
                switch (x) {
                    case 1:
                        s = "校区负责人";
                        break;
                    case 2:
                        s = "年级负责人";
                        break;
                    case 3:
                        s = "班主任";
                        break;
                    case 4:
                        s = "任课老师";
                        break;
                    case 5:
                        s = "学段负责人";
                        break;
                }
                return s;
            }).toArray(String[]::new)).getData());
        }
        return vo;
    }

    @Override
    public List<TeacherClassVO> listClassByTeacher(Long teacherId) {

        return baseMapper.listClassByTeacher(teacherId);
    }

    @Override
    public List<TeacherClassVO> listDeptByTeacher(Long teacherId, Integer type) {
        List<TeacherClassVO> teacherClassVOS = new ArrayList<>();
        List<TeacherDeptVO> teacherDeptVOS = baseMapper.listDeptByTeacher(teacherId, type);
        for (TeacherDeptVO dept : teacherDeptVOS) {
            TeacherClassVO teacherClassVO = new TeacherClassVO();
            teacherClassVO.setType(dept.getType());
            Long deptId = null;
            if (dept.getType() == 1) {
                //校区
                deptId = dept.getCampusId();
            } else if (dept.getType() == 2) {
                deptId = dept.getGradeId();
            } else if (dept.getType() == 3) {
                deptId = dept.getClassId();
            } else if (dept.getType() == 5) {
                deptId = dept.getSectionId();
            }
            EduUserDept eduUserDept = remoteUserDeptService.getByDeptId(deptId).getData();
            teacherClassVO.setDeptId(eduUserDept.getDeptId());
            teacherClassVO.setDeptName(eduUserDept.getDeptName());
            teacherClassVOS.add(teacherClassVO);
        }
        return teacherClassVOS;
    }

    @Override
    public List<Long> listClassIdByStaffId() {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        List<Long> resultList = new ArrayList<>();
        List<Long> parentIdList = new ArrayList<>();
        //根据sysUserId查询staffId
        EduStaff staff = this.getOne(Wrappers.lambdaQuery(new EduStaff())
            .eq(EduStaff::getSchoolId, FebsUtil.getTopDeptId())
            .eq(EduStaff::getSysUserId, currentUser.getUserId()));

        //任课老师
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_TEACHER.getValue())) {
            resultList.addAll(
                baseMapper.listDeptByTeacher(staff.getId(), 4).stream().map(TeacherDeptVO::getClassId)
                    .collect(Collectors.toList()));
        }
        //班主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_CLASS_PRINCIPAL.getValue())) {
            resultList.addAll(
                baseMapper.listDeptByTeacher(staff.getId(), 3).stream().map(TeacherDeptVO::getClassId)
                    .collect(Collectors.toList()));
        }
        //年级主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_GRADE_PRINCIPAL.getValue())) {
            List<Long> gradeIdList = baseMapper.listDeptByTeacher(staff.getId(), 2).stream()
                .map(TeacherDeptVO::getGradeId)
                .collect(Collectors.toList());
            parentIdList.addAll(gradeIdList);
        }
        //学段主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_SECTION_PRINCIPAL.getValue())) {
            List<Long> sectionIdList = baseMapper.listDeptByTeacher(staff.getId(), 5).stream()
                .map(TeacherDeptVO::getSectionId)
                .collect(Collectors.toList());
            parentIdList.addAll(sectionIdList);

        }
        //学区主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_CAMPUS_PRINCIPAL.getValue())) {
            List<Long> campusIdList = baseMapper.listDeptByTeacher(staff.getId(), 1).stream()
                .map(TeacherDeptVO::getCampusId)
                .collect(Collectors.toList());
            parentIdList.addAll(campusIdList);
        }

        List<EduUserDept> resultDeptList = new ArrayList<>();
        if (CollUtil.isNotEmpty(parentIdList)) {
            List<EduUserDept> childIdByParentAndType = eduUserDeptService
                .findChildIdByParentAndType(parentIdList, 1, resultDeptList);
            resultList.addAll(childIdByParentAndType.stream().map(EduUserDept::getDeptId).collect(Collectors.toList()));
        }
        return resultList;
    }

    @Override
    public List<Integer> listStaffRolesByStaffId(Long staffId) {
        return eduTeacherDeptMapper.findType(staffId);
    }

    @Override
    public List<TeacherDeptVO> listDeptByStaffId(Long staffId) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        List<TeacherDeptVO> resultList = new ArrayList<>();
        //班主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_CLASS_PRINCIPAL.getValue())) {
            List<TeacherDeptVO> classList = baseMapper.listDeptByTeacher(staffId, 3);
            resultList.addAll(classList);
        }
        //年级主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_GRADE_PRINCIPAL.getValue())) {
            List<TeacherDeptVO> gradeList = baseMapper.listDeptByTeacher(staffId, 2);
            resultList.addAll(gradeList);
        }
        //学段主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_SECTION_PRINCIPAL.getValue())) {
            List<TeacherDeptVO> sectionList = baseMapper.listDeptByTeacher(staffId, 5);
            resultList.addAll(sectionList);
        }
        //学区主任
        if (currentUser.getRolePerms().contains(RoleEnum.ROLE_CAMPUS_PRINCIPAL.getValue())) {
            List<TeacherDeptVO> campusList = baseMapper.listDeptByTeacher(staffId, 1);
            resultList.addAll(campusList);
        }
//        List<TeacherClassVO> teacherClassVOS = new ArrayList<>();
//        List<TeacherDeptVO> teacherDeptVOS = baseMapper.listDeptByTeacher(staffId, type);

        resultList.forEach(teacherDeptVO -> {
            Integer type = teacherDeptVO.getType();
            switch (type) {
                case 1:
                    EduUserDept campus = remoteUserDeptService.getByDeptId(teacherDeptVO.getCampusId()).getData();
                    teacherDeptVO.setCampusName(campus.getDeptName());
                    break;
                case 2:
                    EduUserDept campus_g = remoteUserDeptService.getByDeptId(teacherDeptVO.getCampusId()).getData();
                    teacherDeptVO.setCampusName(campus_g.getDeptName());
                    EduUserDept grade = remoteUserDeptService.getByDeptId(teacherDeptVO.getGradeId()).getData();
                    teacherDeptVO.setGradeName(grade.getDeptName());
                    break;
                case 3:
                    EduUserDept campus_c = remoteUserDeptService.getByDeptId(teacherDeptVO.getCampusId()).getData();
                    teacherDeptVO.setCampusName(campus_c.getDeptName());
                    EduUserDept grade_c = remoteUserDeptService.getByDeptId(teacherDeptVO.getGradeId()).getData();
                    teacherDeptVO.setGradeName(grade_c.getDeptName());
                    EduUserDept clazz = remoteUserDeptService.getByDeptId(teacherDeptVO.getClassId()).getData();
                    teacherDeptVO.setClassName(clazz.getDeptName());
                    break;
                case 5:
                    EduUserDept campus_s = remoteUserDeptService.getByDeptId(teacherDeptVO.getCampusId()).getData();
                    teacherDeptVO.setCampusName(campus_s.getDeptName());

//                    EduUserDept campus_s = remoteUserDeptService.getByDeptId(teacherDeptVO.getCampusId()).getData();
//                    teacherDeptVO.setCampusName(campus_s.getDeptName());

            }
        });

        for (TeacherDeptVO dept : resultList) {
//            TeacherClassVO teacherClassVO = new TeacherClassVO();
//            teacherClassVO.setType(dept.getType());
            Long deptId = null;
            if (dept.getType() == 1) {
                //校区
                deptId = dept.getCampusId();
            } else if (dept.getType() == 2) {
                deptId = dept.getGradeId();
            } else if (dept.getType() == 3) {
                deptId = dept.getClassId();
            } else if (dept.getType() == 5) {
                deptId = dept.getSectionId();
            }
//            EduUserDept eduUserDept = remoteUserDeptService.getByDeptId(deptId).getData();
//            teacherClassVO.setDeptId(eduUserDept.getDeptId());
//            teacherClassVO.setDeptName(eduUserDept.getDeptName());
//            teacherClassVOS.add(teacherClassVO);
        }
        return null;
    }

    @Override
    public void delStaffBatch(List<Long> staffIds) {
        List<EduStaff> staffList = list(Wrappers.lambdaQuery(new EduStaff()).in(EduStaff::getId, staffIds));

        // 删除人脸相关信息
        List<EduFaceGroupUser> faceList =
            eduFaceGroupUserService.list(Wrappers.<EduFaceGroupUser>lambdaQuery()
                .eq(EduFaceGroupUser::getUserType, 1)
                .in(EduFaceGroupUser::getUserId, staffIds));
        if (CollUtil.isNotEmpty(faceList)) {
//            eduFaceGroupUserService.delUserBatch(DelFaceGroupUserDTO.builder()
//                .faceIds(faceList.stream().map(EduFaceGroupUser::getId).collect(Collectors.toList())).build());
            // 分组处理数据
            Map<Long, List<EduFaceGroupUser>> faceGroupMap = faceList.stream().collect(
                Collectors.groupingBy(EduFaceGroupUser::getFaceGroupId));
            faceGroupMap.forEach((faceGroupId, userList) ->
                eduFaceGroupUserService.delUserBatch(DelFaceGroupUserDTO.builder()
                    .faceGroupId(faceGroupId)
                    .faceIds(userList.stream().map(EduFaceGroupUser::getId).collect(Collectors.toList()))
                    .build())
            );
        }

        removeByIds(staffIds);
        eduTeacherDeptService.remove(Wrappers.lambdaQuery(new EduTeacherDept()).in(EduTeacherDept::getTeacherId, staffIds));
        eduStaffDeptMapper.delete(Wrappers.lambdaQuery(new EduStaffDept()).in(EduStaffDept::getStaffId, staffIds));
        Long schoolId = staffList.get(0).getSchoolId();
        // 学校绑定类型
        Dept school = commonService.getDept(schoolId);
        boolean containsWx = school.getSchoolType().contains(Dept.TYPE_QYWX);
        boolean containsYida = school.getSchoolType().contains(Dept.TYPE_YIDA_APP);
//        boolean containsDahua = school.getSchoolType().contains(Dept.TYPE_DAHUA);
        // 绑定了微信
        if (containsWx) {
            List<String> staffWxIdList = staffList.stream().filter(x -> StrUtil.isNotBlank(x.getWxId()) && x.getWxPath() == 0)
                .map(EduStaff::getWxId)
                .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(staffWxIdList)) {
                String wxAccessToken = commonService.getAddressListToken(schoolId);
                wxUtil.deleteUser(wxAccessToken, staffWxIdList);
            }
        }
        // 绑定了易达app
        if (containsYida) {
            EduYidaApp yidaApp = commonService.getYidaApp(schoolId);
            EduYidaAppAccount yidaAppAccount = commonService.getYidaAppAccount(schoolId, 1);
            staffList.stream().map(EduStaff::getYidaAppUserId).filter(StrUtil::isNotBlank)
                .forEach(x -> AppUtil.subscribeUnFollow(yidaAppAccount.getYidaAppAccountId(), x, yidaApp));
        }
//        // 绑定了大华
//        if (containsDahua) {
//            DaHuaUtil.delUser(staffList.stream().map(x -> x.getDahuaId().toString()).collect(Collectors.joining(",")));
//        }
    }

    @Override
    @GlobalTransactional
    public void delTeacherBatch(List<Long> teacherIds) {
        Long schoolId = getById(teacherIds.get(0)).getSchoolId();
        Dept school = commonService.getDept(schoolId);
        List<EduTeacherDept> teacherDepts = eduTeacherDeptService.listTeacherDept(teacherIds);
        eduTeacherDeptService.remove(Wrappers.lambdaQuery(new EduTeacherDept()).in(EduTeacherDept::getTeacherId, teacherIds));
        for (EduStaff teacher : listByIds(teacherIds)) {
            remoteUserService.updateUserRoleByRoleName(teacher.getSysUserId(),
                Collections.singletonList(RoleName.STAFF.getName()));
        }

        if (school.getSchoolType().contains(Dept.TYPE_QYWX) && CollUtil.isNotEmpty(teacherDepts)) {
            log.info("处理企业微信删除教师信息");
            EduApp appSelect = commonService.getAppContactUsedBySelect(school.getDeptId());
            // TODO: 2021/10/28 删除学校部门与教师关联信息
            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SCHOOL, null, schoolId);
            String accessToken = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());
            for (EduTeacherDept teacherDept : teacherDepts) {
                Long deptId = null;
                switch (teacherDept.getType()) {
                    case 1:
                        deptId = teacherDept.getCampusId();
                        break;
                    case 2:
                        deptId = teacherDept.getGradeId();
                        break;
                    case 3:
                    case 4:
                        deptId = teacherDept.getClassId();
                        break;
                    case 5:
                        deptId = teacherDept.getSectionId();
                        break;
                    default:
                        break;
                }
                String plainUserId = commonService.getPlainUserId(teacherDept.getTeacherWxId(), school.getDeptId(), appSelect);
                teacherDept.setTeacherWxId(plainUserId);

                EduUserDept userDept = eduUserDeptService.getById(deptId);
                teacherDept.setDeptWxId(userDept.getWxId());
                wxUtil.deleteSchoolDeptUser(accessToken, teacherDept);
            }
        }

        log.info("处理完成");
    }

    @Override
    public void dealWxTeacherChange(Long schoolId, Long campusId, Long sectionId, Long gradeId, Long classId,
        List<Map> teacherList, Long deptWxId) {
        // 删除部门关联信息
        if (CollUtil.isNotEmpty(teacherList)) {
            LambdaQueryWrapper<EduTeacherDept> delTeacherDeptCondition = Wrappers.lambdaQuery(new EduTeacherDept());
            // 删除单个部门负责人
            if (classId != null) {
                delTeacherDeptCondition.eq(EduTeacherDept::getClassId, classId);
            } else if (gradeId != null) {
                delTeacherDeptCondition.eq(EduTeacherDept::getGradeId, gradeId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getClassId);
            } else if (sectionId != null) {
                delTeacherDeptCondition.eq(EduTeacherDept::getSectionId, sectionId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getGradeId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getClassId);
            } else if (campusId != null) {
                delTeacherDeptCondition.eq(EduTeacherDept::getCampusId, campusId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getSectionId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getGradeId);
                delTeacherDeptCondition.isNull(EduTeacherDept::getClassId);
            } else {
                // 未满足条件不删除关联关系
                delTeacherDeptCondition.eq(EduTeacherDept::getSchoolId, -1L);
            }

            eduTeacherDeptService.remove(delTeacherDeptCondition);
            List<EduTeacherDept> eduTeacherDeptList = new ArrayList<>();
            for (Map teacher : teacherList) {
                try {
                    EduTeacherDept eduTeacherDept = new EduTeacherDept();
                    eduTeacherDept.setSchoolId(schoolId);
                    eduTeacherDept.setCampusId(campusId);
                    eduTeacherDept.setSectionId(sectionId);
                    eduTeacherDept.setGradeId(gradeId);
                    eduTeacherDept.setClassId(classId);

                    String teacherWxId = (String) teacher.get("userid");
                    // 根据通讯录应用情况获取对应用户密文id
                    teacherWxId = commonService.getSecretUserId(teacherWxId, schoolId);
                    int teacherType = Integer.parseInt(teacher.get("type").toString());
                    String subject = ObjectUtil.toString(teacher.get("subject"));

                    EduStaff teacherInfo = getOne(
                        Wrappers.lambdaQuery(new EduStaff()).eq(EduStaff::getWxId, teacherWxId)
                            .eq(EduStaff::getSchoolId, schoolId));
                    if (teacherInfo == null) {
                        continue;
                    }
                    eduTeacherDept.setTeacherId(teacherInfo.getId());
                    // 教师类型
                    switch (teacherType) {
                        case 1:
                            eduTeacherDept.setType(1);
                            remoteUserService.bindRoleByUser(teacherInfo.getSysUserId(), "校区负责人");
                            break;
                        case 2:
                            eduTeacherDept.setType(2);
                            remoteUserService.bindRoleByUser(teacherInfo.getSysUserId(), "年级负责人");
                            break;
                        case 3:
                            remoteUserService.bindRoleByUser(teacherInfo.getSysUserId(), "班主任");
                            eduTeacherDept.setType(3);
                            break;
                        case 4:
                            remoteUserService.bindRoleByUser(teacherInfo.getSysUserId(), "任课老师");
                            eduTeacherDept.setType(4);
                            break;
                        case 5:
                            remoteUserService.bindRoleByUser(teacherInfo.getSysUserId(), "学段负责人");
                            eduTeacherDept.setType(5);
                            break;
                        default:
                            break;
                    }
                    // 填充部门信息
                    if (StrUtil.isNotBlank(subject) && !"null".equals(subject)) {
                        // 科目信息
                        EduCourse course = eduCourseMapper.selectOne(
                            Wrappers.lambdaQuery(new EduCourse()).eq(EduCourse::getSchoolId, schoolId)
                                .eq(EduCourse::getCourseName, subject));
                        if (course == null) {
                            course = new EduCourse();
                            course.setCourseName(subject);
                            course.setSchoolId(schoolId);
                            eduCourseMapper.insert(course);
                        }
                        eduTeacherDept.setCourseId(course.getId());
                    }
                    eduTeacherDeptList.add(eduTeacherDept);
                } catch (Exception e) {
                    log.error("处理家校沟通教师数据失败: schoolId:{}, campusId: {}, sectionId:{}, gradeId:{}, classId:{}, teacher:{}",
                        schoolId, campusId, sectionId, gradeId, classId, teacher, e);
                }
            }
            eduTeacherDeptService.saveBatch(eduTeacherDeptList);
        }
    }

    @Override
    @GlobalTransactional
    public void initStaff(List<EduStaff> staffList) {
        Dept school = commonService.getDept(staffList.get(0).getSchoolId());
        saveBatch(staffList);
        List<EduStaffDept> staffDeptList = new ArrayList<>();
        for (EduStaff staff : staffList) {
            if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
                String cardNum = DaHuaUtil.generateCardNum();
                staff.setDahuaCode(staff.getMobile());
                staff.setDahuaId(
                    DaHuaUtil.addUser(staff.getName(), staff.getDahuaCode(), 1, 1, cardNum, null, null, null, null, null, ""));
            }
            List<EduStaffDept> eduStaffDeptList = staff.getStaffDept();
            if (CollUtil.isNotEmpty(eduStaffDeptList)) {
                staffDeptList.addAll(eduStaffDeptList.stream().map(x -> {
                    x.setStaffId(staff.getId());
                    return x;
                }).collect(Collectors.toList()));
            }
        }
        if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
            updateBatchById(staffList);
        }
        eduStaffDeptService.saveBatch(staffDeptList);
    }

    @Override
    public ResultBean<ConcurrentHashMap<Integer, Object>> importStaff(MultipartFile file, Long schoolId, long timestamp) {
        // 验证文件类型
        if (!FileUtil.checkMultipartFile(file, FebsConstant.EXCEL_FILE_TYPE)) {
            return ResultBean.buildError(ResultMsgType.FILE_TYPE_ERROR.getValue());
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 调用导入方法
        ConcurrentHashMap<Integer, Object> errorMap = new ConcurrentHashMap<>(16);
        try {
            EasyExcel.read(file.getInputStream(), StaffImportDTO.class,
                new StaffDataExcelListener(this, errorMap, schoolId, timestamp))
                .sheet().headRowNumber(8).doRead();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        stopWatch.stop();
        log.info("导入职工数据总共耗时: {}", stopWatch.getTotalTimeSeconds() + "秒");
        // 判断是否有错误数据
        if (errorMap.size() > 0) {
            return ResultBean
                .buildError(ResultStatusType.IMPORT_FAIL.getValue(), ResultMsgType.IMPORT_EXCEL_FAIL.getValue(), errorMap);
        }
        return ResultBean.buildSuccess(ResultMsgType.IMPORT_EXCEL_SUCCESS.getValue(), null);
    }

//    @Override
//    public void importStaff(String path, Long schoolId, CurrentUser currentUser, Long key, String fileName) {
//
//
//
////        try {
////            Dept school = commonService.getDept(schoolId);
////            // 解压文件到本地
////            File zipFile = new File(path);
////            String zipPath = ZipUtil.unzip(zipFile, CharsetUtil.CHARSET_GBK).getAbsolutePath();
////            Map<String, Dept> cacheDept = new HashMap<>();
////            // 循环拿到数据
////            List<File> face = FileUtil.loopFiles(zipPath, x -> {
////                String suffix = FileUtil.getSuffix(x);
////                return (!"txt".equals(suffix)) && (!"xlsx".equals(suffix));
////            });
////            List<File> excel = FileUtil.loopFiles(zipPath, x -> {
////                String suffix = FileUtil.getSuffix(x);
////                return "xlsx".equals(suffix);
////            });
////            int count = 0;
////            int complete = 0;
////            int percent = 0;
////
////            String token = commonService.getAddressListToken(schoolId);
////
////            for (File file : excel) {
////                Workbook workbook;
////                try {
////                    workbook = com.yida.data.common.core.utils.ExcelUtil.readExcel(file, "xlsx");
////                } catch (IOException e) {
////                    e.printStackTrace();
////                    throw new FebsException("读取职工名单失败,请重新上传");
////                }
////                Sheet campusSheet = workbook.getSheetAt(0);
////                List<Map<Integer, Cell>> staffList = ExcelUtil.readData(campusSheet, 9);
//////                Role staffRole = remoteRoleService.getRoleByNameNoPermission("职工").getData();
////                count = face.size() + staffList.size();
////                List<Map<String, Object>> errorData = new ArrayList<>();
////                for (int i = 0; i < staffList.size(); i++) {
////                    Map<Integer, Cell> staff = staffList.get(i);
////                    String name = ExcelUtil.getCellValue(staff.get(1));
////                    if (StrUtil.isBlankIfStr(name)) {
////                        continue;
////                    }
////                    //别名
////                    String alias = ExcelUtil.getCellValue(staff.get(2));
////                    //性别
////                    String sex = ExcelUtil.getCellValue(staff.get(3));
////                    //联系电话
////                    String phone = ExcelUtil.getCellValue(staff.get(4));
////                    //座机
////                    String landLine = ExcelUtil.getCellValue(staff.get(5));
////                    //邮箱
////                    String email = ExcelUtil.getCellValue(staff.get(6));
////                    //地址
////                    String addr = ExcelUtil.getCellValue(staff.get(7));
////                    //部门名称
////                    String deptName = ExcelUtil.getCellValue(staff.get(8));
////                    //是否是上级
////                    String identity = ExcelUtil.getCellValue(staff.get(9));
////                    //职务
////                    String position = ExcelUtil.getCellValue(staff.get(10));
////                    //？？
////                    String companyAbbre = ExcelUtil.getCellValue(staff.get(11));
////                    //？？
////                    String foreignPosition = ExcelUtil.getCellValue(staff.get(12));
////                    //是否同步到企业微信
////                    String wxPath = ExcelUtil.getCellValue(staff.get(13));
////
////                    try {
////                        EduStaff eduStaff = new EduStaff();
////                        //职工已存在跳过
////                        EduStaff existStaff = getOne(Wrappers.lambdaQuery(new EduStaff()).eq(EduStaff::getMobile, phone)
////                            .eq(EduStaff::getSchoolId, schoolId));
////                        if (existStaff != null) {
////                            eduStaff = existStaff;
////                        } else {
////                            Dept dept = cacheDept.containsKey(deptName) ? cacheDept.get(deptName)
////                                : remoteDeptService.getDeptBySchoolAndName(schoolId, deptName).getData();
////                            cacheDept.put(deptName, dept);
////                            eduStaff.setName(name);
////                            eduStaff.setSex("男".equals(sex) ? "0" : "女".equals(sex) ? "1" : "2");
////                            eduStaff.setMobile(phone);
////                            eduStaff.setSchoolId(school.getDeptId());
////                            eduStaff.setSchoolName(school.getDeptName());
////
////                            eduStaff.setAlias(alias);
////                            eduStaff.setLandLine(landLine);
////                            eduStaff.setEmail(email);
////                            eduStaff.setAddress(addr);
////                            eduStaff.setPosition(position);
////                            eduStaff.setIsLeader("上级".equals(identity) ? 1 : 0);
////                            eduStaff.setCompanyAbbre(companyAbbre);
////                            eduStaff.setForeignPosition(foreignPosition);
////                            eduStaff.setWxPath(Integer.parseInt(wxPath));
////
////                            eduStaff.setWxId(StrUtil.isNotBlank(phone) ? phone : StrUtil.uuid().replace("-", ""));
////                            save(eduStaff);
////
////                            EduStaffDept staffDept = new EduStaffDept();
////                            staffDept.setStaffId(eduStaff.getId());
////                            staffDept.setStaffName(eduStaff.getName());
////                            staffDept.setDeptId(dept.getDeptId());
////                            staffDept.setDeptName(dept.getDeptName());
////                            staffDept.setDeptWxId(dept.getWxId());
////                            staffDept.setIsLeader("下级".equals(identity) ? 1 : 0);
////                            staffDept.setIsMain(1);
////                            eduStaffDeptService.save(staffDept);
////
////                            eduStaff.setStaffDept(Collections.singletonList(staffDept));
////                            // 微信教师信息新增
////                            if ("0".equals(wxPath)) {
////                                wxUtil.createUser(token, eduStaff);
////                            }
////                            //添加系统账号
////                            saveSystemUser(eduStaff);
////                            updateById(eduStaff);
////                        }
////                    } catch (Exception e) {
////                        errorData.add(new HashMap<String, Object>() {{
////                            put("name", name);
////                            put("alias", alias);
////                            put("wxId", phone);
////                            put("sex", sex);
////                            put("phone", phone);
////                            put("landLine", landLine);
////                            put("email", email);
////                            put("addr", addr);
////                            put("deptName", deptName);
////                            put("identity", identity);
////                            put("position", position);
////                            put("companyAbbre", companyAbbre);
////                            put("foreignPosition", foreignPosition);
////                        }});
////                    }
////
////                    complete++;
////                    if (complete / count != percent) {
////                        percent = complete / count;
////                        redisService.hset(CachePrefixConstant.IMPORT_STAFF_KEY + currentUser.getUsername(), key.toString(),
////                            percent);
////                    }
////                }
////                // 新增通知
////                Long noticeId = null;
////
////                //EduNoticeSystem eduNoticeSystem = new EduNoticeSystem();
////                //eduNoticeSystem.setContent("文档" + file.getName() + "已经上传完成,共上传" + staffList.size() + "条数据,其中错误" + errorData.size() + "条。");
////                //noticeId = eduNoticeSystemService.insertNotice(eduNoticeSystem);
////                //
////                //EduNoticeSystemUser eduNoticeSystemUser = new EduNoticeSystemUser();
////                //eduNoticeSystemUser.setNoticeId(noticeId);
////                //eduNoticeSystemUser.setUserId(currentUser.getUserId());
////                //if (CollUtil.isNotEmpty(errorData)) {
////                //    redisService.set(CachePrefixConstant.IMPORT_ERROR + noticeId.toString(), JSONUtil.toJsonStr(errorData), 3600L);
////                //}
////            }
////
////            // 保存人脸
////            for (File pic : face) {
////                String name = FileUtil.getName(pic);
////                String mobile = name.split("\\.")[0];
////                EduStaff staff = getOne(Wrappers.lambdaQuery(new EduStaff()).eq(EduStaff::getSchoolId, school.getDeptId())
////                    .eq(EduStaff::getMobile, mobile));
////                if (staff != null) {
////                    eduUserFaceService.uploadImage(pic, staff.getId(), staff.getName(), 1);
////                }
////                complete++;
////                if (complete / count != percent) {
////                    percent = complete / count;
////                    redisService.hset(CachePrefixConstant.IMPORT_STAFF_KEY + currentUser.getUsername(), key.toString(), percent);
////                }
////            }
////        } finally {
////            redisService.hdel(CachePrefixConstant.IMPORT_STAFF_KEY + currentUser.getUsername(), key.toString());
////            redisService.hdel(CachePrefixConstant.IMPORT_STAFF_FILE + currentUser.getUsername(), key.toString());
////        }
//    }

    @Override
    public Integer importTeacherHeartbeat(String username, Long key) {
        Object value = redisService.hget(CachePrefixConstant.IMPORT_TEACHER_KEY + username, key.toString());
        if (value != null) {
            return Integer.valueOf(value.toString());
        }
        return 100;
    }

    @Override
    public Integer importStaffHeartbeat(String username, Long key) {
        Object value = redisService.hget(CachePrefixConstant.IMPORT_STAFF_KEY + username, key.toString());
        if (value != null) {
            return Integer.valueOf(value.toString());
        }
        return 100;
    }

    @Override
    public List<Map<String, String>> listImportKey(String username, Integer type) {
        List<Map<String, String>> list = new ArrayList<>();
        Map<Object, Object> keyList = redisService.hmget(
            (type == 0 ? CachePrefixConstant.IMPORT_TEACHER_KEY : CachePrefixConstant.IMPORT_STAFF_KEY) + username);
        if (CollUtil.isNotEmpty(keyList)) {
            for (Map.Entry<Object, Object> objectEntry : keyList.entrySet()) {
                Map<String, String> res = new HashMap<>();
                Object key = objectEntry.getKey();
                Object value = objectEntry.getValue();
                Object filename = redisService.hget(
                    (type == 0 ? CachePrefixConstant.IMPORT_TEACHER_FILE : CachePrefixConstant.IMPORT_STAFF_FILE) + username,
                    key.toString());
                if (filename != null && StrUtil.isNotBlank(filename.toString())) {
                    res.put("percent", value.toString());
                    res.put("filename", filename.toString());
                    res.put("key", key.toString());
                    list.add(res);
                }
            }

        }
        return list;
    }

    //添加系统账号
    @Override
    public SystemUser saveSystemUser(EduStaff eduStaff) {
        SystemUser systemUser = remoteUserService.getInfoByUsernameNoPermission(eduStaff.getMobile()).getData();
        if (systemUser == null) {
            systemUser = new SystemUser();
            systemUser.setNickname(eduStaff.getName());
            systemUser.setSex(eduStaff.getSex());
            systemUser.setUsername(eduStaff.getMobile());
            systemUser.setMobile(eduStaff.getMobile());
            systemUser.setDeptId(eduStaff.getSchoolId());
//            systemUser.setRoleId(role.getRoleId().toString());
            systemUser.setRoleName(RoleName.STAFF.getName());
//            systemUser.setStatus("0");
//            systemUser.setUserType(1);
            systemUser = remoteUserService.addUser(systemUser).getData();
//            eduStaff.setYidaAppUserId(systemUser.getYidaAppUserId());
        }
        eduStaff.setSysUserId(systemUser.getUserId());
        updateById(eduStaff);
        return systemUser;
    }

    @Override
    public void saveStaffBySchoolAndWx(EduStaff staff) {
        EduStaff exist = getOne(Wrappers.lambdaQuery(new EduStaff()).eq(EduStaff::getSchoolId, staff.getSchoolId())
            .eq(EduStaff::getWxId, staff.getWxId()));
        if (exist != null) {
            staff.setId(exist.getId());
            eduStaffDeptService.remove(Wrappers.lambdaQuery(new EduStaffDept()).eq(EduStaffDept::getStaffId, staff.getId()));
        }
        saveOrUpdate(staff);
        if (CollUtil.isNotEmpty(staff.getStaffDept())) {
            for (EduStaffDept staffDept : staff.getStaffDept()) {
                staffDept.setStaffId(staff.getId());
            }
            eduStaffDeptService.saveBatch(staff.getStaffDept());
        }
    }

    @Override
    public void dealWxUserDelete(String wxId, Long schoolId) {
        EduStaff staff = getOne(
            Wrappers.lambdaQuery(new EduStaff()).eq(EduStaff::getWxId, wxId).eq(EduStaff::getSchoolId, schoolId));
        if (staff != null) {
            eduTeacherDeptService.remove(
                Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, staff.getId()));
            eduStaffDeptService.remove(Wrappers.lambdaQuery(new EduStaffDept()).eq(EduStaffDept::getStaffId, staff.getId()));
            removeById(staff.getId());
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response, Integer type) {
        try {
            String fileName = "staff.xlsx";
            // 获取导入文件模板
            ClassPathResource classPathResource = new ClassPathResource("template/" + fileName);
            InputStream inputStream = classPathResource.getInputStream();
            com.yida.data.common.core.utils.FileUtil
                .download(com.yida.data.common.core.utils.FileUtil.inputStreamToFile(inputStream), fileName, false, response);
        } catch (Exception e) {
            throw new FebsException("教职工信息导入模板失败");
        }
//
//        // 根据树形结构建造文件夹
//        String tempDir = StrUtil.uuid().replace("-", "");
//        File dir = FileUtil.mkdir(tempDir);
//        FileWriter.create(FileUtil.newFile(dir.getAbsolutePath() + "\\" + "请阅读我！！！.txt"))
//            .writeFromStream(this.getClass().getClassLoader().getResourceAsStream("template/staff.txt"), true);
//
//        FileWriter.create(FileUtil.newFile(dir.getAbsolutePath() + "\\" + "人员信息.xlsx")).writeFromStream(
//            this.getClass().getClassLoader().getResourceAsStream(type == 0 ? "template/teacher.xlsx" : "template/staff.xlsx"),
//            true);
//        File file = ZipUtil.zip(tempDir);
//
//        System.out.println(file.getAbsolutePath());
//        try {
//            com.yida.data.common.core.utils.FileUtil.download(file, "导入模板.zip", true, response);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("student import template download fail,msg:[{}]", e.getMessage());
//        }
    }

    @Override
    public void downloadError(HttpServletResponse response, Integer type, Long noticeId) {
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(this.getClass().getClassLoader()
                .getResourceAsStream("template" + (type == 0 ? "/老师信息上传表" + ".xlsx" : "/staff.xlsx")));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("eerror:{}", e.getMessage());
            throw new FebsException("下载失败");
        }
        if (type == 0) {
            Map<Object, Object> errorData = redisService.hmget(CachePrefixConstant.IMPORT_TEACHER_KEY + noticeId.toString());
            JSONArray subject = JSONUtil.parseArray(errorData.get("subject").toString());
            JSONArray head = JSONUtil.parseArray(errorData.get("head").toString());
            JSONArray grade = JSONUtil.parseArray(errorData.get("grade").toString());
            JSONArray section = JSONUtil.parseArray(errorData.get("section").toString());
            JSONArray campus = JSONUtil.parseArray(errorData.get("campus").toString());

            if (subject != null && subject.size() > 0) {
                Sheet sheet = workbook.getSheetAt(0);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < subject.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(subject.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(subject.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(subject.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(subject.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(subject.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(subject.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(subject.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(subject.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(subject.getJSONObject(i).get("campus").toString());
                    row.createCell(10).setCellValue(subject.getJSONObject(i).get("subject").toString());
                    row.createCell(11).setCellValue(subject.getJSONObject(i).get("section").toString());
                    row.createCell(12).setCellValue(subject.getJSONObject(i).get("grade").toString());
                    row.createCell(13).setCellValue(subject.getJSONObject(i).get("class").toString());
                    row.createCell(14).setCellValue(subject.getJSONObject(i).get("position").toString());
                    row.createCell(15).setCellValue(subject.getJSONObject(i).get("identity").toString());
                    row.createCell(16).setCellValue(subject.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(17).setCellValue(subject.getJSONObject(i).get("foreignPosition").toString());
                }
            }

            if (head != null && head.size() > 0) {
                Sheet sheet = workbook.getSheetAt(1);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < head.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(head.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(head.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(head.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(head.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(head.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(head.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(head.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(head.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(head.getJSONObject(i).get("campus").toString());
                    row.createCell(10).setCellValue(head.getJSONObject(i).get("subject").toString());
                    row.createCell(11).setCellValue(head.getJSONObject(i).get("section").toString());
                    row.createCell(12).setCellValue(head.getJSONObject(i).get("grade").toString());
                    row.createCell(13).setCellValue(head.getJSONObject(i).get("class").toString());
                    row.createCell(14).setCellValue(head.getJSONObject(i).get("position").toString());
                    row.createCell(15).setCellValue(head.getJSONObject(i).get("identity").toString());
                    row.createCell(16).setCellValue(head.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(17).setCellValue(head.getJSONObject(i).get("foreignPosition").toString());
                }
            }

            if (grade != null && grade.size() > 0) {
                Sheet sheet = workbook.getSheetAt(2);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < grade.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(grade.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(grade.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(grade.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(grade.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(grade.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(grade.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(grade.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(grade.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(grade.getJSONObject(i).get("campus").toString());
                    row.createCell(10).setCellValue(grade.getJSONObject(i).get("section").toString());
                    row.createCell(11).setCellValue(grade.getJSONObject(i).get("grade").toString());
                    row.createCell(12).setCellValue(grade.getJSONObject(i).get("position").toString());
                    row.createCell(13).setCellValue(grade.getJSONObject(i).get("identity").toString());
                    row.createCell(14).setCellValue(grade.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(15).setCellValue(grade.getJSONObject(i).get("foreignPosition").toString());
                }
            }

            if (section != null && section.size() > 0) {
                Sheet sheet = workbook.getSheetAt(3);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < section.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(section.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(section.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(section.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(section.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(section.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(section.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(section.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(section.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(section.getJSONObject(i).get("campus").toString());
                    row.createCell(10).setCellValue(section.getJSONObject(i).get("section").toString());
                    row.createCell(11).setCellValue(section.getJSONObject(i).get("position").toString());
                    row.createCell(12).setCellValue(section.getJSONObject(i).get("identity").toString());
                    row.createCell(13).setCellValue(section.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(14).setCellValue(section.getJSONObject(i).get("foreignPosition").toString());
                }
            }

            if (campus != null && campus.size() > 0) {
                Sheet sheet = workbook.getSheetAt(4);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < campus.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(campus.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(campus.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(campus.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(campus.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(campus.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(campus.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(campus.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(campus.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(campus.getJSONObject(i).get("campus").toString());
                    row.createCell(10).setCellValue(campus.getJSONObject(i).get("position").toString());
                    row.createCell(11).setCellValue(campus.getJSONObject(i).get("identity").toString());
                    row.createCell(12).setCellValue(campus.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(13).setCellValue(campus.getJSONObject(i).get("foreignPosition").toString());
                }
            }
        } else {
            Object errorData = redisService.get(CachePrefixConstant.IMPORT_STAFF_KEY + noticeId.toString());
            if (ObjectUtil.isNotNull(errorData)) {
                JSONArray staff = JSONUtil.parseArray(errorData.toString());
                Sheet sheet = workbook.getSheetAt(0);
                sheet.removeRow(sheet.getRow(9));
                for (int i = 0; i < staff.size(); i++) {
                    Row row = sheet.createRow(9 + i);
                    row.createCell(1).setCellValue(staff.getJSONObject(i).get("name").toString());
                    row.createCell(2).setCellValue(staff.getJSONObject(i).get("alias").toString());
                    row.createCell(3).setCellValue(staff.getJSONObject(i).get("wxId").toString());
                    row.createCell(4).setCellValue(staff.getJSONObject(i).get("sex").toString());
                    row.createCell(5).setCellValue(staff.getJSONObject(i).get("phone").toString());
                    row.createCell(6).setCellValue(staff.getJSONObject(i).get("landLine").toString());
                    row.createCell(7).setCellValue(staff.getJSONObject(i).get("email").toString());
                    row.createCell(8).setCellValue(staff.getJSONObject(i).get("addr").toString());
                    row.createCell(9).setCellValue(staff.getJSONObject(i).get("deptName").toString());
                    row.createCell(10).setCellValue(staff.getJSONObject(i).get("identity").toString());
                    row.createCell(11).setCellValue(staff.getJSONObject(i).get("position").toString());
                    row.createCell(12).setCellValue(staff.getJSONObject(i).get("companyAbbre").toString());
                    row.createCell(13).setCellValue(staff.getJSONObject(i).get("foreignPosition").toString());
                }
            }
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("失败数据" + ".xlsx", "UTF-8"));
            response.setHeader("content_type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("eerror:{}", e.getMessage());
            throw new FebsException("下载失败");
        }
    }

    @Override
    public IPage<StaffPageVO> listStaffPage(Page page, CurrentUser currentUser, Long areaId, Long schoolId, Long deptId,
        Integer isLeader, String position, String name, String mobile, Integer sex,
        Integer collectType) {
        List<Long> schoolIds = new ArrayList<>();
        if (DeptTypeEnum.COMPANY_TYPE.getValue().equals(currentUser.getDeptType())) {
            if (schoolId != null) {
                schoolIds.add(schoolId);
            } else if (areaId != null) {
                List<Dept> schoolList = remoteDeptService.getSchoolByArea(areaId, null).getData();
                if (CollUtil.isNotEmpty(schoolList)) {
                    schoolIds.addAll(schoolList.stream().map(Dept::getDeptId).collect(Collectors.toList()));
                }
            }
        } else if (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(currentUser.getDeptType())) {
            schoolIds.add(currentUser.getDeptId());
        }
        IPage<StaffPageVO> staffPage = baseMapper.listStaffPage(page, schoolIds, deptId, isLeader,
            position, name, mobile, sex, collectType);
        if (CollUtil.isNotEmpty(staffPage.getRecords())) {
            // 查询系统用户
            List<Long> sysUserIds = staffPage.getRecords().stream().map(StaffPageVO::getSysUserId).filter(Objects::nonNull)
                .collect(Collectors.toList());
            List<SystemUser> systemUsers = new ArrayList<>();
            sysUserIds.addAll(
                staffPage.getRecords().stream().map(StaffPageVO::getCreateId).filter(Objects::nonNull)
                    .collect(Collectors.toList()));
            if (CollUtil.isNotEmpty(sysUserIds)) {
                // TODO: 2023/9/18 注释职工列表调用查询用户信息接口
//                systemUsers = remoteUserService.listInfoById(sysUserIds.toArray(new Long[sysUserIds.size()])).getData();
            }
            for (StaffPageVO record : staffPage.getRecords()) {
                if (CollUtil.isNotEmpty(systemUsers)) {
                    for (SystemUser systemUser : systemUsers) {
                        if (ObjectUtil.equal(record.getSysUserId(), systemUser.getUserId())) {
                            record.setStatus(Integer.valueOf(systemUser.getStatus()));
                        }
                        if (ObjectUtil.equal(record.getCreateId(), systemUser.getUserId())) {
                            record.setCreateUser(systemUser.getNickname());
                        }
                    }
                }
                // 查学校
                Dept school = commonService.getDept(record.getSchoolId());
                if (school != null) {
                    record.setSchoolName(school.getDeptName());
                }
                // 查部门与身份
                if (CollUtil.isNotEmpty(record.getDeptList())) {
                    StringBuilder sb = new StringBuilder();
                    for (EduStaffDept staffDept : record.getDeptList()) {
                        Dept dept = commonService.getDept(staffDept.getDeptId());
                        if (dept != null) {
                            sb.append(dept.getDeptName()).append("-").append(staffDept.getIsLeader() == 1 ? "上级" : "普通成员")
                                .append(",");
                        }
                    }
                    if (sb.length() > 0) {
                        record.setDeptIdentity(sb.substring(0, sb.length() - 1));
                    }
                }
            }
        }
        return staffPage;
    }

    @Override
    public void saveStaff(EduStaff eduStaff, CurrentUser currentUser) {
        Dept school = commonService.getDept(eduStaff.getSchoolId());

        EduStaff existStaff = null;
        if (eduStaff.getId() != null) {
            existStaff = getById(eduStaff.getId());
        }
        log.info("保存前的职工数据==================before: {}", existStaff);

        SystemUser systemUser = saveSystemUser(eduStaff);
        // 判断是新增还是修改
        if (eduStaff.getId() == null) {
            //新增
            eduStaff.setWxId(StrUtil.uuid().replace("-", ""));
            eduStaff.setSysUserId(systemUser.getUserId());
            eduStaff.setCreateId(currentUser.getUserId());
        } else {
            //修改
            eduStaff.setUpdateId(currentUser.getUserId());
        }
        // 保存职工信息
        saveOrUpdate(eduStaff);

        // 保存教师人脸
        if (StrUtil.isNotBlank(eduStaff.getAvatar())) {
            eduUserFaceService.updateUserFace(eduStaff.getAvatar(), eduStaff.getId(), eduStaff.getName(), 1);
        }
        // 删除关联信息重新添加
        eduStaffDeptMapper.delete(Wrappers.lambdaQuery(new EduStaffDept()).eq(EduStaffDept::getStaffId, eduStaff.getId()));
        List<EduStaffDept> staffDeptList = eduStaff.getStaffDept();
        if (CollUtil.isNotEmpty(staffDeptList)) {
            for (EduStaffDept staffDept : staffDeptList) {
                EduStaffDept eduStaffDept = new EduStaffDept();
                eduStaffDept.setStaffId(eduStaff.getId());
                eduStaffDept.setStaffName(eduStaff.getName());
                eduStaffDept.setDeptId(staffDept.getDeptId());
                eduStaffDept.setDeptName(staffDept.getDeptName());
                eduStaffDept.setDeptWxId(staffDept.getDeptWxId());
                eduStaffDept.setIsLeader(staffDept.getIsLeader());
                eduStaffDept.setIsMain(staffDept.getIsMain());
                eduStaffDept.setCreateId(currentUser.getUserId());
                eduStaffDeptMapper.insert(eduStaffDept);
            }
        }
        // 学校绑定了企业微信
        if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null, eduStaff.getSchoolId());
            // 当前为要同步到企业微信
            if (eduStaff.getWxPath() == 0) {
                log.info("保存后的职工数据-------------------------after: {}", existStaff);
                // 之前已经创建进行修改 否则新增
                if (existStaff != null && existStaff.getWxPath() == 0) {
                    eduStaff.setWxId(existStaff.getWxId());
                    wxUtil.updateUser(commonService.getAddressListToken(school.getDeptId()), eduStaff);
                } else {
                    wxUtil.createUser(commonService.getAddressListToken(school.getDeptId()), eduStaff);
                    //  判断是否需要转换成加密用户id
                    if (Objects.nonNull(app.getTemplateId())) {
                        // 转换用户id保存到数据库
                        String convertUserId = commonService.getSecretUserId(eduStaff.getWxId(), school.getDeptId());
                        eduStaff.setWxId(convertUserId);
                    }
                }
            } else {
                // 之前同步现在不同步  删除在企业微信中的数据
                if (existStaff != null && existStaff.getWxPath() == 0) {
                    wxUtil.deleteUser(commonService.getAddressListToken(school.getDeptId()),
                        Collections.singletonList(existStaff.getWxId()));
                    // 重新生成wxId
                    eduStaff.setWxId(StrUtil.uuid().replace("-", ""));
                }
            }
        }
        // 学校绑定了易达app
        if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
            EduYidaAppAccount yidaAppAccount = commonService.getYidaAppAccount(eduStaff.getSchoolId(), 1);
            EduYidaApp yidaApp = commonService.getYidaApp(eduStaff.getSchoolId());
            eduStaff.setYidaAppUserId(AppUtil.userSave(eduStaff.getMobile(), eduStaff.getName(), yidaApp));
            AppUtil.subscribeFollow(yidaAppAccount.getYidaAppAccountId(), eduStaff.getYidaAppUserId(), yidaApp);
        }
        // 绑定了大华
        if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
            int sex = Integer.parseInt(eduStaff.getSex()) + 1;
            sex = sex > 2 ? 1 : sex;
            if (existStaff != null) {
                DaHuaUtil.updateUser(eduStaff.getDahuaId(), eduStaff.getName(), eduStaff.getDahuaCode(), 1, sex, null, null, null,
                    null, null, eduStaff.getAvatar());
            } else {
                String cardNum = DaHuaUtil.generateCardNum();
                eduStaff.setDahuaCode(eduStaff.getMobile());
                eduStaff.setDahuaId(
                    DaHuaUtil.addUser(eduStaff.getName(), eduStaff.getMobile(), 1, sex, cardNum, null, null,
                        null, null, null, eduStaff.getAvatar()));
            }
        }
        updateById(eduStaff);
    }

    @Override
    public EduStaff getStaffById(Long staffId) {
        EduStaff staff = baseMapper.getStaffById(staffId);
        if (staff != null) {
            Dept dept = commonService.getDept(staff.getSchoolId());
            if (ObjectUtil.isNotNull(dept)) {
                staff.setSchoolName(dept.getDeptName());
            }
            if (CollUtil.isNotEmpty(staff.getStaffDept())) {
                for (EduStaffDept staffDept : staff.getStaffDept()) {
                    Dept staffD = commonService.getDept(staffDept.getDeptId());
                    if (staffD != null) {
                        staffDept.setDeptName(staffD.getDeptName());
                        staffDept.setStaffName(staff.getName());
                    }
                }
            }
        }
        return staff;
    }

    @Override
    public List<TeacherDeptVO> findTeacherRole(Long teacherId) {
        List<TeacherDeptVO> teacherDeptVOList = new ArrayList<>();
        //查询教师管理的部门， 班主任到班，其他角色到年级
        List<Integer> type = eduTeacherDeptMapper.findType(teacherId);
        if (type.contains(1)) { //校区负责人
            //查询教师对应年级
            List<EduUserDept> deptType = new ArrayList<>();
            List<EduTeacherDept> teacherDepts = eduTeacherDeptMapper.selectList(
                Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, teacherId)
                    .eq(EduTeacherDept::getType, 1));
            for (EduTeacherDept teacherDept : teacherDepts) {
                EduUserDept campusDept = eduUserDeptService.getById(teacherDept.getCampusId());
                List<EduUserDept> data = eduUserDeptService.findListByParent(
                    Collections.singletonList(teacherDept.getCampusId()));
                for (EduUserDept datum : data) {
                    EduUserDept sectionDept = eduUserDeptService.getById(datum.getDeptId());
                    List<EduUserDept> data1 = eduUserDeptService.findListByParent(Collections.singletonList(datum.getDeptId()));
                    for (EduUserDept dept : data1) {
                        TeacherDeptVO teacherDeptVO = new TeacherDeptVO();
                        teacherDeptVO.setCampusId(teacherDept.getCampusId());
                        teacherDeptVO.setCampusName(campusDept.getDeptName());
                        teacherDeptVO.setSectionId(datum.getDeptId());
                        teacherDeptVO.setSectionName(sectionDept.getDeptName());
                        teacherDeptVO.setGradeId(dept.getDeptId());
                        teacherDeptVO.setGradeName(dept.getDeptName());
                        teacherDeptVO.setType(1);
                        teacherDeptVOList.add(teacherDeptVO);
                    }
                }
            }
        } else if (type.contains(5)) { //学段负责人
            List<EduUserDept> deptType = new ArrayList<>();
            List<EduTeacherDept> teacherDepts = eduTeacherDeptMapper.selectList(
                Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, teacherId)
                    .eq(EduTeacherDept::getType, 5));
            for (EduTeacherDept teacherDept : teacherDepts) {
                EduUserDept sectionDept = eduUserDeptService.getById(teacherDept.getSectionId());
                AllDeptInfoVO parentUp = eduUserDeptService.findParentUp(teacherDept.getSectionId(), 4);
                List<EduUserDept> data = eduUserDeptService.findListByParent(
                    Collections.singletonList(teacherDept.getSectionId()));
                for (EduUserDept datum : data) {
                    TeacherDeptVO teacherDeptVO = new TeacherDeptVO();
                    teacherDeptVO.setCampusId(parentUp.getCampusId());
                    teacherDeptVO.setCampusName(parentUp.getCampusName());
                    teacherDeptVO.setSectionId(teacherDept.getSectionId());
                    teacherDeptVO.setSectionName(sectionDept.getDeptName());
                    teacherDeptVO.setGradeId(datum.getDeptId());
                    teacherDeptVO.setGradeName(datum.getDeptName());
                    teacherDeptVO.setType(5);
                    teacherDeptVOList.add(teacherDeptVO);
                }
            }
        } else if (type.contains(2)) { //年级负责人
            List<EduUserDept> deptType = new ArrayList<>();
            List<EduTeacherDept> teacherDepts = eduTeacherDeptMapper.selectList(
                Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, teacherId)
                    .eq(EduTeacherDept::getType, 2));
            for (EduTeacherDept teacherDept : teacherDepts) {
                AllDeptInfoVO parentUp = eduUserDeptService.findParentUp(teacherDept.getSectionId(), 4);
                log.info("上级部门信息：{}", parentUp);
                TeacherDeptVO teacherDeptVO = new TeacherDeptVO();
                teacherDeptVO.setCampusId(parentUp.getCampusId());
                teacherDeptVO.setCampusName(parentUp.getCampusName());
                teacherDeptVO.setSectionId(parentUp.getSectionId());
                teacherDeptVO.setSectionName(parentUp.getSectionName());
                teacherDeptVO.setGradeId(teacherDept.getGradeId());
                EduUserDept data = eduUserDeptService.getById(teacherDept.getGradeId());
                teacherDeptVO.setGradeName(data.getDeptName());
                teacherDeptVO.setType(2);
                teacherDeptVOList.add(teacherDeptVO);
            }
        } else {
            List<EduUserDept> deptList = eduTeacherDeptMapper.selectDeptList(teacherId); //班主任或者任课老师
            deptList.forEach(eduUserDept -> {
                AllDeptInfoVO parentUp = eduUserDeptService.findParentUp(eduUserDept.getDeptId(), 4);
                TeacherDeptVO teacherDeptVO = new TeacherDeptVO();
                teacherDeptVO.setCampusId(parentUp.getCampusId());
                teacherDeptVO.setCampusName(parentUp.getCampusName());
                teacherDeptVO.setSectionId(parentUp.getSectionId());
                teacherDeptVO.setSectionName(parentUp.getSectionName());
                teacherDeptVO.setGradeId(parentUp.getGradeId());
                teacherDeptVO.setGradeName(parentUp.getGradeName());
                teacherDeptVO.setType(3);
                teacherDeptVOList.add(teacherDeptVO);
            });
        }
        return teacherDeptVOList;
    }

    @Override
    public List<EduStaff> listTeacherByClass(List<Long> classIds, String name) {
        return eduTeacherDeptMapper.listTeacherByClass(classIds, name);
    }

    @Override
    public List<EduStaff> listTeacherBySchool(Long schoolId, String name) {
        return eduTeacherDeptMapper.listTeacherBySchool(schoolId, name);
    }

    @Override
    public List<EduTeacherDept> listTeacherDept(Long teacherId) {
        List<EduTeacherDept> teacherDeptList = eduTeacherDeptMapper.selectList(
            Wrappers.lambdaQuery(new EduTeacherDept()).eq(EduTeacherDept::getTeacherId, teacherId));
        if (CollUtil.isNotEmpty(teacherDeptList)) {
            for (EduTeacherDept teacherDept : teacherDeptList) {
                Long deptId = null;
                switch (teacherDept.getType()) {
                    case 1:
                        deptId = teacherDept.getCampusId();
                        break;
                    case 2:
                        deptId = teacherDept.getGradeId();
                        break;
                    case 3:
                    case 4:
                        deptId = teacherDept.getClassId();
                        break;
                    case 5:
                        deptId = teacherDept.getSectionId();
                        break;
                }
                if (deptId != null) {
                    EduUserDept userDept = eduUserDeptService.getById(deptId);
                    if (Objects.nonNull(userDept)) {
                        teacherDept.setDeptWxId(userDept.getWxId());
                    }

                }
            }
        }
        return teacherDeptList;
    }

    @Override
    public List<EduStaffDept> listStaffDept(Long staffId) {
        return eduStaffDeptService.list(Wrappers.lambdaQuery(new EduStaffDept()).eq(EduStaffDept::getStaffId, staffId));
    }

    @Override
    public List<StaffWithDeptVO> listStaffWithDept(Long schoolId) {
        return eduStaffDeptMapper.listStaffWithDept(schoolId);
    }

    @Override
    public List<TeacherCourseInfoVO> listTeacherCourseByGrade(Long gradeId, Long classId) {
        return eduTeacherDeptMapper.listTeacherCourseByGrade(gradeId, classId);
    }

    @Override
    public List<EduUserDept> listClassByGradeIdAndTeacherId(Long gradeId, Long staffId) {
        List<Integer> type = eduTeacherDeptMapper.findType(staffId);
        if (CollUtil.isEmpty(type)) {
            return new ArrayList<>();
        }
        if (type.contains(1) || type.contains(2) || type.contains(5)) {
            return eduUserDeptService.findChildByParent(gradeId);
        } else {
            List typeList = new ArrayList();
            typeList.add(3);
            typeList.add(4);
            List<EduTeacherDept> teacherDepts = eduTeacherDeptMapper.selectList(
                Wrappers.lambdaQuery(new EduTeacherDept())
                    .eq(EduTeacherDept::getTeacherId, staffId)
                    .eq(EduTeacherDept::getGradeId, gradeId)
                    .in(EduTeacherDept::getType, typeList));
            List<EduUserDept> list = eduUserDeptService.list(Wrappers.lambdaQuery(new EduUserDept())
                .in(EduUserDept::getDeptId, teacherDepts.stream().map(EduTeacherDept::getClassId).collect(
                    Collectors.toList())));
            return list;
        }
    }

    @Override
    public List<EduStaff> listTeacherByClassAndName(Long classId, String name) {
        return eduTeacherDeptMapper.listTeacherByClassAndName(classId, name);
    }


    @Override
    public List<Long> listStaffByDeptId(Long deptId, String nameOrPhone, Long schoolId) {

        return baseMapper.listStaffByNameOrPhone(deptId, nameOrPhone, schoolId);
    }

    @Override
    public List<EduStaff> listStaff(ListStaffDTO dto) {
        return baseMapper.listStaff(dto);
    }

    @Override
    public void syncQywxStaff() {
        log.info("开始同步职工数据");
        // 查询所有绑定了企业微信的学校
        List<Dept> schoolList = remoteDeptService.listSchoolBySchoolType(Dept.TYPE_QYWX).getData();
        for (Dept school : schoolList) {
            log.info("[{}], schoolId:[{}]开始同步职工数据", school.getDeptName(), school.getDeptId());
            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null, school.getDeptId());
            String accessToken = wxUtil.getAccessToken(school.getCorpId(), app.getWxSecret());
            // 判断学校是否绑定了大华
            boolean bindDaHuaFlag = false;
            if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
                bindDaHuaFlag = true;
            }
            // 判断学校是否绑定了app
            boolean bindAppFlag = false;
            EduYidaAppAccount yidaAppAccount = commonService.getYidaAppAccount(school.getDeptId(), 1);
            EduYidaApp yidaApp = commonService.getYidaApp(school.getDeptId());
            if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                bindAppFlag = true;
            }

            JSONArray userList = wxUtil.getUserList(accessToken, 1L);
            for (Object staff : userList) {
                Map<Long, Dept> deptCache = new HashMap<>();
                // 遍历企业微信成员
                JSONObject staffJson = (JSONObject) staff;
                String staffWxId = staffJson.getStr("userid");
                // 职工是否存在
                EduStaff existStaff = getOne(Wrappers.<EduStaff>lambdaQuery().eq(EduStaff::getWxId, staffWxId)
                    .eq(EduStaff::getSchoolId, school.getDeptId()));
                EduStaff eduStaff = existStaff != null ? existStaff : new EduStaff();

                eduStaff.setWxId(staffWxId);
                eduStaff.setName(staffJson.get("name").toString());
                eduStaff.setMobile(staffJson.get("mobile").toString());
                // 教师性别 0:男, 1:女, 2:保密
                String sexStr = staffJson.getStr("gender");
                eduStaff.setSex("1".equals(sexStr) ? "0" : "2".equals(sexStr) ? "1" : "2");
                eduStaff.setSchoolId(school.getDeptId());
                eduStaff.setSchoolName(school.getDeptName());
                eduStaff.setAvatar(eduStaff.getAvatar() == null ? staffJson.getStr("avatar") : null);
                eduStaff.setPosition(staffJson.getStr("position"));
                eduStaff.setEmail(staffJson.getStr("email"));
                eduStaff.setAddress(staffJson.getStr("address"));

                // 学校绑定了易达app
                if (bindAppFlag) {
                    eduStaff.setYidaAppUserId(AppUtil.userSave(eduStaff.getMobile(), eduStaff.getName(), yidaApp));
                    AppUtil.subscribeFollow(yidaAppAccount.getYidaAppAccountId(), eduStaff.getYidaAppUserId(), yidaApp);
                }
                // 绑定了大华
                if (bindDaHuaFlag) {
                    int sex = Integer.parseInt(eduStaff.getSex()) + 1;
                    sex = sex > 2 ? 1 : sex;
                    if (Objects.nonNull(eduStaff.getDahuaId())) {
                        DaHuaUtil
                            .updateUser(eduStaff.getDahuaId(), eduStaff.getName(), eduStaff.getDahuaCode(), 1, sex, null, null,
                                null,
                                null, null, "");
                    } else {
                        String cardNum = DaHuaUtil.generateCardNum();
                        eduStaff.setDahuaCode(eduStaff.getMobile());
                        eduStaff.setDahuaId(
                            DaHuaUtil.addUser(eduStaff.getName(), eduStaff.getMobile(), 1, sex, cardNum,
                                null, null, null, null, null, ""));
                    }
                }
                saveOrUpdate(eduStaff);

                // 成员部门信息
                JSONArray department = staffJson.getJSONArray("department");
                JSONArray isLeader = staffJson.getJSONArray("is_leader_in_dept");
                if (CollUtil.isNotEmpty(department)) {
                    eduStaffDeptService.remove(
                        Wrappers.<EduStaffDept>lambdaQuery().eq(EduStaffDept::getStaffId, eduStaff.getId()));
                    List<EduStaffDept> staffDeptList = new ArrayList<>();
                    for (int i = 0; i < department.size(); i++) {
                        // 成员的每个部门信息
                        EduStaffDept staffDept = new EduStaffDept();
                        staffDept.setStaffId(eduStaff.getId());
                        staffDept.setStaffName(eduStaff.getName());
                        staffDept.setDeptWxId(Long.valueOf(department.get(i).toString()));
                        Dept dept = deptCache.containsKey(staffDept.getDeptWxId()) ? deptCache.get(staffDept.getDeptWxId())
                            : (department.getLong(i) == 1L ? school : remoteDeptService.getDeptBySchoolAndWxId(school.getDeptId(),
                                Long.valueOf(department.get(i).toString())).getData());
                        staffDept.setDeptId(dept.getDeptId());
                        staffDept.setDeptName(dept.getDeptName());
                        staffDept.setIsLeader(isLeader.getInt(i));
                        staffDept.setIsMain(ObjectUtil.equal(staffJson.get("main_department"), department.get(i)) ? 0 : 1);
                        staffDeptList.add(staffDept);
                    }
                    eduStaffDeptService.saveBatch(staffDeptList);
                }
                // 保存系统用户信息
                saveSystemUser(eduStaff);
//                SystemUser systemUser = remoteUserService.getInfoByUsernameNoPermission(eduStaff.getMobile()).getData();
//                if (ObjectUtil.isNull(systemUser)) {
//                    systemUser = saveSystemUser(eduStaff);
//                    eduStaff.setYidaAppUserId(systemUser.getYidaAppUserId());
//                }
//                eduStaff.setSysUserId(systemUser.getUserId());
//                saveOrUpdate(eduStaff);
            }
        }
    }

    @Override
    public List<TeacherClassAndGradeVO> listClassAndGradeByTeacher(Long teacherId) {
        List<TeacherClassAndGradeVO> classAndGrade = baseMapper.listClassAndGradeByTeacher(teacherId);
        for (TeacherClassAndGradeVO classAndGradeId : classAndGrade) {
            EduUserDept data = eduUserDeptService.getById(classAndGradeId.getClassId());
            classAndGradeId.setClassName(data.getDeptName());
            EduUserDept gradeData = eduUserDeptService.getById(classAndGradeId.getGradeId());
            classAndGradeId.setGradeName(gradeData.getDeptName());
        }
        return classAndGrade;
    }

    @Override
    public StaStaffDistributeVO staStaffDistribute(List<Long> schoolIds) {
        StaStaffDistributeVO vo = new StaStaffDistributeVO();
        if (CollUtil.isNotEmpty(schoolIds)) {
            // 性别
            List<NameValueVO<String, Integer>> genderList = new ArrayList<>();
            NameValueVO<String, Integer> male = new NameValueVO<>();
            male.setName("男");
            male.setValue(
                (int) count(Wrappers.<EduStaff>lambdaQuery().eq(EduStaff::getSex, 0).in(EduStaff::getSchoolId, schoolIds)));
            NameValueVO<String, Integer> female = new NameValueVO<>();
            female.setName("女");
            female.setValue(
                (int) count(Wrappers.<EduStaff>lambdaQuery().eq(EduStaff::getSex, 1).in(EduStaff::getSchoolId, schoolIds)));
            NameValueVO<String, Integer> secret = new NameValueVO<>();
            secret.setName("未知");
            secret.setValue(
                (int) count(Wrappers.<EduStaff>lambdaQuery().notIn(EduStaff::getSex, 0, 1).in(EduStaff::getSchoolId, schoolIds)));
            genderList.add(male);
            genderList.add(female);
            genderList.add(secret);
            vo.setGender(genderList);
            // 年级、科目、角色
            List<TeacherListVO> teacherList = baseMapper.listTeacher(null, PageTeacherDTO.builder().schoolIds(schoolIds).build());
            if (CollUtil.isNotEmpty(teacherList)) {
                Map<String, Integer> sectionCount = new HashMap<>();
                Map<String, Integer> courseCount = new HashMap<>();
                Map<String, Integer> typeCount = new HashMap<>();
                for (TeacherListVO teacher : teacherList) {
                    List<TeacherDeptVO> deptList = teacher.getDeptVOList();
                    // 学段
                    Map<String, List<TeacherDeptVO>> sectionName = deptList.stream()
                        .filter(x -> StrUtil.isNotBlank(x.getSectionName()))
                        .collect(Collectors.groupingBy(TeacherDeptVO::getSectionName));
                    for (Entry<String, List<TeacherDeptVO>> section : sectionName.entrySet()) {
                        sectionCount.put(section.getKey(), sectionCount.getOrDefault(section.getKey(), 0) + 1);
                    }
                    // 科目
                    Map<String, List<TeacherDeptVO>> courseName = deptList.stream()
                        .filter(x -> StrUtil.isNotBlank(x.getCourseName()))
                        .collect(Collectors.groupingBy(TeacherDeptVO::getCourseName));
                    for (Entry<String, List<TeacherDeptVO>> course : courseName.entrySet()) {
                        courseCount.put(course.getKey(), courseCount.getOrDefault(course.getKey(), 0) + 1);
                    }
                    // 类型
                    List<Integer> typeList = deptList.stream()
                        .map(TeacherDeptVO::getType).collect(Collectors.toList());
                    for (Integer type : typeList) {
                        String s = null;
                        switch (type) {
                            case 1:
                                s = "校区负责人";
                                break;
                            case 2:
                                s = "年级负责人";
                                break;
                            case 3:
                                s = "班主任";
                                break;
                            case 4:
                                s = "任课老师";
                                break;
                            case 5:
                                s = "学段负责人";
                                break;
                            default:
                                ;
                        }
                        typeCount.put(s, typeCount.getOrDefault(s, 0) + 1);
                    }
                }
                // 学段数据
                if (!sectionCount.isEmpty()) {
                    List<NameValueVO<String, Integer>> sectionList = new ArrayList<>();
                    for (Entry<String, Integer> section : sectionCount.entrySet()) {
                        sectionList
                            .add(new NameValueVO<String, Integer>(Optional.ofNullable(section.getKey()).orElse("未知"),
                                section.getValue()));
                    }
                    vo.setSection(sectionList);
                }
                // 课程
                if (!courseCount.isEmpty()) {
                    List<NameValueVO<String, Integer>> courseList = new ArrayList<>();
                    for (Entry<String, Integer> course : courseCount.entrySet()) {
                        courseList.add(
                            new NameValueVO<String, Integer>(course.getKey() == null ? "未知" : course.getKey(),
                                course.getValue()));
                    }
                    vo.setCourse(courseList);
                }
                // 类型数据
                if (!typeCount.isEmpty()) {
                    List<NameValueVO<String, Integer>> typeList = new ArrayList<>();
                    for (Entry<String, Integer> type : typeCount.entrySet()) {
                        typeList
                            .add(new NameValueVO<String, Integer>(type.getKey() == null ? "未知" : type.getKey(), type.getValue()));
                    }
                    vo.setType(typeList);
                }
            }
            vo.setNum(teacherList.size());
        } else {
            vo.setNum(0);
        }
        return vo;
    }

    @Override
    public StaStaffDistributeVO staStaffNum(List<Long> schoolIds) {
        Long aLong = baseMapper.selectCount(Wrappers.<EduStaff>lambdaQuery().in(EduStaff::getSchoolId, schoolIds));
        StaStaffDistributeVO staStaffDistributeVO = new StaStaffDistributeVO();
        staStaffDistributeVO.setNum(Math.toIntExact(aLong));
        return staStaffDistributeVO;
    }

    @Override
    public void exportStaff(Long areaId, Long schoolId, Long deptId, Integer isLeader, String position,
        String name, String mobile, Integer sex, Integer collectType,
        HttpServletResponse response) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        CurrentUser currentUser = FebsUtil.getCurrentUser();
        List<Long> schoolIds = new ArrayList<>();
        if (DeptTypeEnum.COMPANY_TYPE.getValue().equals(currentUser.getDeptType())) {
            if (schoolId != null) {
                schoolIds.add(schoolId);
            } else if (areaId != null) {
                List<Dept> schoolList = remoteDeptService.getSchoolByArea(areaId, null).getData();
                if (CollUtil.isNotEmpty(schoolList)) {
                    schoolIds.addAll(schoolList.stream().map(Dept::getDeptId).collect(Collectors.toList()));
                }
            }
        } else if (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(currentUser.getDeptType())) {
            schoolIds.add(currentUser.getDeptId());
        }
        // 查询职工导出数据
        List<StaffPageVO> staffList = baseMapper.listExportStaff(schoolIds, deptId, isLeader,
            position, name, mobile, sex, collectType);
        List<StaffExportDTO> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(staffList)) {
            for (StaffPageVO vo : staffList) {
                // 查学校
                Dept school = commonService.getDept(vo.getSchoolId());
                if (school != null) {
                    vo.setSchoolName(school.getDeptName());
                }
                // 查部门与身份
                if (CollUtil.isNotEmpty(vo.getDeptList())) {
                    StringBuilder sb = new StringBuilder();
                    for (EduStaffDept staffDept : vo.getDeptList()) {
                        Dept dept = commonService.getDept(staffDept.getDeptId());
                        if (dept != null) {
                            sb.append(dept.getDeptName()).append("-").append(staffDept.getIsLeader() == 1 ? "上级" : "普通成员")
                                .append(",");
                        }
                    }
                    if (sb.length() > 0) {
                        vo.setDeptIdentity(sb.substring(0, sb.length() - 1));
                    }
                }

                StaffExportDTO exportDTO = new StaffExportDTO();
                BeanUtils.copyProperties(vo, exportDTO);
                String collectStatus = "未采集";
                if (Objects.nonNull(vo.getCollectType()) && vo.getCollectType() == 1) {
                    collectStatus = "已采集";
                }
                exportDTO.setCollectStatus(collectStatus);
                list.add(exportDTO);
            }
        }

        // 导出Excel
        EasyExcelUtil.exportExcelData(list, StaffExportDTO.class, "职工导出数据",
            ExcelTypeEnum.XLS, response);
        stopWatch.stop();
        log.info("导出职工数据总共耗时: {}", stopWatch.getTotalTimeSeconds() + "秒");
    }

    @Override
    public void getWxIdByStaffId(Long staffId) {
        EduStaff eduStaff = getById(staffId);
        EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SELECT, null, eduStaff.getSchoolId());
        if (Objects.nonNull(app.getTemplateId())) {
            // 转换用户id保存到数据库
            String convertUserId = wxServiceProviderUtil
                .convertUserIdToSecret(wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret()), eduStaff.getWxId());
            EduStaff changeStaff = new EduStaff();
            changeStaff.setId(eduStaff.getId());
            changeStaff.setWxId(convertUserId);
            updateById(changeStaff);
        }
    }

    @Override
    public void saveExcelData(ConcurrentHashMap<Integer, StaffImportDTO> concurrentHashMap,
        ConcurrentHashMap<Integer, Object> errorMap, Long schoolId, long timestamp) {

        // 当前登录用户信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        // 当前时间
        LocalDateTime now = LocalDateTime.now();

        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            // 保存前判断是否已存在
            for (Map.Entry<Integer, StaffImportDTO> entry : concurrentHashMap.entrySet()) {
                // 获取对应key-value值
                Integer i = entry.getKey();
                StaffImportDTO staffImportDTO = entry.getValue();
                // 验证导入信息是否为空
//                if (!checkStudentImportInfo(errorMap, welcomeStudentDTO, i)) {
//                    continue;
//                }
                // 验证身份证号码在当前学校的迎新表中是否重复
//                List<EduSchoolStudentInformation> studentList =
//                    this.eduSchoolStudentInformationMapper.selectList(Wrappers.lambdaQuery(new EduSchoolStudentInformation())
//                        .eq(EduSchoolStudentInformation::getStudentIdCard, welcomeStudentDTO.getStudentIdCard())
//                        .eq(EduSchoolStudentInformation::getSchoolId, schoolId)
//                    );
//                if (!studentList.isEmpty()) {
//                    log.error("身份证号码已存在: {}", welcomeStudentDTO.toString());
//                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.ID_CARD_EXIST.getValue());
//                    continue;
//                }
//                // 验证学区是否存在
//                EduUserDept campus = commonService.getUserDeptBySchoolIdAndNameAndType(
//                    welcomeStudentDTO.getCampusName(), UserDeptTypeEnum.CAMPUS_TYPE.getValue(),
//                    schoolId, String.valueOf(timestamp), schoolId);
//                if (!Optional.ofNullable(campus).isPresent()) {
//                    log.error("学区名称错误: {}", welcomeStudentDTO.toString());
//                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.CAMPUS_NAME_ERROR.getValue());
//                    continue;
//                }
//                // 验证学段是否存在
//                EduUserDept section = commonService.getUserDeptBySchoolIdAndNameAndType(
//                    welcomeStudentDTO.getSectionName(), UserDeptTypeEnum.SECTION_TYPE.getValue(),
//                    schoolId, String.valueOf(timestamp), campus.getDeptId());
//                if (!Optional.ofNullable(section).isPresent()) {
//                    log.error("学段名称错误: {}", welcomeStudentDTO.toString());
//                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.SECTION_NAME_ERROR.getValue());
//                    continue;
//                }
//                // 验证年级是否存在
//                EduUserDept grade = commonService.getUserDeptBySchoolIdAndNameAndType(
//                    welcomeStudentDTO.getGradeName(), UserDeptTypeEnum.GRADE_TYPE.getValue(),
//                    schoolId, String.valueOf(timestamp), section.getDeptId());
//                if (!Optional.ofNullable(grade).isPresent()) {
//                    log.error("年级名称错误: {}", welcomeStudentDTO.toString());
//                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.GRADE_NAME_ERROR.getValue());
//                    continue;
//                }
//                // 验证班级是否存在
//                EduUserDept classDept = commonService.getUserDeptBySchoolIdAndNameAndType(
//                    welcomeStudentDTO.getClassName(), UserDeptTypeEnum.CLASS_TYPE.getValue(),
//                    schoolId, String.valueOf(timestamp), grade.getDeptId());
//                if (!Optional.ofNullable(classDept).isPresent()) {
//                    log.error("班级名称错误: {}", welcomeStudentDTO.toString());
//                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.CLASS_NAME_ERROR.getValue());
//                    continue;
//                }
                // 保存数据
                EduStaff saveInfo = new EduStaff();
                BeanUtils.copyProperties(staffImportDTO, saveInfo);
                saveInfo.setWxPath(1);
                saveInfo.setSchoolId(FebsUtil.getDeptId());
                if (StringUtils.isNotEmpty(saveInfo.getMobile())) {
                    saveStaff(saveInfo, FebsUtil.getCurrentUser());
                }
            }
        }
    }

    @Override
    public List<DeptManagetVO> getDeptManager(List<Long> deptIdList, Long ruleId) {
        List<EduTeacherDept> teacherDeptList = eduTeacherDeptService.list(Wrappers.lambdaQuery(new EduTeacherDept())
            .eq(EduTeacherDept::getSchoolId, FebsUtil.getTopDeptId()));
        List<DeptManagetVO> deptManagetVOList = new ArrayList<>();
        for (Long deptId : deptIdList) {
            DeptManagetVO vo = new DeptManagetVO();
            vo.setDeptId(deptId);
            //班级
            List<EduTeacherDept> classDept = teacherDeptList.stream().filter(t -> deptId.equals(t.getClassId()))
                .collect(Collectors.toList());
            List<ManagerVo> managerVoList = new ArrayList<>();
            List<Long> staffIdList = new ArrayList<>();
            if (CollUtil.isEmpty(classDept)) {
                List<EduTeacherDept> gradeDept = teacherDeptList.stream()
                    .filter(t -> deptId.equals(t.getGradeId()) && ObjectUtil.isNull(t.getClassId()))
                    .collect(Collectors.toList());
                if (CollUtil.isEmpty(gradeDept)) {
                    List<EduTeacherDept> sectionDept = teacherDeptList.stream().filter(
                        t -> deptId.equals(t.getSectionId()) && ObjectUtil.isNull(t.getGradeId()) && ObjectUtil
                            .isNull(t.getClassId()))
                        .collect(Collectors.toList());
                    if (CollUtil.isEmpty(sectionDept)) {
                        List<EduTeacherDept> campusDept = teacherDeptList.stream().filter(
                            t -> deptId.equals(t.getCampusId()) && ObjectUtil.isNull(t.getSectionId()) && ObjectUtil
                                .isNull(t.getGradeId()) && ObjectUtil.isNull(t.getClassId()))
                            .collect(Collectors.toList());
                        if (CollUtil.isEmpty(campusDept)) {
                            List<EduTeacherDept> schoolDept = teacherDeptList.stream()
                                .filter(t -> deptId.equals(-t.getSchoolId()) && ObjectUtil.isNull(t.getCampusId()) && ObjectUtil
                                    .isNull(t.getSectionId()) && ObjectUtil
                                    .isNull(t.getGradeId()) && ObjectUtil.isNull(t.getClassId()))
                                .collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(schoolDept)) {
                                staffIdList = schoolDept.stream().map(EduTeacherDept::getTeacherId).collect(Collectors.toList());
                            }
                        } else {
                            staffIdList = campusDept.stream().map(EduTeacherDept::getTeacherId).collect(Collectors.toList());
                        }
                    } else {
                        staffIdList = sectionDept.stream().map(EduTeacherDept::getTeacherId).collect(Collectors.toList());
                    }
                } else {
                    staffIdList = gradeDept.stream().map(EduTeacherDept::getTeacherId).collect(Collectors.toList());
                }

            } else {
                staffIdList = classDept.stream().map(EduTeacherDept::getTeacherId).collect(Collectors.toList());
            }
            for (Long staffId : staffIdList) {
                ManagerVo managerVo = new ManagerVo();
                managerVo.setUserId(staffId);
                managerVo.setUserName(commonService.getStaffById(staffId).getName());
                managerVoList.add(managerVo);
            }
            vo.setManagerVoList(managerVoList);
            deptManagetVOList.add(vo);
        }
        return deptManagetVOList;
    }

    @Override
    public void updateStaffCache() {
        log.info("开始更新教职工信息缓存");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        redisService.del(CachePrefixConstant.STAFF_DATA);
        List<EduStaff> staffList = list();
        for (EduStaff staff : staffList) {
            EduStaff staffById = getStaffById(staff.getId());
            if (ObjectUtil.isNotNull(staffById)) {
                redisService.hset(CachePrefixConstant.STAFF_DATA, staffById.getId().toString(), staffById);
            }
        }
        stopWatch.stop();
        log.info("更新教职工信息缓存结束，总共耗时：[{}]", stopWatch.getTotalTimeSeconds() + "秒");
    }
}