package yangtz.cs.liu.campus.service.impl.teacher;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.annotation.DeptFilter;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import org.springframework.web.bind.annotation.PathVariable;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClassMentor;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherResume;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherWages;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMentorMapper;
import yangtz.cs.liu.campus.mapper.teacher.*;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherVO;
import yangtz.cs.liu.campus.vo.teacher.TeacherNameListVo;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static yangtz.cs.liu.campus.constant.UserType.TEACHER;

@Service
public class SchoolTeacherServiceImpl extends ServiceImpl<SchoolTeacherMapper, SchoolTeacher> implements ISchoolTeacherService {

    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    @Autowired
    private SchoolTeacherAwardMapper schoolTeacherAwardMapper;

    @Autowired
    private SchoolTeacherDutyMapper schoolTeacherDutyMapper;

    @Autowired
    private SchoolTeacherLeaveMapper schoolTeacherLeaveMapper;

    @Autowired
    private SchoolTeacherOvertimeMapper schoolTeacherOvertimeMapper;

    @Autowired
    private SchoolTeacherResumeMapper schoolTeacherResumeMapper;

    @Autowired
    private SchoolTeacherWagesMapper schoolTeacherWagesMapper;

    @Autowired
    private SchoolClassMentorMapper schoolClassMentorMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    /*
     * 获取老师列表信息
     * */
    @Override
    //@DeptFilter(deptAlias = "d")
    public List<SchoolTeacher> selectSchoolTeacherList(SchoolTeacherVO schoolTeacher) {
        return schoolTeacherMapper.selectSchoolTeacherList(schoolTeacher);
    }

    @Override
    public List<SchoolTeacher> teacherList(SchoolTeacherVO schoolTeacher) {
        return schoolTeacherMapper.teacherList(schoolTeacher);
    }

    //添加老师信息
    @Override
    public String insertTeacher(SchoolTeacher schoolTeacher) {
        int i = judgIsExit(schoolTeacher);
        if (i == 0) {
            schoolTeacher.setUserId(getUserId());
            this.save(schoolTeacher);
            return "新增成功";
        } else if (i == 1) {
            return "老师姓名" + schoolTeacher.getTeacherName() + "已存在，新增失败";
        } else if (i == 2) {
            return "身份证号" + schoolTeacher.getIdCard() + "已存在,新增失败";
        } else if (i == 3) {
            return "工作编号" + schoolTeacher.getTeacherCode() + "已存在，新增失败";
        } else if (i == 4) {
            return "老师电话" + schoolTeacher.getTeacherTel() + "已存在，新增失败";
        } else {
            return "微信号" + schoolTeacher.getOpenId() + "已存在，新增失败";
        }

    }

    //id获取教师列表
    @Override
    public List<SchoolTeacher> listByIds(List<Long> ids) {
        return schoolTeacherMapper.listByIds(ids);
    }

    //修改教师信息
    @Override
    public String updateSchoolTeacher(SchoolTeacher schoolTeacher) {
        int i = judgIsExit(schoolTeacher);
        if (i == 0) {
            this.updateById(schoolTeacher);
            return "更新成功";
        } else if (i == 1) {
            return "老师姓名" + schoolTeacher.getTeacherName() + "已存在，更新失败";
        } else if (i == 2) {
            return "身份证号" + schoolTeacher.getIdCard() + "已存在,更新失败";
        } else if (i == 3) {
            return "工作编号" + schoolTeacher.getTeacherCode() + "已存在，更新失败";
        } else if (i == 4) {
            return "老师电话" + schoolTeacher.getTeacherTel() + "已存在，更新失败";
        } else {
            return "微信号" + schoolTeacher.getOpenId() + "已存在，更新失败";
        }
    }

    //判断老师信息是否重复
//    @Override
//    public SchoolTeacher judgeSchoolTeacher(SchoolTeacherVO schoolTeacher) {
//        return schoolTeacherMapper.judgeSchoolTeacher(schoolTeacher);
//    }

    //删除老师信息byids
    @Override
    public int deleteSchoolTeacherByIds(List<Long> ids) {
        //TODO 先删除子表的信息
        //使用的mybatis-plus方式
        LambdaQueryWrapper<SchoolTeacherWages> schoolTeacherWages = new LambdaQueryWrapper<>();
        schoolTeacherWages
                .in(SchoolTeacherWages::getTeacherId, ids)
        ;

        LambdaQueryWrapper<SchoolTeacherResume> schoolTeacherResume = new LambdaQueryWrapper<>();
        schoolTeacherResume
                .in(SchoolTeacherResume::getTeacherId, ids)
        ;
        schoolTeacherWagesMapper.delete(schoolTeacherWages);
        schoolTeacherResumeMapper.delete(schoolTeacherResume);

        //使用的mybatis方式
        schoolTeacherAwardMapper.deleteSchoolTeacherAwardByIds(ids);
//        schoolTeacherDutyMapper.removeschoolTeacherDutyByIds(ids);
        schoolTeacherLeaveMapper.removeSchoolTeacherLeaveByTeacherIds(ids);
        schoolTeacherOvertimeMapper.removeSchoolTeacherOvertimeByIds(ids);

        List<SchoolTeacher> schoolTeachers = schoolTeacherMapper.selectBatchIds(ids);
        List<Long> userIds = new ArrayList<>();
        for (SchoolTeacher schoolTeacher : schoolTeachers) {
            userIds.add(schoolTeacher.getUserId());
        }
        sysUserMapper.removeUserByIds(userIds);
//        sysUserMapper.deleteUserByIds(userIds);
        return schoolTeacherMapper.deleteSchoolTeacherByIds(ids);
    }

    @Override
    public String importStudent(List<SchoolTeacherVO> dataManagementList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(dataManagementList) || dataManagementList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolTeacherVO teacher : dataManagementList) {
            try {
                /*
                 * 验证是否存在这个老师
                 *工作编号不能重复，姓名不能重复，身份证号不能重复，老师电话不能重复、微信号不能重复
                 * */
                SchoolTeacher schoolTeacher = new SchoolTeacher();
                BeanUtils.copyProperties(teacher, schoolTeacher);
                int i = judgIsExit(schoolTeacher);
                if (i == 0) {
                    this.save(schoolTeacher);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、老师 " + schoolTeacher.getTeacherName() + " 导入成功");
                } else if (i == 1) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "导入失败、老师姓名 " + schoolTeacher.getTeacherName() + " 已存在");
                } else if (i == 2) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "导入失败、身份证号 " + schoolTeacher.getIdCard() + " 已存在");
                } else if (i == 3) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "导入失败、工作编号 " + schoolTeacher.getTeacherCode() + " 已存在");
                } else if (i == 4) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "导入失败、老师电话 " + schoolTeacher.getTeacherTel() + " 已存在");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "导入失败、微信号 " + schoolTeacher.getOpenId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、老师 " + teacher.getTeacherName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    /**
     * 公众号获取老师信息
     *
     * @param studentId
     * @return
     */
    @Override
    public List<SchoolTeacher> getTeacherInfo(Long studentId) {
        return schoolTeacherMapper.getTeacherInfo(studentId);
    }

    /**
     * 公众号
     *
     * @param teacherName
     * @return
     */
    @Override
    public List<SchoolTeacher> queryList(String teacherName) {
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.like(isNotBlank(teacherName), SchoolTeacher::getTeacherName, teacherName);
        return schoolTeacherMapper.selectList(lqw);
    }

    /**
     * 导入数据校验
     *
     * @param list
     */
    @Override
    public void checkImport(List<SchoolTeacher> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolTeacher schoolTeacher : list) {
            if (StringUtils.isEmpty(schoolTeacher.getTeacherName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、教师姓名为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolTeacher.getSex())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、教师性别为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolTeacher.getIdCard())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolTeacher.getTeacherTel())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、电话号码为空,请您重新输入! ");
            } else {
                LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
                lqw
                        .eq(SchoolTeacher::getIdCard, schoolTeacher.getIdCard())
                        .eq(SchoolTeacher::getTeacherCode, schoolTeacher.getTeacherCode())
                        .eq(SchoolTeacher::getTeacherTel, schoolTeacher.getTeacherTel())
                ;
                SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
                if (isNotNull(teacher)) {
                    if (StringUtils.isNotBlank(schoolTeacher.getTeacherCode()) && schoolTeacher.getTeacherCode().equals(teacher.getTeacherCode())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、教师编号已存在,请您重新输入! ");
                    } else if (schoolTeacher.getIdCard().equals(teacher.getIdCard())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、教师身份证号已存在,请您重新输入! ");
                    } else if (schoolTeacher.getTeacherTel().equals(teacher.getTeacherTel())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、教师电话号码已存在,请您重新输入! ");
                    }
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
    }

    /**
     * 导入数据
     *
     * @param list
     * @return
     */
    @Override
    public String importData(List<SchoolTeacher> list) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        for (SchoolTeacher schoolTeacher : list) {
            try {
                //新增进userId
                SysUser user = new SysUser();
                sysUserMapper.insertUser(user);
                schoolTeacher.setUserId(user.getUserId());
                schoolTeacherMapper.insertTeacher(schoolTeacher);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据" + " 导入成功");
            } catch (Exception e) {
                throw new ServiceException("导入失败");
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    /**
     * 检查设备号是否唯一
     */
    @Override
    public void checkDeviceNumUnique(SchoolTeacherVO schoolTeacher) {
        Long id = StringUtils.isNull(schoolTeacher.getId()) ? -1L : schoolTeacher.getId();
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getDeviceNum, schoolTeacher.getDeviceNum());
        SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
        if (StringUtils.isNotNull(teacher) && teacher.getId().longValue() != id.longValue()) {
            throw new ServiceException("设备号已存在");
        }
    }

    /**
     * 检查教师编号是否唯一
     */
    @Override
    public void checkTeacherCodeUnique(SchoolTeacherVO schoolTeacher) {
        Long id = StringUtils.isNull(schoolTeacher.getId()) ? -1L : schoolTeacher.getId();
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getTeacherCode, schoolTeacher.getTeacherCode());
        SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
        if (StringUtils.isNotNull(teacher) && teacher.getId().longValue() != id.longValue()) {
            throw new ServiceException("工作编号已存在");
        }
    }

    /**
     * 检查身份证号是否唯一
     */
    @Override
    public void checkIdCardUnique(SchoolTeacherVO schoolTeacher) {
        Long id = StringUtils.isNull(schoolTeacher.getId()) ? -1L : schoolTeacher.getId();
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getIdCard, schoolTeacher.getIdCard());
        SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
        if (StringUtils.isNotNull(teacher) && teacher.getId().longValue() != id.longValue()) {
            throw new ServiceException("身份证号已存在");
        }
    }

    /**
     * 检查手机号是否唯一
     */
    @Override
    public void checkTeacherTelUnique(SchoolTeacherVO schoolTeacher) {
        Long id = StringUtils.isNull(schoolTeacher.getId()) ? -1L : schoolTeacher.getId();
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getTeacherTel, schoolTeacher.getTeacherTel());
        SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
        if (StringUtils.isNotNull(teacher) && teacher.getId().longValue() != id.longValue()) {
            throw new ServiceException("手机号码已存在");
        }
    }

    /**
     * 检查邮箱账号是否唯一
     */
    @Override
    public void checkEmailUnique(SchoolTeacherVO schoolTeacher) {
        Long id = StringUtils.isNull(schoolTeacher.getId()) ? -1L : schoolTeacher.getId();
        SysUser info = sysUserMapper.checkEmailUnique(schoolTeacher.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != id.longValue()) {
            throw new ServiceException("邮箱账号已存在");
        }
    }

    /**
     * 检查密码是否符合条件(密码必须包含大小写字母、数字、特殊字符中的任意三种)
     * @param schoolTeacherVO
     */
    @Override
    public void checkPasswordUnique(SchoolTeacherVO schoolTeacherVO) {
        String password = schoolTeacherVO.getPassword();
//        String pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{8,}$";
        String pattern = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$";
        boolean matches = Pattern.matches(pattern, password);
        if (matches == false){
            throw new ServiceException("密码必须包含大小写字母、数字、特殊字符中的任意三种");
        }
    }


    @Override
    public int insert(SchoolTeacherVO schoolTeacherVO) {
        /** 先新增用户表 */
        SysUser user = new SysUser();
        BeanUtils.copyProperties(schoolTeacherVO, user);
        /** 加密密码 */
        user.setPassword(SecurityUtils.encryptPassword(schoolTeacherVO.getPassword()));
        user.setLoginName(schoolTeacherVO.getTeacherName());
        user.setUserName(schoolTeacherVO.getTeacherName());
        user.setPhonenumber(schoolTeacherVO.getTeacherTel());
        //user.setAvatar(schoolTeacherVO.getPicUrl());
        /** 老师 */
        //user.setUserType(TEACHER);
        user.setUserLoginType(TEACHER);
        userService.insertUser(user);

        /** 新增教师表 */
        schoolTeacherVO.setId(user.getUserId());
        schoolTeacherVO.setPicUrl(schoolTeacherVO.getAvatar());
        return schoolTeacherMapper.insertSchoolTeacher(schoolTeacherVO);
    }

    @Override
    public int updateTeacher(SchoolTeacherVO schoolTeacherVO) {
        /** 修改用户 */
        SysUser user = new SysUser();
        BeanUtils.copyProperties(schoolTeacherVO, user);
        if (StringUtils.isNotBlank(schoolTeacherVO.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(schoolTeacherVO.getPassword()));
        }
        user.setUserName(schoolTeacherVO.getTeacherName());
        user.setPhonenumber(schoolTeacherVO.getTeacherTel());
        //user.setAvatar(schoolTeacherVO.getPicUrl());
        user.setUserId(schoolTeacherVO.getId());
        userService.updateUser(user);

        /** 修改教师表 */
        schoolTeacherVO.setPicUrl(schoolTeacherVO.getAvatar());
        return schoolTeacherMapper.updateTeacher(schoolTeacherVO);
    }

    /**
     * 个人信息修改，不涉及角色，岗位修改
     */
    @Override
    public int editProfile(SchoolTeacherVO schoolTeacherVO) {
        /** 修改用户 */
        SysUser user = new SysUser();
        BeanUtils.copyProperties(schoolTeacherVO, user);
        user.setUserName(schoolTeacherVO.getTeacherName());
        user.setPhonenumber(schoolTeacherVO.getTeacherTel());
       // user.setAvatar(schoolTeacherVO.getPicUrl());
        user.setUserId(schoolTeacherVO.getId());
        userService.updateUserProfile(user);

        /** 修改教师表 */
        return schoolTeacherMapper.updateTeacher(schoolTeacherVO);
    }

    @Override
    public int deleteTeacher(List<Long> ids) {
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.in(SchoolTeacher::getId, ids);
        List<SchoolTeacher> schoolTeacherList = schoolTeacherMapper.selectList(lqw);
        /** 级联删除用户表 */
        List<Long> list = schoolTeacherList.stream().map(SchoolTeacher::getId).collect(Collectors.toList());
        Long[] userIds = (Long[]) list.toArray(new Long[list.size()]);
        userService.deleteUserByIds(userIds);
        /** 删除教师表 */
        return schoolTeacherMapper.deleteBatchIds(ids);
    }

    @Override
    public SchoolTeacherVO queryOne(Long id) {
//        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(SchoolTeacher::getId, id).select(SchoolTeacher::getUserId);
//        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectOne(lqw);
//        Long userId = schoolTeacher.getUserId();
        SchoolTeacher teacher = schoolTeacherMapper.selectById(id);
        Long userId = teacher.getId();

        SchoolTeacherVO schoolTeacherVO = new SchoolTeacherVO();
        BeanUtils.copyProperties(teacher, schoolTeacherVO);

        List<Long> roleList = roleMapper.selectRoleListByUserId(userId);
        schoolTeacherVO.setRoleIds((Long[]) roleList.toArray(new Long[roleList.size()]));
        List<SysRole> sysRoles = roleMapper.getRolesByUserId(userId);
        schoolTeacherVO.setRoleName(sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.joining(",")));

        List<Long> postList = postMapper.selectPostListByUserId(userId);
        schoolTeacherVO.setPostIds((Long[]) postList.toArray(new Long[postList.size()]));
        List<SysPost> sysPosts = postMapper.getPostsByUserId(userId);
        schoolTeacherVO.setPostName(sysPosts.stream().map(SysPost::getPostName).collect(Collectors.joining(",")));

        //查询任职部门信息
        List<Long> deptList = deptMapper.selectDeptListByUserId(userId);
        schoolTeacherVO.setDeptIds((Long[]) deptList.toArray(new Long[deptList.size()]));
        List<SysDept> sysDepts = deptMapper.getDeptdByUserId(userId);
        schoolTeacherVO.setDeptNames(sysDepts.stream().map(SysDept::getDeptName).collect(Collectors.joining(",")));

        SysUser user = userService.selectUserById(userId);
        schoolTeacherVO.setStatus(user.getStatus());
        schoolTeacherVO.setDeptId(user.getDeptId());
        schoolTeacherVO.setDeptName(user.getDept().getDeptName());
        schoolTeacherVO.setEmail(user.getEmail());
        schoolTeacherVO.setRemark(user.getRemark());
        //schoolTeacherVO.setUserLoginType(user.getUserLoginType());
        schoolTeacherVO.setEmployeeType(user.getEmployeeType());
        schoolTeacherVO.setSign(user.getSign());
        schoolTeacherVO.setAvatar(user.getAvatar());
        return schoolTeacherVO;
    }

    /**
     * 个人工作->基本信息
     */
    @Override
    public SchoolTeacher getProfile() {
        SchoolTeacher teacher = schoolTeacherMapper.getProfile(getUserId());
        SysDept dept = deptMapper.selectDeptById(teacher.getDeptId());
        if (StringUtils.isNotNull(dept.getParentId())) {
            teacher.setParentId(dept.getParentId());
            teacher.setParentName(dept.getParentName());
        }
        return teacher;
    }

    //查询全部教职工
    @Override
    public List<SchoolTeacher> getAllTeachers(SchoolTeacher teacher) {
        return schoolTeacherMapper.getAllTeachers(teacher);
    }

    //获取处室主任
    @Override
    public List<SchoolTeacher> getSectionLeader(Long deptId, String role,SchoolTeacherVO teacher) {
        return schoolTeacherMapper.getSectionLeader(deptId, role,teacher);
    }

    //(改造)获取处室主任
    @Override
    public List<SchoolTeacher> getSectionDirector(Long deptId, String role, SchoolTeacherVO teacher) {
        return schoolTeacherMapper.getSectionDirector(deptId, role,teacher);
    }

    @Override
    public List<TeacherNameListVo> selectSchoolTeacherNameList() {
        return schoolTeacherMapper.selectSchoolTeacherNameList();
    }

    public int judgIsExit(SchoolTeacher schoolTeacher) {
        SchoolTeacher schoolTeacher1 = new SchoolTeacher();
        if (StringUtils.isNotNull(schoolTeacher.getId())) {
            schoolTeacher1.setId(schoolTeacher.getId());
        }
        schoolTeacher1.setTeacherName(schoolTeacher.getTeacherName());
        if (schoolTeacherMapper.query(schoolTeacher1).size() > 0 && schoolTeacher.getTeacherName() != null) {
            return 1;
        }
        schoolTeacher1.setTeacherName("");
        schoolTeacher1.setIdCard(schoolTeacher.getIdCard());
        if (schoolTeacherMapper.query(schoolTeacher1).size() > 0 && schoolTeacher.getIdCard() != null) {
            return 2;
        }
        schoolTeacher1.setIdCard("");
        schoolTeacher1.setTeacherCode(schoolTeacher.getTeacherCode());
        if (schoolTeacherMapper.query(schoolTeacher1).size() > 0 && schoolTeacher.getTeacherCode() != null) {
            return 3;
        }
        schoolTeacher1.setTeacherCode("");
        schoolTeacher1.setTeacherTel(schoolTeacher.getTeacherTel());
        if (schoolTeacherMapper.query(schoolTeacher1).size() > 0 && schoolTeacher.getTeacherTel() != null) {
            return 4;
        }
        schoolTeacher1.setTeacherTel("");
        schoolTeacher1.setOpenId(schoolTeacher.getOpenId());
        if (schoolTeacherMapper.query(schoolTeacher1).size() > 0 && schoolTeacher.getOpenId() != null) {
            return 5;
        }
        return 0;
    }

    /**
     * 微信 查看班级所有任课老师信息
     */
    @Override
    public List<SchoolTeacherVO> getTeachers(Long classId) {
        LambdaQueryWrapper<SchoolClassMentor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolClassMentor::getClassId, classId);
        List<SchoolClassMentor> schoolClassMentors = schoolClassMentorMapper.selectList(lqw);
        List<SchoolTeacherVO> list = new ArrayList<>();
        for (SchoolClassMentor schoolClassMentor : schoolClassMentors) {
            SchoolTeacherVO schoolTeacherVO = new SchoolTeacherVO();
            Long teacherId = schoolClassMentor.getTeacherId();
            SchoolTeacher teacher = schoolTeacherMapper.selectById(teacherId);
            if (isNotNull(teacher)) {
                BeanUtils.copyProperties(teacher, schoolTeacherVO);
            }
            schoolTeacherVO.setCourseName(schoolClassMentor.getCourseName());
            list.add(schoolTeacherVO);
        }
        return list;

    }

    //修改头像
    @Override
    public boolean updatePic(Long userId, String avatar) {
        return schoolTeacherMapper.updatePic(userId,avatar) > 0;
    }

    @Override
    public String getOpenIdByUserId(Long userId) {
        return schoolTeacherMapper.getOpenIdByUserId(userId);
    }

    @Override
    public String getDdUserIdByUserId(Long userId) {
        return schoolTeacherMapper.getDdUserIdByUserId(userId);
    }

    @Override
    public String getUnionIdByUserId(Long userId) {
        return schoolTeacherMapper.getUnionIdByUserId(userId);
    }

    public void updateDdUserId(SysUser sysUser,String ddUserId) {
        //更新教师表钉钉用户id
        SchoolTeacher schoolTeacher = new SchoolTeacher();
        schoolTeacher.setId(sysUser.getUserId());
        schoolTeacher.setDdUserId(ddUserId);
        schoolTeacher.setUnionId(sysUser.getUnionId());
        schoolTeacherMapper.updateById(schoolTeacher);

        //更新用户表钉钉用户id
        SysUser user = new SysUser();
        user.setUserId(sysUser.getUserId());
        user.setDdUserId(ddUserId);
        user.setUnionId(sysUser.getUnionId());
        sysUserMapper.updateUser(user);
    }

    @Override
    public SchoolTeacher selectTeacherByPhone(String phonenumber){
        return schoolTeacherMapper.getTeacherByPhone(phonenumber);
    }
}
