package yangtz.cs.liu.dingding.service.impl.dingUser;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClassHeadmaster;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClassMentor;
import yangtz.cs.liu.campus.domain.schoolCurriculum.SchoolCurriculum;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentClassRelation;
import yangtz.cs.liu.campus.domain.student.SchoolStudentClasses;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.mapper.schoolCurriculum.SchoolCurriculumMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassHeadmasterService;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassMentorService;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentClassRelationService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentClassesService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;
import yangtz.cs.liu.dingding.domain.dingDept.SysDdDept;
import yangtz.cs.liu.dingding.domain.dingGrade.SchoolGradeMentorCopy;
import yangtz.cs.liu.dingding.domain.dingUser.SysDdUser;
import yangtz.cs.liu.dingding.domain.dingUser.SysDdUserDept;
import yangtz.cs.liu.dingding.domain.schoolTeacher.SysDdTeacher;
import yangtz.cs.liu.dingding.mapper.dingDept.DdDeptMapper;
import yangtz.cs.liu.dingding.mapper.dingUser.DdUserMapper;
import yangtz.cs.liu.dingding.mapper.schoolTeacher.DdTeacherMapper;
import yangtz.cs.liu.dingding.service.dingUser.IDdUserService;
import yangtz.cs.liu.dingding.utils.AccessTokenUtils;
import yangtz.cs.liu.dingding.utils.DingDeptUtils;
import yangtz.cs.liu.dingding.utils.DingUserUtils;
import yangtz.cs.liu.dingding.vo.DingJiaXiaoVo;
import yangtz.cs.liu.wechat.utils.AccessTokenUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DdUserServiceImpl implements IDdUserService {
    private static Logger log = LoggerFactory.getLogger(DdUserServiceImpl.class);

    @Autowired
    private DingUserUtils dingUserUtils;
    @Autowired
    private DdDeptMapper ddDeptMapper;
    @Autowired
    private DdUserMapper ddUserMapper;
    @Autowired
    private DdTeacherMapper ddTeacherMapper;
    @Autowired
    private DingDeptUtils dingDeptUtils;
    //班主任和班级关系
    @Autowired
    ISchoolClassHeadmasterService iSchoolClassHeadmasterService;
    @Autowired
    private SchoolTeacherMapper teacherMapper;
    @Autowired
    ISysUserService sysUserService;
    //学校班级
    @Autowired
    ISchoolClassService iSchoolClassService;

    @Autowired
    SchoolCurriculumMapper schoolCurriculumMapper;
    //任课老师和班级关系 ----------------
    @Autowired
    ISchoolClassMentorService schoolClassMentorService;

    //学生表     ---------------------
    @Autowired
    ISchoolStudentService schoolStudentService;
    //学生与班级关系 --------------------
    @Autowired
    ISchoolStudentClassRelationService iSchoolStudentClassRelationService;
    //学生历史班级表    -----------------
    @Autowired
    ISchoolStudentClassesService schoolStudentClassesService;
    @Autowired
    private AccessTokenUtils accessTokenUtils;
    //家长信息表          ---------------------
    @Autowired
    ISchoolStudentParentService iSchoolStudentParentService;

    final String teacher ="teacher";
    final String guardian ="guardian";
    final String student ="student";


    /**
     * 获取钉钉全部用户id
     * @return
     */
    @Override
    public List<String> getDdUserListAll() {
        //存放钉钉用户id的集合
        List<String> ddUserIds = new ArrayList<>();
        //获取系统所有部门列表
        List<SysDdDept> ddDeptListAll = ddDeptMapper.selectDdDeptList(new SysDdDept());
        for (SysDdDept ddDept : ddDeptListAll) {
            //循环查找每个部门的用户id列表
            OapiUserListidResponse.ListUserByDeptResponse ddUserIdList = dingUserUtils.getuserIdByDept(ddDept.getDdDeptId());
            List<String> useridList = ddUserIdList.getUseridList();
            if (useridList.size() > 0) {
                for (String ddUserId : useridList) {
                    if (!ddUserIds.contains(ddUserId)){
                        ddUserIds.add(ddUserId);
                    }
                }
            }
        }
        return ddUserIds;
    }

    /**
     * 下拉钉钉用户到系统
     * @return
     */
    @Override
    @Transactional
    public int addDdUser() {
        int i = 1;
        //查询所有级部
        List<Map<String, Object>> gradeList = ddDeptMapper.selectGradeList();
        //新增的用户的集合
        //用户表
        List<SysDdUser> userList = new ArrayList<>();
        //教师表
        List<SysDdTeacher> teacherList = new ArrayList<>();
        //获取钉钉全部用户id
        List<String> ddUserIdList = getDdUserListAll();
        for (String ddUserId : ddUserIdList) {
            //循环获取钉钉用户详情
            OapiV2UserGetResponse.UserGetResponse ddUser = dingUserUtils.getUser(ddUserId);

            //多部门任职信息
            List<OapiV2UserGetResponse.DeptPosition> deptPositionList = ddUser.getDeptPositionList();

            //用户部门列表
            List<Long> ddUserDepts = new ArrayList<>();
            //用户部门列表(用于判断是否是级部成员)
            List<Long> ddUserDepts1 = new ArrayList<>();

            //用户表数据
            SysDdUser sysDdUser = new SysDdUser();

            //设置主部门和任职部门
            if (deptPositionList.size()>0){
                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                    if (StringUtils.isNotNull(deptPosition.getIsMain())){
                        if (deptPosition.getIsMain()){
                            SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                            if (StringUtils.isNotNull(dept)){
                                sysDdUser.setDeptId(dept.getDeptId());
                                ddUserDepts1.add(dept.getDeptId());
                            }
                        }else {
                            SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                            if (StringUtils.isNotNull(dept1)){
                                ddUserDepts.add(dept1.getDeptId());
                                ddUserDepts1.add(dept1.getDeptId());
                            }
                        }
                    }else {
                        SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                        if (StringUtils.isNotNull(dept)){
                            ddUserDepts.add(dept.getDeptId());
                            ddUserDepts1.add(dept.getDeptId());
                        }
                    }
                }
            }
            if (StringUtils.isNull(sysDdUser.getDeptId())){
                sysDdUser.setDeptId(ddUserDepts.get(0));
                ddUserDepts.remove(ddUserDepts.get(0));
            }
            sysDdUser.setDdUserDepts(ddUserDepts);
            sysDdUser.setLoginName(ddUser.getName());
            sysDdUser.setPassword(SecurityUtils.encryptPassword("Ez2023@345"));
            sysDdUser.setUserName(ddUser.getName());
            sysDdUser.setUserType("00");
            sysDdUser.setUserLoginType("0");
            sysDdUser.setPhonenumber(ddUser.getMobile());
            sysDdUser.setCreateBy("钉钉管理员");
            sysDdUser.setUnionId(ddUser.getUnionid());
            sysDdUser.setDdUserId(ddUser.getUserid());
            if (StringUtils.isNotEmpty(ddUser.getEmail())){
                sysDdUser.setEmail(ddUser.getEmail());
            }
            if (StringUtils.isNotEmpty(ddUser.getAvatar())){
                sysDdUser.setAvatar(ddUser.getAvatar());
            }
            if (StringUtils.isNotEmpty(ddUser.getRemark())){
                sysDdUser.setRemark(ddUser.getRemark());
            }
            ddUserMapper.insertDdUser(sysDdUser);
            userList.add(sysDdUser);

            //新增教师数据
            SysDdTeacher sysDdTeacher = new SysDdTeacher();
            sysDdTeacher.setId(sysDdUser.getUserId());
            sysDdTeacher.setTeacherName(sysDdUser.getUserName());
            sysDdTeacher.setTeacherTel(sysDdUser.getPhonenumber());
            if (StringUtils.isNotEmpty(sysDdUser.getAvatar())){
                sysDdTeacher.setPicUrl(sysDdUser.getAvatar());
            }
            sysDdTeacher.setUnionId(sysDdUser.getUnionId());
            sysDdTeacher.setDdUserId(sysDdUser.getDdUserId());
            sysDdTeacher.setCreateBy("钉钉管理员");
            sysDdTeacher.setCreateTime(DateUtils.getNowDate());
            ddTeacherMapper.addTeacherList(sysDdTeacher);

            //判断用户是否为级部成员
            for (Long deptId : ddUserDepts1) {
                //根据部门id获取部门信息
                SysDdDept sysDdDept = ddDeptMapper.selectDeptByDeptId(deptId);
                //判断是否是年级部成员
                if ("年级部".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }

                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("1");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
                //判断是否是学科组长成员
                if ("学科组长".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }
                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("2");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
            }
        }
        //新增用户和部门关系
        for (SysDdUser ddUser : userList) {
            SysDdUserDept sysDdUserDept = new SysDdUserDept();
            sysDdUserDept.setUserId(ddUser.getUserId());
            for (Long ddUserDept : ddUser.getDdUserDepts()) {
                sysDdUserDept.setDeptId(ddUserDept);
                ddUserMapper.insertDdUserDept(sysDdUserDept);
            }
        }
        return i;
    }

    /**
     * 用户表数据新增到教师表
     */
    @Override
    public int addDdTeacher() {
        //查询所有用户
        List<SysDdUser> userList = ddUserMapper.selectDdUserList(new SysDdUser());
        for (SysDdUser ddUser : userList) {

        }
        return 1;
    }

    /**
     * 同步钉钉用户列表
     * @return
     */
    @Override
    @Transactional
    public String syncDdUser() {
        //查询所有级部
        List<Map<String, Object>> gradeList = ddDeptMapper.selectGradeList();
        //获取钉钉全部用户id
        List<String> ddUserIdList = getDdUserListAll();
        //获取钉钉全部用户详情
        List<OapiV2UserGetResponse.UserGetResponse> ddUserAll = new ArrayList<>();
        //存放钉钉用户不存在系统库的用户id
        List<String> ddUserIdList1 = new ArrayList<>();
        ddUserIdList1.addAll(ddUserIdList);

        //循环获取所有用户详情
        for (String ddUserId : ddUserIdList) {
            OapiV2UserGetResponse.UserGetResponse ddUser = dingUserUtils.getUser(ddUserId);
            ddUserAll.add(ddUser);
        }

        //获取系统全部用户
        List<SysDdUser> userList = ddUserMapper.selectDdUserList(new SysDdUser());
        //存放钉钉已删除的用户集合
        List<SysDdUser> userList1 = new ArrayList<>();
        userList1.addAll(userList);

        //获取所有部门
        List<SysDdDept> deptList = ddDeptMapper.selectDdDeptList(new SysDdDept());

        //判断系统用户列表是否存在钉钉用户id
        for (String ddUserId : ddUserIdList) {
            for (SysDdUser ddUser : userList) {
                if (ddUserId.equals(ddUser.getDdUserId())){
                    //存在，从集合中剔除
                    ddUserIdList1.remove(ddUserId);
                }
            }
        }
        //新增系统不存在的钉钉用户
        if(ddUserIdList1.size() > 0){
            for (String ddUserId : ddUserIdList1) {
                for (OapiV2UserGetResponse.UserGetResponse ddUser : ddUserAll) {
                    if (ddUserId.equals(ddUser.getUserid())){

                        //多部门任职信息
                        List<OapiV2UserGetResponse.DeptPosition> deptPositionList = ddUser.getDeptPositionList();

                        //用户部门列表
                        List<Long> ddUserDepts = new ArrayList<>();
                        //用户部门列表(用于判断是否是级部成员)
                        List<Long> ddUserDepts1 = new ArrayList<>();
                        //根据钉钉部门id查询部门信息
                        //新增用户到用户表
                        SysDdUser sysDdUser = new SysDdUser();

                        //设置主部门和任职部门
                        if (deptPositionList.size()>0){
                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                if (StringUtils.isNotNull(deptPosition.getIsMain()) && deptPosition.getIsMain()){
                                    SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                                    if (StringUtils.isNotNull(dept)){
                                        sysDdUser.setDeptId(dept.getDeptId());
                                        ddUserDepts1.add(dept.getDeptId());
                                    }
                                }else {
                                    SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                                    if (StringUtils.isNotNull(dept1)){
                                        ddUserDepts.add(dept1.getDeptId());
                                        ddUserDepts1.add(dept1.getDeptId());
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNull(sysDdUser.getDeptId())){
                            sysDdUser.setDeptId(ddUserDepts1.get(0));
                            ddUserDepts.remove(ddUserDepts1.get(0));
                        }
                        sysDdUser.setDdUserDepts(ddUserDepts);
                        sysDdUser.setLoginName(ddUser.getName());
                        sysDdUser.setPassword(SecurityUtils.encryptPassword("Ez2023@345"));
                        sysDdUser.setUserName(ddUser.getName());
                        sysDdUser.setUserType("00");
                        sysDdUser.setUserLoginType("0");
                        sysDdUser.setPhonenumber(ddUser.getMobile());
                        sysDdUser.setCreateBy("钉钉管理员");
                        sysDdUser.setUnionId(ddUser.getUnionid());
                        sysDdUser.setDdUserId(ddUser.getUserid());
                        if (StringUtils.isNotEmpty(ddUser.getEmail())){
                            sysDdUser.setEmail(ddUser.getEmail());
                        }
                        if (StringUtils.isNotEmpty(ddUser.getAvatar())){
                            sysDdUser.setAvatar(ddUser.getAvatar());
                        }
                        if (StringUtils.isNotEmpty(ddUser.getRemark())){
                            sysDdUser.setRemark(ddUser.getRemark());
                        }
                        ddUserMapper.insertDdUser(sysDdUser);

                        //新增用户和部门关系
                        SysDdUserDept sysDdUserDept = new SysDdUserDept();
                        sysDdUserDept.setUserId(sysDdUser.getUserId());
                        for (Long ddUserDept : sysDdUser.getDdUserDepts()) {
                            sysDdUserDept.setDeptId(ddUserDept);
                            ddUserMapper.insertDdUserDept(sysDdUserDept);
                        }

                        //新增用户到教师表
                        SysDdTeacher sysDdTeacher = new SysDdTeacher();
                        sysDdTeacher.setId(sysDdUser.getUserId());
                        sysDdTeacher.setTeacherName(sysDdUser.getUserName());
                        sysDdTeacher.setTeacherTel(sysDdUser.getPhonenumber());
                        if (StringUtils.isNotEmpty(sysDdUser.getAvatar())){
                            sysDdTeacher.setPicUrl(sysDdUser.getAvatar());
                        }
                        sysDdTeacher.setUnionId(sysDdUser.getUnionId());
                        sysDdTeacher.setDdUserId(sysDdUser.getDdUserId());
                        sysDdTeacher.setCreateBy("钉钉管理员");
                        sysDdTeacher.setCreateTime(DateUtils.getNowDate());
                        ddTeacherMapper.addTeacherList(sysDdTeacher);

                        //判断用户是否是级部成员，如果是，新增到级部成员
                        for (Long deptId : ddUserDepts1) {
                            //根据部门id获取部门信息
                            SysDdDept sysDdDept = ddDeptMapper.selectDeptByDeptId(deptId);
                            //判断是否是年级部成员
                            if ("年级部".equals(sysDdDept.getDeptName())){
                                //是，查看父部门属于那个级部
                                SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                                for (Map<String, Object> grade : gradeList) {
                                    //级部id
                                    Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                                    //级部值
                                    String gradeYear = grade.get("gradeYear").toString();
                                    //判断父部门名称是否包含级部值
                                    if (parentDept.getDeptName().contains(gradeYear)){
                                        //包含，新增用户到该级部成员
                                        SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                                        //设置职位
                                        if (deptPositionList.size() > 0){
                                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                                if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                                    if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                                        schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                                    }else {
                                                        schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                                    }
                                                }
                                            }
                                        }
                                        schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                                        schoolGradeMentor.setGradeId(gradeId);
                                        schoolGradeMentor.setCreateBy("钉钉管理员");
                                        schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                                        schoolGradeMentor.setType("1");
                                        ddUserMapper.insertGradeMentor(schoolGradeMentor);
                                    }
                                }
                            }
                            //判断是否是学科组长成员
                            if ("学科组长".equals(sysDdDept.getDeptName())){
                                //是，查看父部门属于那个级部
                                SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                                for (Map<String, Object> grade : gradeList) {
                                    //级部id
                                    Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                                    //级部值
                                    String gradeYear = grade.get("gradeYear").toString();
                                    //判断父部门名称是否包含级部值
                                    if (parentDept.getDeptName().contains(gradeYear)){
                                        //包含，新增用户到该级部成员
                                        SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                                        //设置职位
                                        if (deptPositionList.size() > 0){
                                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                                if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                                    if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                                        schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                                    }else {
                                                        schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                                    }
                                                }
                                            }
                                        }
                                        schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                                        schoolGradeMentor.setGradeId(gradeId);
                                        schoolGradeMentor.setCreateBy("钉钉管理员");
                                        schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                                        schoolGradeMentor.setType("2");
                                        ddUserMapper.insertGradeMentor(schoolGradeMentor);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //判断钉钉已删除的用户
        for (SysDdUser ddUser : userList) {
            for (String ddUserId : ddUserIdList) {
                if (ddUserId.equals(ddUser.getDdUserId())){
                    //存在从集合中剔除
                    userList1.remove(ddUser);
                }
            }
        }
        //删除钉钉中已删除的用户
        if (userList1.size() > 0){
            for (SysDdUser ddUser : userList1) {
                //删除用户
                ddUserMapper.deleteDdUser(ddUser.getUserId());
                //删除用户和部门关系
                ddUserMapper.deleteDdUserDept(ddUser.getUserId());
                //删除教师
                ddUserMapper.deleteDdTeacher(ddUser.getUserId());
                //删除级部成员信息
                ddUserMapper.deleteGradeMentor(ddUser.getUserId());
            }
        }

        //更新系统用户信息
        for (OapiV2UserGetResponse.UserGetResponse ddUser : ddUserAll) {
            for (SysDdUser sysDdUser : userList) {
                if (ddUser.getUserid().equals(sysDdUser.getDdUserId())){
                    //多部门任职信息
                    List<OapiV2UserGetResponse.DeptPosition> deptPositionList = ddUser.getDeptPositionList();
                    //系统用户部门列表
                    List<Long> ddUserDepts = ddUserMapper.selectDeptIdByUserId(sysDdUser.getUserId());
                    //存放钉钉部门id列表
                    List<Long> ddDeptIds = new ArrayList<>();
                    for (Long ddUserDept : ddUserDepts) {
                        for (SysDdDept dept : deptList) {
                            if (ddUserDept.equals(dept.getDeptId())){
                                ddDeptIds.add(dept.getDdDeptId());
                            }
                        }
                    }
                    //钉钉用户部门id列表
                    List<Long> deptIdList = ddUser.getDeptIdList();
                    //钉钉用户部门id列表(不包含钉钉已删除的部门)
                    List<Long> deptIdList1 = new ArrayList<>();
                    deptIdList1.addAll(deptIdList);
                    //去除掉钉钉已删除的部门id
                    for (Long ddUserDeptId : deptIdList) {
                        SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(ddUserDeptId);
                        if (StringUtils.isNull(dept1)){
                            deptIdList1.remove(ddUserDeptId);
                        }
                    }
                    //更新的部门id列表
                    List<Long> deptIds = new ArrayList<>();
                    //更新的部门id列表（用于判断是否是级部成员）
                    List<Long> deptIds1 = new ArrayList<>();
                    //判断系统用户和钉钉用户部门是否发生改变
                    boolean isEqual = ddDeptIds.containsAll(deptIdList1) && deptIdList1.containsAll(ddDeptIds);
                    if (!isEqual) {
                        //发生改变更新用户信息
                        //设置主部门和任职部门
                        if (deptPositionList.size()>0){
                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                if (StringUtils.isNotNull(deptPosition.getIsMain()) && deptPosition.getIsMain()){
                                    SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                                    if (StringUtils.isNotNull(dept)){
                                        sysDdUser.setDeptId(dept.getDeptId());
                                        deptIds1.add(dept.getDeptId());
                                    }
                                }else {
                                    SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                                    if (StringUtils.isNotNull(dept1)){
                                        deptIds.add(dept1.getDeptId());
                                        deptIds1.add(dept1.getDeptId());
                                    }
                                }
                            }
                        }
                        if (!deptIds1.contains(sysDdUser.getDeptId())){
                            sysDdUser.setDeptId(deptIds1.get(0));
                            deptIds.remove(deptIds1.get(0));
                        }
                        //删除原用户与部门关系
                        ddUserMapper.deleteDdUserDept(sysDdUser.getUserId());
                        //删除级部成员信息
                        ddUserMapper.deleteGradeMentor(sysDdUser.getUserId());

                        SysDdUserDept sysDdUserDept = new SysDdUserDept();
                        sysDdUserDept.setUserId(sysDdUser.getUserId());
                        for (Long ddUserDept : deptIds) {
                            sysDdUserDept.setDeptId(ddUserDept);
                            ddUserMapper.insertDdUserDept(sysDdUserDept);
                        }
                        for (Long ddUserDept : deptIds1){
                            //根据部门id获取部门信息
                            SysDdDept sysDdDept = ddDeptMapper.selectDeptByDeptId(ddUserDept);
                            //判断是否是年级部成员
                            if ("年级部".equals(sysDdDept.getDeptName())){
                                //是，查看父部门属于那个级部
                                SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                                for (Map<String, Object> grade : gradeList) {
                                    //级部id
                                    Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                                    //级部值
                                    String gradeYear = grade.get("gradeYear").toString();
                                    //判断父部门名称是否包含级部值
                                    if (parentDept.getDeptName().contains(gradeYear)){
                                        //包含，新增用户到该级部成员
                                        SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                                        //设置职位
                                        if (deptPositionList.size() > 0){
                                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                                if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                                    if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                                        schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                                    }else {
                                                        schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                                    }
                                                }
                                            }
                                        }
                                        schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                                        schoolGradeMentor.setGradeId(gradeId);
                                        schoolGradeMentor.setCreateBy("钉钉管理员");
                                        schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                                        schoolGradeMentor.setType("1");
                                        ddUserMapper.insertGradeMentor(schoolGradeMentor);
                                    }
                                }
                            }
                            //判断是否是学科组长成员
                            if ("学科组长".equals(sysDdDept.getDeptName())){
                                //是，查看父部门属于那个级部
                                SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                                for (Map<String, Object> grade : gradeList) {
                                    //级部id
                                    Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                                    //级部值
                                    String gradeYear = grade.get("gradeYear").toString();
                                    //判断父部门名称是否包含级部值
                                    if (parentDept.getDeptName().contains(gradeYear)){
                                        //包含，新增用户到该级部成员
                                        SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                                        //设置职位
                                        if (deptPositionList.size() > 0){
                                            for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                                if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                                    if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                                        schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                                    }else {
                                                        schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                                    }
                                                }
                                            }
                                        }
                                        schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                                        schoolGradeMentor.setGradeId(gradeId);
                                        schoolGradeMentor.setCreateBy("钉钉管理员");
                                        schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                                        schoolGradeMentor.setType("2");
                                        ddUserMapper.insertGradeMentor(schoolGradeMentor);
                                    }
                                }
                            }
                        }
                        sysDdUser.setUpdateBy("钉钉管理员");
                        ddUserMapper.updateDdUser(sysDdUser);
                    }
                    //更新系统用户信息
                    sysDdUser.setUserName(ddUser.getName());
                    sysDdUser.setLoginName(ddUser.getName());
                    sysDdUser.setPhonenumber(ddUser.getMobile());
                    if (StringUtils.isNotEmpty(ddUser.getEmail())){
                        sysDdUser.setEmail(ddUser.getEmail());
                    }
                    if (StringUtils.isNotEmpty(ddUser.getAvatar())){
                        sysDdUser.setAvatar(ddUser.getAvatar());
                    }
                    if (StringUtils.isNotEmpty(ddUser.getRemark())){
                        sysDdUser.setRemark(ddUser.getRemark());
                    }
                    sysDdUser.setUpdateBy("钉钉管理员");
                    ddUserMapper.updateDdUser(sysDdUser);
                    //更新系统教师信息
                    SysDdTeacher sysDdTeacher = new SysDdTeacher();
                    sysDdTeacher.setId(sysDdUser.getUserId());
                    sysDdTeacher.setTeacherName(sysDdUser.getUserName());
                    sysDdTeacher.setTeacherTel(sysDdUser.getPhonenumber());
                    if (StringUtils.isNotEmpty(sysDdUser.getAvatar())){
                        sysDdTeacher.setPicUrl(sysDdUser.getAvatar());
                    }
                    sysDdTeacher.setUpdateBy("钉钉管理员");
                    sysDdTeacher.setUpdateTime(DateUtils.getNowDate());
                    ddTeacherMapper.updateDdTeacher(sysDdTeacher);
                }
            }
        }
        return "同步成功";
    }

    /**
     * 处理通讯录用户增加
     * @param eventJson
     * @return
     */
    @Override
    @Transactional
    public int addUser(JSONObject eventJson) {
        int i = 0;
        String ddUserId = eventJson.getString("UserId");
        String replace = ddUserId.replace("[\"", "");
        String userIds = replace.replace("\"]", "");
        String[] split = userIds.split(",");
        //查询所有级部
        List<Map<String, Object>> gradeList = ddDeptMapper.selectGradeList();
        for (String userId : split) {
            //查询钉钉用户详情
            OapiV2UserGetResponse.UserGetResponse ddUser = dingUserUtils.getUser(userId);
            //钉钉用户部门列表
            List<Long> deptIdList = ddUser.getDeptIdList();
            for (Long ddDeptId : deptIdList) {
                //查询部门详情
                OapiV2DepartmentGetResponse.DeptGetResponse dept = dingDeptUtils.getDept(ddDeptId, "");
                if (dept.getName().equals("学生") || dept.getName().equals("家长")){
                    return 1;
                }
            }
            //多部门任职信息
            List<OapiV2UserGetResponse.DeptPosition> deptPositionList = ddUser.getDeptPositionList();
            //钉钉用户的钉钉部门id列表

            //用户系统部门id列表
            List<Long> ddUserDepts = new ArrayList<>();
            //用户系统部门id列表(用于判断是否是级部成员)
            List<Long> ddUserDepts1 = new ArrayList<>();

            //用户表数据
            SysDdUser sysDdUser = new SysDdUser();

            //设置主部门和任职部门
            if (deptPositionList.size()>0){
                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                    if (StringUtils.isNotNull(deptPosition.getIsMain()) && deptPosition.getIsMain()){
                        SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                        if (StringUtils.isNotNull(dept)){
                            sysDdUser.setDeptId(dept.getDeptId());
                            ddUserDepts1.add(dept.getDeptId());
                        }
                    }else {
                        SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                        if (StringUtils.isNotNull(dept1)){
                            ddUserDepts.add(dept1.getDeptId());
                            ddUserDepts1.add(dept1.getDeptId());
                        }
                    }
                }
            }
            if (StringUtils.isNull(sysDdUser.getDeptId())){
                sysDdUser.setDeptId(ddUserDepts1.get(0));
                ddUserDepts.remove(ddUserDepts1.get(0));
            }

            sysDdUser.setDdUserDepts(ddUserDepts);
            sysDdUser.setLoginName(ddUser.getName());
            sysDdUser.setPassword(SecurityUtils.encryptPassword("Ez2023@345"));
            sysDdUser.setUserName(ddUser.getName());
            sysDdUser.setUserType("00");
            sysDdUser.setUserLoginType("0");
            sysDdUser.setPhonenumber(ddUser.getMobile());
            sysDdUser.setCreateBy("钉钉管理员");
            sysDdUser.setUnionId(ddUser.getUnionid());
            sysDdUser.setDdUserId(ddUser.getUserid());
            if (StringUtils.isNotEmpty(ddUser.getEmail())){
                sysDdUser.setEmail(ddUser.getEmail());
            }
            if (StringUtils.isNotEmpty(ddUser.getAvatar())){
                sysDdUser.setAvatar(ddUser.getAvatar());
            }
            if (StringUtils.isNotEmpty(ddUser.getRemark())){
                sysDdUser.setRemark(ddUser.getRemark());
            }
            i += ddUserMapper.insertDdUser(sysDdUser);
            //新增用户和部门关系
            SysDdUserDept sysDdUserDept = new SysDdUserDept();
            sysDdUserDept.setUserId(sysDdUser.getUserId());
            for (Long ddUserDept : sysDdUser.getDdUserDepts()) {
                sysDdUserDept.setDeptId(ddUserDept);
                ddUserMapper.insertDdUserDept(sysDdUserDept);
            }
            //新增教师表信息
            SysDdTeacher sysDdTeacher = new SysDdTeacher();
            sysDdTeacher.setId(sysDdUser.getUserId());
            sysDdTeacher.setTeacherName(sysDdUser.getUserName());
            sysDdTeacher.setTeacherTel(sysDdUser.getPhonenumber());
            if (StringUtils.isNotEmpty(sysDdUser.getAvatar())){
                sysDdTeacher.setPicUrl(sysDdUser.getAvatar());
            }
            sysDdTeacher.setUnionId(sysDdUser.getUnionId());
            sysDdTeacher.setDdUserId(sysDdUser.getDdUserId());
            sysDdTeacher.setCreateBy("钉钉管理员");
            sysDdTeacher.setCreateTime(DateUtils.getNowDate());
            ddTeacherMapper.addTeacherList(sysDdTeacher);

            //判断用户是否是级部成员，如果是，新增到级部成员
            for (Long deptId : ddUserDepts1) {
                //根据部门id获取部门信息
                SysDdDept sysDdDept = ddDeptMapper.selectDeptByDeptId(deptId);
                //判断是否是年级部成员
                if ("年级部".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }
                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("1");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
                //判断是否是学科组长成员
                if ("学科组长".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }
                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("2");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
            }
        }
        return i;
    }

    /**
     * 处理通讯录用户修改
     * @param eventJson
     * @return
     */
    @Override
    public int updateUser(JSONObject eventJson) {
        int i = 0;
        String ddUserId = eventJson.getString("UserId");
        String replace = ddUserId.replace("[\"", "");
        String userIds = replace.replace("\"]", "");
        String[] split = userIds.split(",");
        //查询所有级部
        List<Map<String, Object>> gradeList = ddDeptMapper.selectGradeList();
        for (String userId : split) {
            //查询钉钉用户详情
            OapiV2UserGetResponse.UserGetResponse ddUser = dingUserUtils.getUser(userId);
            //钉钉用户部门列表
            List<Long> deptIdList = ddUser.getDeptIdList();
            for (Long ddDeptId : deptIdList) {
                //查询部门详情
                OapiV2DepartmentGetResponse.DeptGetResponse dept = dingDeptUtils.getDept(ddDeptId, "");
                if (dept.getName().equals("学生") || dept.getName().equals("家长")){
                    return 1;
                }
            }
            //查询系统用户详情
            SysDdUser sysDdUser = ddUserMapper.selectDdUserByDdUserId(userId);
            //多部门任职信息
            List<OapiV2UserGetResponse.DeptPosition> deptPositionList = ddUser.getDeptPositionList();
            //用户系统部门id列表
            List<Long> ddUserDepts = new ArrayList<>();
            //用户系统部门id列表(用于判断是否是级部成员)
            List<Long> ddUserDepts1 = new ArrayList<>();

            //设置主部门和任职部门
            if (deptPositionList.size()>0){
                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                    if (StringUtils.isNotNull(deptPosition.getIsMain()) && deptPosition.getIsMain()){
                        SysDdDept dept = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                        if (StringUtils.isNotNull(dept)){
                            sysDdUser.setDeptId(dept.getDeptId());
                            ddUserDepts1.add(dept.getDeptId());
                        }
                    }else {
                        SysDdDept dept1 = ddDeptMapper.selectDeptByDdDeptId(deptPosition.getDeptId());
                        if (StringUtils.isNotNull(dept1)){
                            ddUserDepts.add(dept1.getDeptId());
                            ddUserDepts1.add(dept1.getDeptId());
                        }
                    }
                }
            }
            if (!ddUserDepts1.contains(sysDdUser.getDeptId())){
                sysDdUser.setDeptId(ddUserDepts1.get(0));
                ddUserDepts.remove(ddUserDepts1.get(0));
            }

            //删除原用户与部门关系
            ddUserMapper.deleteDdUserDept(sysDdUser.getUserId());
            //删除级部成员信息
            ddUserMapper.deleteGradeMentor(sysDdUser.getUserId());
            //新增新用户与部门关系
            SysDdUserDept sysDdUserDept = new SysDdUserDept();
            sysDdUserDept.setUserId(sysDdUser.getUserId());
            for (Long ddUserDept : ddUserDepts) {
                sysDdUserDept.setDeptId(ddUserDept);
                ddUserMapper.insertDdUserDept(sysDdUserDept);
            }
            for (Long ddUserDept : ddUserDepts1) {

                //根据部门id获取部门信息
                SysDdDept sysDdDept = ddDeptMapper.selectDeptByDeptId(ddUserDept);
                //判断是否是年级部成员
                if ("年级部".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }
                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("1");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
                //判断是否是学科组长成员
                if ("学科组长".equals(sysDdDept.getDeptName())){
                    //是，查看父部门属于那个级部
                    SysDdDept parentDept = ddDeptMapper.selectDeptByDeptId(sysDdDept.getParentId());
                    for (Map<String, Object> grade : gradeList) {
                        //级部id
                        Long gradeId = Long.parseLong(grade.get("gradeId").toString());
                        //级部值
                        String gradeYear = grade.get("gradeYear").toString();
                        //判断父部门名称是否包含级部值
                        if (parentDept.getDeptName().contains(gradeYear)){
                            //包含，新增用户到该级部成员
                            SchoolGradeMentorCopy schoolGradeMentor = new SchoolGradeMentorCopy();
                            //设置职位
                            if (deptPositionList.size() > 0){
                                for (OapiV2UserGetResponse.DeptPosition deptPosition : deptPositionList) {
                                    if (deptPosition.getDeptId().equals(sysDdDept.getDdDeptId())){
                                        if (StringUtils.isNotEmpty(deptPosition.getTitle())){
                                            schoolGradeMentor.setTeacherPost(deptPosition.getTitle());
                                        }else {
                                            schoolGradeMentor.setTeacherPost(ddUser.getTitle());
                                        }
                                    }
                                }
                            }
                            schoolGradeMentor.setTeacherId(sysDdUser.getUserId());
                            schoolGradeMentor.setGradeId(gradeId);
                            schoolGradeMentor.setCreateBy("钉钉管理员");
                            schoolGradeMentor.setCreateTime(DateUtils.getNowDate());
                            schoolGradeMentor.setType("2");
                            ddUserMapper.insertGradeMentor(schoolGradeMentor);
                        }
                    }
                }
            }
            //更新系统用户信息
            sysDdUser.setDeptId(ddUserDepts.get(0));
            sysDdUser.setUserName(ddUser.getName());
            sysDdUser.setLoginName(ddUser.getName());
            sysDdUser.setPhonenumber(ddUser.getMobile());
            sysDdUser.setUpdateBy("钉钉管理员");
            if (StringUtils.isNotEmpty(ddUser.getEmail())){
                sysDdUser.setEmail(ddUser.getEmail());
            }
            if (StringUtils.isNotEmpty(ddUser.getAvatar())){
                sysDdUser.setAvatar(ddUser.getAvatar());
            }
            if (StringUtils.isNotEmpty(ddUser.getRemark())){
                sysDdUser.setRemark(ddUser.getRemark());
            }
            i += ddUserMapper.updateDdUser(sysDdUser);
            //更新系统教师信息
            SysDdTeacher sysDdTeacher = new SysDdTeacher();
            sysDdTeacher.setId(sysDdUser.getUserId());
            sysDdTeacher.setTeacherName(sysDdUser.getUserName());
            sysDdTeacher.setTeacherTel(sysDdUser.getPhonenumber());
            if (StringUtils.isNotEmpty(sysDdUser.getAvatar())){
                sysDdTeacher.setPicUrl(sysDdUser.getAvatar());
            }
            sysDdTeacher.setUpdateBy("钉钉管理员");
            sysDdTeacher.setUpdateTime(DateUtils.getNowDate());
            ddTeacherMapper.updateDdTeacher(sysDdTeacher);
        }
        return i;
    }

    /**
     * 处理通讯录用户离职
     * @param eventJson
     * @return
     */
    @Override
    public int leaveUser(JSONObject eventJson) {
        int i = 0;
        String ddUserId = eventJson.getString("UserId");
        String replace = ddUserId.replace("[\"", "");
        String userIds = replace.replace("\"]", "");
        String[] split = userIds.split(",");
        for (String userId : split) {
            //查询系统用户详情
            SysDdUser sysDdUser = ddUserMapper.selectDdUserByDdUserId(userId);
            //在用户表中删除用户
            i += ddUserMapper.deleteDdUser(sysDdUser.getUserId());
            //删除用户和部门关系
            i += ddUserMapper.deleteDdUserDept(sysDdUser.getUserId());
            //在教师表中删除用户
            i += ddUserMapper.deleteDdTeacher(sysDdUser.getUserId());
            //在级部成员表中删除用户
            i += ddUserMapper.deleteGradeMentor(sysDdUser.getUserId());
        }
        return i;
    }


    /**
     * 家校通讯录 人员身份新增
     */
    public int xjUserAdd(JSONObject eventJson){

        String userId = (String)eventJson.get("userId");
        String role =  (String)eventJson.get("role");
        String name =  (String)eventJson.get("name");
        Integer classId = (Integer) eventJson.get("classId");
        String featureSt = (String) eventJson.get("feature");
        JSONObject feature = JSONObject.parseObject(featureSt);
        //根据ddclassId 查找班级
        Long l = iSchoolClassService.selectDdClassId(String.valueOf(classId));
        //判断该当前的角色
        if (teacher.equals(role)){
            //老师
            // 只在老师角色下意义。 1：班主任 0：非班主任
            Integer isAdviser = (Integer)feature.get("isAdviser");
            //查询老师表
            SchoolTeacher schoolTeacher = teacherMapper.selectTeacherByDdUerId(userId);
            if (null == schoolTeacher){
                log.warn("新增老师:"+name+",未在系统中找到不做处理跳过");
                return 0;
            }
            //判断是否是班主任
            if ("1".equals(isAdviser)){
                //班主任
                //当前老师是班主任 记录班主任跟班级关系
                SchoolClassHeadmaster schoolClassHeadmaster = new SchoolClassHeadmaster();
                schoolClassHeadmaster.setTeacherId(schoolTeacher.getId());
                schoolClassHeadmaster.setClassId(l);
                iSchoolClassHeadmasterService.save(schoolClassHeadmaster);
                //设置班级 班主任信息
                SchoolClass schoolClassss = new SchoolClass();
                schoolClassss.setId(l);
                schoolClassss.setTeacherId(schoolTeacher.getId());
                schoolClassss.setTeacherName(schoolTeacher.getTeacherName());
                schoolClassss.setTeacherTel(schoolTeacher.getTeacherTel());
                iSchoolClassService.updateById(schoolClassss);
            }else {
                //任课老师
                //查找部门
                SysUser sysUser = sysUserService.selectUserById(schoolTeacher.getId());
                String deptName = sysUser.getDept().getDeptName();
                //根据部门查找课程信息
                SchoolCurriculum schoolCurriculum = schoolCurriculumMapper.selectCourseName(deptName);
                //任课老师 跟班级关系
                SchoolClassMentor schoolClassMentor = new SchoolClassMentor();
                schoolClassMentor.setTeacherId(schoolTeacher.getId());
                schoolClassMentor.setClassId(l);
                schoolClassMentor.setCourseName(schoolCurriculum.getCourseName());
                schoolClassMentor.setCourseId(schoolCurriculum.getId());
                schoolClassMentorService.save(schoolClassMentor);
            }
        }else if (student.equals(role)){
            //学生
            //学生信息
            SchoolStudent schoolStudent = new SchoolStudent();
            schoolStudent.setStudentName(name);
            schoolStudent.setClassId(l);
            schoolStudent.setStudentStatus("1");
            schoolStudent.setDdUserId(userId);
            schoolStudentService.save(schoolStudent);
            //学生班级信息
            SchoolStudentClassRelation schoolStudentClassRelation = new SchoolStudentClassRelation();
            schoolStudentClassRelation.setStudentId(schoolStudent.getId());
            schoolStudentClassRelation.setClassId(l);
            iSchoolStudentClassRelationService.save(schoolStudentClassRelation);
            //学生与班级历史关系
            SchoolClass school= iSchoolClassService.selectSchoolClassById(l);
            SchoolStudentClasses schoolStudentClasses = new SchoolStudentClasses();
            schoolStudentClasses.setStudentId(schoolStudent.getId());
            schoolStudentClasses.setGrade(school.getGradeName());
            schoolStudentClasses.setClasses(school.getClassName());
            schoolStudentClasses.setTeacherName(school.getTeacherName());
            schoolStudentClassesService.save(schoolStudentClasses);

        }else if (guardian.equals(role)){
            //家长
                //找寻学生
            String token = accessTokenUtils.getToken();
            String toUserId = this.getToUserId(token, userId, classId.toString());
            Long ddUserId = schoolStudentService.getDdUserId(toUserId);
            String tel = this.getTel(userId, token);
            //创建用户user表
                SysUser jUser = new SysUser();
                jUser.setLoginName(name);
                jUser.setUserName(name);
                jUser.setUserType("01");
                jUser.setUserLoginType("1");
                jUser.setPhonenumber(this.getTel(userId,token));
                jUser.setPassword(SecurityUtils.encryptPassword("123#@!"));
                jUser.setStatus("0");
                jUser.setDelFlag("0");
                jUser.setDdUserId(userId);
                jUser.setRoleIds(new Long[]{111L});
                jUser.setStudentId(ddUserId);
                sysUserService.insertUser(jUser);
                //家长表
                SchoolStudentParent schoolStudentParent = new SchoolStudentParent() ;
                schoolStudentParent.setStudentId(ddUserId);
                schoolStudentParent.setUserId(jUser.getUserId());
                schoolStudentParent.setParentName(name);
                schoolStudentParent.setTelephone(tel);
                Integer patriarch = this.getPatriarch(name.substring(name.length() - 2));
                schoolStudentParent.setRelationship(String.valueOf(patriarch));
            iSchoolStudentParentService.save(schoolStudentParent);
        }
        return 0;
    }


    /**
     * 删除信息
     * @param eventJson
     * @return
     */

    public Integer xjUserDelete(JSONObject eventJson){
        String userId = (String)eventJson.get("userId");
        String role =  (String)eventJson.get("role");
        String name =  (String)eventJson.get("name");
        Integer classId = (Integer) eventJson.get("classId");
        String featureSt = (String) eventJson.get("feature");
        JSONObject feature = JSONObject.parseObject(featureSt);

        //根据ddclassId 查找班级
        Long l = iSchoolClassService.selectDdClassId(String.valueOf(classId));
        //判断该当前的角色
        if (teacher.equals(role)){
            //老师
            // 只在老师角色下意义。 1：班主任 0：非班主任
            Integer isAdviser = (Integer)feature.get("isAdviser");
            //查询老师表
            SchoolTeacher schoolTeacher = teacherMapper.selectTeacherByDdUerId(userId);
            if (null == schoolTeacher){
                log.warn("删除老师:"+name+",未在系统中找到不做处理跳过");
                return 0;
            }
            //判断是否是班主任
            if ("1".equals(isAdviser)){
                //班主任
                //当前老师是班主任 记录班主任跟班级关系   删除
                LambdaQueryWrapper<SchoolClassHeadmaster> lqw=new LambdaQueryWrapper<>();
                lqw.eq(SchoolClassHeadmaster::getTeacherId,schoolTeacher.getId());
                lqw.eq(SchoolClassHeadmaster::getClassId,l);
                iSchoolClassHeadmasterService.remove(lqw);
                //设置班级 班主任信息 设置为null
                SchoolClass schoolClassss = new SchoolClass();
                schoolClassss.setId(l);
                schoolClassss.setTeacherId(null);
                schoolClassss.setTeacherName(null);
                schoolClassss.setTeacherTel(null);
                iSchoolClassService.updateById(schoolClassss);
            }else {
                //任课老师
                //查找部门
                SysUser sysUser = sysUserService.selectUserById(schoolTeacher.getId());
                String deptName = sysUser.getDept().getDeptName();
                //根据部门查找课程信息
                SchoolCurriculum schoolCurriculum = schoolCurriculumMapper.selectCourseName(deptName);
                //任课老师 跟班级关系
                LambdaQueryWrapper<SchoolClassMentor> lqw=new LambdaQueryWrapper<>();
                lqw.eq(SchoolClassMentor::getTeacherId,schoolTeacher.getId());
                lqw.eq(SchoolClassMentor::getClassId,l);
                lqw.eq(SchoolClassMentor::getCourseName,schoolCurriculum.getCourseName());
                lqw.eq(SchoolClassMentor::getCourseId,schoolCurriculum.getId());
                schoolClassMentorService.remove(lqw);
            }
        }else if (student.equals(role)){
            //学生
            Long ddUserId = schoolStudentService.getDdUserId(userId);
            //学生信息  删除
            LambdaQueryWrapper<SchoolStudent> lqw=new LambdaQueryWrapper<>();
            lqw.eq(SchoolStudent::getDdUserId,userId);
            schoolStudentService.remove(lqw);

            //学生班级信息
            LambdaQueryWrapper<SchoolStudentClassRelation> crlqw=new LambdaQueryWrapper<>();
            crlqw.eq(SchoolStudentClassRelation::getStudentId,ddUserId);
            crlqw.eq(SchoolStudentClassRelation::getClassId,l);
            iSchoolStudentClassRelationService.remove(crlqw);

            //学生与班级历史关系
            SchoolClass school= iSchoolClassService.selectSchoolClassById(l);
            LambdaQueryWrapper<SchoolStudentClasses> icsclqw=new LambdaQueryWrapper<>();
            icsclqw.eq(SchoolStudentClasses::getStudentId,ddUserId);
            icsclqw.eq(SchoolStudentClasses::getGrade,school.getGradeName());
            icsclqw.eq(SchoolStudentClasses::getClasses,school.getClassName());
            icsclqw.eq(SchoolStudentClasses::getTeacherName,school.getTeacherName());
            schoolStudentClassesService.remove(icsclqw);

        }else if (guardian.equals(role)){
            //家长
            //删除用户家长表
            SysUser sysUser = sysUserService.selectUserByDdUserId(userId);
            sysUserService.deleteUserById(sysUser.getUserId());
            // 删除家长表
            LambdaQueryWrapper<SchoolStudentParent> jzlqw=new LambdaQueryWrapper<>();
            jzlqw.eq(SchoolStudentParent::getUserId,sysUser.getUserId());
            jzlqw.eq(SchoolStudentParent::getStudentId,sysUser.getStudentId());
            jzlqw.eq(SchoolStudentParent::getParentName,name);
            jzlqw.eq(SchoolStudentParent::getTelephone,sysUser.getPhonenumber());
            iSchoolStudentParentService.remove(jzlqw);
        }
        return 0;
    }


    /**
     * 钉钉用户修改
     * 这里用户修改只针对学生与家长信息变更，老师的增加与删除都是走新增删除逻辑
     * @param eventJson
     * @return
     */
    public Integer xjUserUpdate(JSONObject eventJson){
        String userId = (String)eventJson.get("userId");
        String role =  (String)eventJson.get("role");
        String name =  (String)eventJson.get("name");
        Integer classId = (Integer) eventJson.get("classId");
        String featureSt = (String) eventJson.get("feature");
        JSONObject feature = JSONObject.parseObject(featureSt);
        //根据ddclassId 查找班级
        Long l = iSchoolClassService.selectDdClassId(String.valueOf(classId));
        //判断该当前的角色
           //学生信息只有手机号、学号 没有记录不做修改 ，学生改班级 都是删除、新增逻辑
         if (guardian.equals(role)){
            //家长
            //找寻学生
            String token = accessTokenUtils.getToken();
             SysUser sysUser = sysUserService.selectUserByDdUserId(userId);
             String tel = this.getTel(userId, token);
            //更新用户user表
             sysUser.setLoginName(name);
             sysUser.setUserName(name);
             sysUser.setPhonenumber(this.getTel(userId,token));
             sysUser.setDdUserId(userId);
             sysUserService.updateUser(sysUser);
            //家长表 修改手机号
             LambdaQueryWrapper<SchoolStudentParent> lqw=new LambdaQueryWrapper<>();
             lqw.eq(SchoolStudentParent::getUserId,sysUser.getUserId());
             lqw.eq(SchoolStudentParent::getStudentId,sysUser.getStudentId());
             SchoolStudentParent one = iSchoolStudentParentService.getOne(lqw);
             one.setTelephone(tel);
            iSchoolStudentParentService.updateById(one);
        }
        return 0;
    }

    /**
     * 人员关系新增
     * @param eventJson
     * @return
     */
    public Integer relationInsert(JSONObject eventJson){

        //家长id
        String userId = (String)eventJson.get("fromUserId");
        //孩子id
        String toUserId =  (String)eventJson.get("toUserId");
        //班级id
        Integer classId =  (Integer)eventJson.get("classId");
        //关系
        Integer relationCode = (Integer) eventJson.get("relationCode");
        //关系名称
        String relationName = (String) eventJson.get("relationName");

        //1.查询学生信息
        Long ddUserId = schoolStudentService.getDdUserId(toUserId);
        SchoolStudent studenUser = schoolStudentService.getById(ddUserId);
        //2.查询用户手机号
        String token = accessTokenUtils.getToken();
        //家长手机号
        String tel = this.getTel(userId, token);
        //3.保存用户信息
        //创建用户user表
        SysUser jUser = new SysUser();
        jUser.setLoginName(studenUser.getStudentName()+relationName);
        jUser.setUserName(studenUser.getStudentName()+relationName);
        jUser.setUserType("01");
        jUser.setUserLoginType("1");
        jUser.setPhonenumber(tel);
        jUser.setPassword(SecurityUtils.encryptPassword("123#@!"));
        jUser.setStatus("0");
        jUser.setDelFlag("0");
        jUser.setDdUserId(userId);
        jUser.setRoleIds(new Long[]{111L});
        jUser.setStudentId(Long.valueOf(toUserId));
        sysUserService.insertUser(jUser);
        //家长表
        SchoolStudentParent schoolStudentParent = new SchoolStudentParent() ;
        schoolStudentParent.setStudentId(studenUser.getId());
        schoolStudentParent.setUserId(jUser.getUserId());
        schoolStudentParent.setParentName(studenUser.getStudentName()+relationName);
        schoolStudentParent.setTelephone(tel);
        Integer patriarch = this.getPatriarch(relationName);
        schoolStudentParent.setRelationship(String.valueOf(patriarch));
        iSchoolStudentParentService.save(schoolStudentParent);
        return 0;
    }

    /**
     * 人员关系更新
     * @return
     */
    public Integer relationUpdate(JSONObject eventJson){

        //家长id
        String userId = (String)eventJson.get("fromUserId");
        //孩子id
        String toUserId =  (String)eventJson.get("toUserId");
        //班级id
        Integer classId =  (Integer)eventJson.get("classId");
        //关系
        Integer relationCode = (Integer) eventJson.get("relationCode");
        //关系名称
        String relationName = (String) eventJson.get("relationName");

        //1.查询学生信息
        Long ddUserId = schoolStudentService.getDdUserId(toUserId);
        SchoolStudent studenUser = schoolStudentService.getById(ddUserId);
        //2.查询用户手机号
        String token = accessTokenUtils.getToken();
        //家长
        SysUser sysUser = sysUserService.selectUserByDdUserId(userId);
        //家长手机号
        String tel = this.getTel(userId, token);
        //更新家长信息
        sysUser.setPhonenumber(tel);
        sysUser.setDdUserId(userId);
        sysUser.setStudentId(Long.valueOf(toUserId));
        sysUserService.updateUser(sysUser);
        //更新家长表
        LambdaQueryWrapper<SchoolStudentParent> jzlqw=new LambdaQueryWrapper<>();
        jzlqw.eq(SchoolStudentParent::getUserId,sysUser.getUserId());
        jzlqw.eq(SchoolStudentParent::getStudentId,studenUser.getId());
        jzlqw.eq(SchoolStudentParent::getParentName,studenUser.getStudentName()+relationName);
        jzlqw.eq(SchoolStudentParent::getTelephone,sysUser.getPhonenumber());
        SchoolStudentParent one = iSchoolStudentParentService.getOne(jzlqw);
        one.setTelephone(tel);
        iSchoolStudentParentService.updateById(one);
        return 0;
    }

    /**
     * 删除人员关系
     * @param eventJson
     * @return
     */
    public Integer relationDelete(JSONObject eventJson){
        //家长id
        String userId = (String)eventJson.get("fromUserId");
        //孩子id
        String toUserId =  (String)eventJson.get("toUserId");
        //班级id
        Integer classId =  (Integer)eventJson.get("classId");
        //关系
        Integer relationCode = (Integer) eventJson.get("relationCode");
        //关系名称
        String relationName = (String) eventJson.get("relationName");
        //1.查询学生信息
        Long ddUserId = schoolStudentService.getDdUserId(toUserId);
        SchoolStudent studenUser = schoolStudentService.getById(ddUserId);
        //家长
        SysUser sysUser = sysUserService.selectUserByDdUserId(userId);
        //删除家长用户信息
        sysUserService.deleteUserById(sysUser.getUserId());
        //删除家长表
        LambdaQueryWrapper<SchoolStudentParent> jzlqw=new LambdaQueryWrapper<>();
        jzlqw.eq(SchoolStudentParent::getUserId,sysUser.getUserId());
        jzlqw.eq(SchoolStudentParent::getStudentId,studenUser.getId());
        jzlqw.eq(SchoolStudentParent::getParentName,studenUser.getStudentName()+relationName);
        jzlqw.eq(SchoolStudentParent::getTelephone,sysUser.getPhonenumber());
        iSchoolStudentParentService.remove(jzlqw);
        return 0;
    }

    public String getToUserId(String token,String fromUserId,String classId){
        String toUserId = null;
        com.alibaba.fastjson2.JSONObject bjParme = new com.alibaba.fastjson2.JSONObject();
        bjParme.put("from_userid",fromUserId);
        bjParme.put("class_id",classId);
        String bjPost = HttpUtil.post("https://oapi.dingtalk.com/topapi/edu/user/relation/get?access_token="+token, bjParme);
        com.alibaba.fastjson2.JSONObject bjObject = com.alibaba.fastjson2.JSONObject.parseObject(bjPost);
        if ((Integer) bjObject.get("errcode") != 0){
            throw  new RuntimeException("获取学生id失败"+bjPost);
        }
        JSONArray jsonArray = bjObject.getJSONObject("result").getJSONArray("relations");
        for (int i= 0; i<  jsonArray.size();i++){
            toUserId =  jsonArray.getJSONObject(0).get("to_userid").toString();
        }
        return toUserId;
    }









    /**
     * 调用钉钉公共接口，获取用户手机号
     */
    public String getTel(String userId ,String assToKen){
        com.alibaba.fastjson2.JSONObject userParme = new com.alibaba.fastjson2.JSONObject();
        userParme.put("userid",userId);
        String userPost = HttpUtil.post("https://oapi.dingtalk.com/topapi/v2/user/get?access_token="+assToKen, userParme);
        com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(userPost);

        if (jsonObject.getJSONObject("result").get("mobile")==null){
            return null;
        }else {
            return jsonObject.getJSONObject("result").get("mobile").toString();
        }
    }

    private Integer getPatriarch(String patriarch){
        Integer gId = null;
        switch (patriarch){
            case  "爸爸": return gId = 0;
            case  "妈妈": return gId = 1;
            case  "爷爷": return gId = 2;
            case  "奶奶": return gId = 3;
            case  "叔叔": return gId = 4;
            case  "姑姑": return gId = 5;
            case  "外婆": return gId = 6;
            case  "外公": return gId = 7;
            case  "哥哥": return gId = 8;
            case  "姐姐": return gId = 9;
            case  "阿姨": return gId = 10;
            case  "家长": return gId = 11;
        }
        return gId;
    }
}
