package yangtz.cs.liu.dingding.controller;


import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.schoolgrade.SchoolGrade;
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.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.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
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.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherVO;
import yangtz.cs.liu.dingding.utils.AccessTokenUtils;
import yangtz.cs.liu.dingding.vo.DingJiaXiaoVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 家校通讯录
 */
@RestController
@RequestMapping("/dd/djtx")
public class DingJiaXiaoController {

    private static final Logger log = LoggerFactory.getLogger(DingJiaXiaoController.class);


    @Autowired
    private AccessTokenUtils accessTokenUtils;

    final String listUrl ="https://oapi.dingtalk.com/topapi/edu/dept/list?access_token=";

    final String userUrl ="https://oapi.dingtalk.com/topapi/edu/user/list?access_token=";

   //年级表
    @Autowired
   ISchoolGradeService schoolGradeService;


    //职工与年级关系 ----------------
    @Autowired
    ISchoolGradeMentorService schoolGradeMentorService;
    //学校班级
    @Autowired
    ISchoolClassService iSchoolClassService;
    //班主任和班级关系   ------------------
    @Autowired
    ISchoolClassHeadmasterService iSchoolClassHeadmasterService;
    //任课老师和班级关系 ----------------
    @Autowired
    ISchoolClassMentorService schoolClassMentorService;
    //学生表     ---------------------
    @Autowired
    ISchoolStudentService schoolStudentService;
    //学生与班级关系 --------------------
    @Autowired
    ISchoolStudentClassRelationService iSchoolStudentClassRelationService;
    //学生历史班级表    -----------------
    @Autowired
    ISchoolStudentClassesService schoolStudentClassesService;
    //家长信息表          ---------------------
    @Autowired
    ISchoolStudentParentService iSchoolStudentParentService;
    //老师表
    @Autowired
    ISchoolTeacherService schoolTeacherService;
    //用户表        ----------------
    @Autowired
    ISysUserService sysUserService;

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    SchoolCurriculumMapper schoolCurriculumMapper;


    public List<String> userTypes = new ArrayList<String>(){
        {
            this.add("teacher");
            this.add("student");
            this.add("guardian");
        }
    };



    //更新年级与班级
    @GetMapping("/updateLabClassYear")
    public String  updateLabClassYear(){
        String token = accessTokenUtils.getToken();
        //年级
        List<SchoolGrade> schoolGradeCopies = new ArrayList<>();
        // 0 获取校园信息
        JSONObject jsonObjectParme = new JSONObject();
        jsonObjectParme.put("page_no",1);
        jsonObjectParme.put("page_size",30);
        String post = HttpUtil.post(listUrl+token, jsonObjectParme);
        JSONObject jsonObject = JSONObject.parseObject(post);
        if ((Integer) jsonObject.get("errcode") != 0){
            throw  new RuntimeException("获取校园列表失败");
        }
        Integer deptId = null;
        JSONObject result = (JSONObject)jsonObject.get("result");
        JSONArray detailsArray = JSONArray.of(result.get("details"));
        for (int i = 0 ; i < detailsArray.size(); i ++){
            JSONObject da = detailsArray.getJSONArray(i).getJSONObject(i);
            deptId = (Integer) da.get("dept_id");
        }
        //1 获取校园学历类型
        JSONObject xyParme = new JSONObject();
        xyParme.put("page_no",1);
        xyParme.put("page_size",30);
        xyParme.put("super_id",deptId);
        String xyPost = HttpUtil.post(listUrl+token, xyParme);
        JSONObject xyObject = JSONObject.parseObject(xyPost);
        if ((Integer) xyObject.get("errcode") != 0){
            throw  new RuntimeException("获取年纪列表失败");
        }
        JSONObject xyResult = (JSONObject)xyObject.get("result");
        JSONArray xyDetailsArray = JSONArray.of(xyResult.get("details"));
        for (int i = 0 ; i < xyDetailsArray.size(); i ++){
            JSONObject da = xyDetailsArray.getJSONArray(i).getJSONObject(i);
            deptId = (Integer) da.get("dept_id");
        }
        //2.获取校园年级
        JSONObject njParme = new JSONObject();
        njParme.put("page_no",1);
        njParme.put("page_size",30);
        njParme.put("super_id",deptId);
        String njPost = HttpUtil.post(listUrl+token, njParme);
        JSONObject njObject = JSONObject.parseObject(njPost);
        if ((Integer) njObject.get("errcode") != 0){
            throw  new RuntimeException("获取年纪列表失败");
        }
        JSONObject njResult = (JSONObject)njObject.get("result");
        JSONArray njDetailsArray = JSONArray.of(njResult.get("details"));
        for (int i = 0 ; i < njDetailsArray.size(); i ++) {
            for (int q = 0; q < njDetailsArray.getJSONArray(i).size(); q++) {
                JSONObject da = njDetailsArray.getJSONArray(i).getJSONObject(q);
                String grName = (String) da.get("name");
                //截取级部 2022级
                String gradeJi = grName.substring(grName.length() - 5);
                String grade = gradeJi.substring(0,gradeJi.length()-1);
                //获取年级 一年级
                String  gradeName = grName.substring(0, grName.length() - 5);
                //级部id
                Integer suId = (Integer) da.get("dept_id");
                SchoolGrade schoolGrade = new SchoolGrade();
                schoolGrade.setGradeValue(Integer.valueOf(this.gradeSubt(gradeName)));
                schoolGrade.setGradeYear(grade);
                schoolGrade.setGradeName(gradeJi+"部");
                schoolGrade.setRemark(gradeName);
                schoolGrade.setDdClassId(String.valueOf(suId));
                schoolGrade.setCreateTime(new Date());
                schoolGrade.setCreateBy("admin");
                schoolGrade.setDelFlag("0");
                schoolGrade.setUpdateBy("admin");
                schoolGrade.setUpdateTime(new Date());
                schoolGradeCopies.add(schoolGrade);
            }
        }

        //对年级进行排序 找出最新年级 设则最新学年状态  并且找出班级 进行保存
        List<SchoolGrade> collect = schoolGradeCopies.stream().sorted(Comparator.comparing(SchoolGrade::getGradeYear, Comparator.reverseOrder())).collect(Collectors.toList());
        //最新学年
        String schoolYear = collect.get(0).getGradeYear();
        for (int i = 0; i < collect.size();i++) {
            collect.get(i).setSchoolYear(schoolYear);
            if (i >= 3){
                //当前第四个以上不是新学年 更新数据库新学年状态
                List<SchoolGrade> schoolGradeCopies1 = schoolGradeService.queryList(collect.get(i));
                 if (schoolGradeCopies1.isEmpty()){
                     collect.get(i).setSfzxxn("1");
                     schoolGradeService.save(collect.get(i));
                 }else {
                     for (SchoolGrade date : schoolGradeCopies1){
                         date.setSfzxxn("1");
                         schoolGradeService.updateById(date);
                     }
                 }
                continue;
            }
            //追加学年
            List<SchoolGrade> schoolGradeCopies1 = schoolGradeService.queryList(collect.get(i));
            if (schoolGradeCopies1.isEmpty()){
                //追加
                collect.get(i).setSfzxxn("0");
                schoolGradeService.save(collect.get(i));
            }
        }
        //追加班级
        for ( SchoolGrade date: collect){
            if (date.getId()==null){
                Long l = schoolGradeService.selectDdClassId(date.getDdClassId());
                date.setId(l);
            }
             //查找班级
            //保存班级
            JSONArray ddHttp = this.getDdHttp(date.getDdClassId(), token);
            JSONArray jsonArrays = ddHttp.getJSONArray(0);
            for (int i = 0 ; i < jsonArrays.size() ; i++){
                //查询当前班级是否存在
                String classDdId = jsonArrays.getJSONObject(i).get("dept_id").toString();
                Long classId = iSchoolClassService.selectDdClassId(classDdId);
                if (null != classId){
                    SchoolClass schoolClass = new SchoolClass();
                    schoolClass.setSchoolYear(Integer.valueOf(date.getSchoolYear()));
                    schoolClass.setClassType("4");
                    schoolClass.setGradeValue(date.getGradeValue());
                    schoolClass.setGradeName(date.getGradeName());
                    schoolClass.setClassValue(Integer.valueOf(jsonArrays.getJSONObject(i).getJSONObject("feature").get("class_level").toString()));
                    schoolClass.setClassName(jsonArrays.getJSONObject(i).getJSONObject("feature").get("class_level").toString()+"班");
                    schoolClass.setClassAlias(jsonArrays.getJSONObject(i).get("name").toString());
                    schoolClass.setUpdateBy("admin");
                    schoolClass.setUpdateTime(new Date());
                    schoolClass.setGradeId(date.getId());
                    schoolClass.setDdClassId(classDdId);
                    schoolClass.setId(classId);
                    iSchoolClassService.updateById(schoolClass);
                }else {
                    SchoolClass schoolClass = new SchoolClass();
                    schoolClass.setSchoolYear(Integer.valueOf(date.getSchoolYear()));
                    schoolClass.setClassType("4");
                    schoolClass.setGradeValue(date.getGradeValue());
                    schoolClass.setGradeName(date.getGradeName());
                    schoolClass.setClassValue(Integer.valueOf(jsonArrays.getJSONObject(i).getJSONObject("feature").get("class_level").toString()));
                    schoolClass.setClassName(jsonArrays.getJSONObject(i).getJSONObject("feature").get("class_level").toString()+"班");
                    schoolClass.setClassAlias(jsonArrays.getJSONObject(i).get("name").toString());
                    schoolClass.setCreateBy("admin");
                    schoolClass.setCreateTime(new Date());
                    schoolClass.setUpdateBy("admin");
                    schoolClass.setUpdateTime(new Date());
                    schoolClass.setGradeId(date.getId());
                    schoolClass.setDdClassId(classDdId);
                    iSchoolClassService.save(schoolClass);
                }
            }
        }

        return "1";
    }


    //更新追加人员信息
    @GetMapping("/updateLabUser")
    public String updateLabUser() throws Exception {
        //查找当前学年 所有的班级
        String nowSchoolYear = schoolGradeService.selectUpToYear();
        SchoolClass schoolClass = new SchoolClass();
        schoolClass.setSchoolYear(Integer.valueOf(nowSchoolYear));
        List<SchoolClass> schoolClassCopies = iSchoolClassService.selectSchoolClassList(schoolClass);
        String token = accessTokenUtils.getToken();
        for (SchoolClass date : schoolClassCopies){
             //同步家校通讯老师
           this.handletTeacherDate(token,"teacher",date);
             //同步学生
             this.handletStdentDate(token,"student",date);
             //同步家长
           this.handGuardianDate(token,"guardian",date);
         }
        return "完成";
    }




    /**
     * 老师处理
     * @param
     * @return
     */
    public void  handletTeacherDate(String token ,String type ,SchoolClass date ) throws Exception{
        List<DingJiaXiaoVo.StudentUserInfo> teacherUserInfos = new ArrayList<>();
        SchoolTeacherVO schoolTeacher  = new SchoolTeacherVO();
        teacherUserInfos = this.addUserList(token, type, date.getDdClassId());
        for (DingJiaXiaoVo.StudentUserInfo teachDate : teacherUserInfos){
            // 关联老师跟班级信息
            schoolTeacher.setTeacherName(teachDate.getName());
            List<SchoolTeacher> schoolTeacherCopies = schoolTeacherService.selectSchoolTeacherList(schoolTeacher);
            if (schoolTeacherCopies.isEmpty()){
                log.error("钉钉老师未在系统中找到:"+teachDate.getName());
                continue;
            }
            SchoolTeacher classHeadTeacher = schoolTeacherCopies.get(0);
            if ("1".equals(teachDate.getIsAdviser())){
                //查询数据库中是否有 没有新增
                LambdaQueryWrapper<SchoolClassHeadmaster> lqw=new LambdaQueryWrapper<>();
                lqw.eq(SchoolClassHeadmaster::getTeacherId,classHeadTeacher.getId());
                lqw.eq(SchoolClassHeadmaster::getClassId,date.getId());
                List<SchoolClassHeadmaster> list = iSchoolClassHeadmasterService.list(lqw);
                if (list.isEmpty()){
                    //当前老师是班主任 记录班主任跟班级关系
                    SchoolClassHeadmaster schoolClassHeadmaster = new SchoolClassHeadmaster();
                    schoolClassHeadmaster.setTeacherId(classHeadTeacher.getId());
                    schoolClassHeadmaster.setClassId(date.getId());
                    iSchoolClassHeadmasterService.save(schoolClassHeadmaster);
                }
                //设置班级 班主任信息
                SchoolClass schoolClassss = new SchoolClass();
                schoolClassss.setId(date.getId());
                schoolClassss.setTeacherId(classHeadTeacher.getId());
                schoolClassss.setTeacherName(classHeadTeacher.getTeacherName());
                schoolClassss.setTeacherTel(classHeadTeacher.getTeacherTel());
                iSchoolClassService.updateById(schoolClassss);
            }else {
                SchoolCurriculum schoolCurriculum = null;
                //查找部门   课程没有编写
                SysUser sysUser = sysUserService.selectUserById(classHeadTeacher.getId());
                //根据用户id去查找部门
                SchoolCurriculum schoolCurriculum2 = schoolCurriculumMapper.selectCourseName(sysUser.getDept().getDeptName());
                //判断主部门
                if (null != schoolCurriculum2){
                    schoolCurriculum  = schoolCurriculum2;
                }else {
                    //多个部门
                    List<Map<String, Object>> maps = sysDeptMapper.selectDeptGroupByUserId(sysUser.getUserId());
                    for (Map mp :maps){
                        SchoolCurriculum schoolCurriculum1 = schoolCurriculumMapper.selectCourseName((String) mp.get("deptName"));
                        if (null != schoolCurriculum1);{
                            schoolCurriculum = schoolCurriculum1;
                            break;
                        }
                    }
                }
                //根据部门查找课程信息
                LambdaQueryWrapper<SchoolClassMentor> lqw=new LambdaQueryWrapper<>();
                lqw.eq(SchoolClassMentor::getTeacherId,classHeadTeacher.getId());
                lqw.eq(SchoolClassMentor::getClassId,date.getId());
                List<SchoolClassMentor> list = schoolClassMentorService.list(lqw);
                if (list.isEmpty()){
                    //任课老师 跟班级关系
                    SchoolClassMentor schoolClassMentor = new SchoolClassMentor();
                    schoolClassMentor.setTeacherId(classHeadTeacher.getId());
                    schoolClassMentor.setClassId(date.getId());
                    schoolClassMentor.setCourseName(schoolCurriculum == null ? null:schoolCurriculum.getCourseName());
                    schoolClassMentor.setCourseId(schoolCurriculum == null ? null:schoolCurriculum.getId());
                    schoolClassMentorService.save(schoolClassMentor);
                }else {
                    SchoolClassMentor schoolClassMentor = list.get(0);
                    schoolClassMentor.setCourseName(schoolCurriculum == null ? null:schoolCurriculum.getCourseName());
                    schoolClassMentor.setCourseId(schoolCurriculum == null ? null:schoolCurriculum.getId());
                    schoolClassMentorService.updateById(schoolClassMentor);
                }
            }
        }
    }

    /**
     * 学生处理
     * @param
     * @returnguardianguardian
     */
    public  void handletStdentDate(String token ,String type ,SchoolClass date) throws  Exception {
        List<DingJiaXiaoVo.StudentUserInfo> studentUserInfos = new ArrayList<>();
        studentUserInfos = this.addUserList(token, type, date.getDdClassId());
        for (DingJiaXiaoVo.StudentUserInfo studentDte : studentUserInfos) {
            //当前是否有这个学生
            Long ddUserId = null;
            ddUserId = schoolStudentService.getDdUserId(studentDte.getUserId());
            if (null == ddUserId) {
                //学生信息
                SchoolStudent schoolStudent = new SchoolStudent();
                schoolStudent.setStudentName(studentDte.getName());
                schoolStudent.setClassId(date.getId());
                schoolStudent.setStudentStatus("1");
                schoolStudent.setDdUserId(studentDte.getUserId());
                schoolStudentService.save(schoolStudent);
                ddUserId = schoolStudent.getId();
            } else {
                SchoolStudent schoolStudent = new SchoolStudent();
                schoolStudent.setStudentName(studentDte.getName());
                schoolStudent.setClassId(date.getId());
                schoolStudent.setStudentStatus("1");
                schoolStudent.setDdUserId(studentDte.getUserId());
                schoolStudent.setId(ddUserId);
                schoolStudentService.updateById(schoolStudent);
            }
            LambdaQueryWrapper<SchoolStudentClassRelation> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolStudentClassRelation::getStudentId, ddUserId);
            lqw.eq(SchoolStudentClassRelation::getClassId, date.getId());
            List<SchoolStudentClassRelation> list = iSchoolStudentClassRelationService.list();
            if (list.isEmpty()) {
                //学生班级信息
                SchoolStudentClassRelation schoolStudentClassRelation = new SchoolStudentClassRelation();
                schoolStudentClassRelation.setStudentId(ddUserId);
                schoolStudentClassRelation.setClassId(date.getId());
                iSchoolStudentClassRelationService.save(schoolStudentClassRelation);
            }
            //学生与班级历史关系
            SchoolClass school = iSchoolClassService.selectSchoolClassById(date.getId());
            LambdaQueryWrapper<SchoolStudentClasses> lsqw = new LambdaQueryWrapper<>();
            lsqw.eq(SchoolStudentClasses::getStudentId, ddUserId);
            lsqw.eq(SchoolStudentClasses::getGrade, school.getGradeName());
            lsqw.eq(SchoolStudentClasses::getClasses, school.getClassName());
            lsqw.eq(SchoolStudentClasses::getTeacherName, school.getTeacherName());
            List<SchoolStudentClasses> list1 = schoolStudentClassesService.list(lsqw);
            if (list1.isEmpty()) {
                SchoolStudentClasses schoolStudentClasses = new SchoolStudentClasses();
                schoolStudentClasses.setStudentId(ddUserId);
                schoolStudentClasses.setGrade(school.getGradeName());
                schoolStudentClasses.setClasses(school.getClassName());
                schoolStudentClasses.setTeacherName(school.getTeacherName());
                schoolStudentClassesService.save(schoolStudentClasses);
            }
        }
    }

    /**
     * 家长处理
     * @param grade
     * @return
     */

    public void handGuardianDate(String token,String type,SchoolClass date)throws  Exception{
        List<DingJiaXiaoVo.StudentUserInfo> guardianUserInfos = new ArrayList<>();
        guardianUserInfos = this.addUserList(token, type, date.getDdClassId());
        for (DingJiaXiaoVo.StudentUserInfo guarDate : guardianUserInfos){
            //找寻学生
            String toUserId = this.getToUserId(token, guarDate.getUserId(), date.getDdClassId());
            Long ddUserId = schoolStudentService.getDdUserId(toUserId);
            Long userId = null;
            //查找监护人
            SysUser sysUser = sysUserService.selectUserByDdUserId(guarDate.getUserId().toString());
            if (null == sysUser){
                //创建用户user表
                SysUser jUser = new SysUser();
                jUser.setLoginName(guarDate.getName());
                jUser.setUserName(guarDate.getName());
                jUser.setUserType("01");
                jUser.setUserLoginType("1");
                jUser.setPhonenumber(guarDate.getMobile());
                jUser.setPassword(SecurityUtils.encryptPassword("123#@!"));
                jUser.setStatus("0");
                jUser.setDelFlag("0");
                jUser.setUnionId(guarDate.getUnionid());
                jUser.setDdUserId(guarDate.getUserId());
                jUser.setRoleIds(new Long[]{111L});
                jUser.setStudentId(ddUserId);
                sysUserService.insertUser(jUser);
                userId = jUser.getUserId();
            }else {
                userId = sysUser.getUserId();
                sysUser.setLoginName(guarDate.getName());
                sysUser.setUserName(guarDate.getName());
                sysUser.setUserType("01");
                sysUser.setUserLoginType("1");
                sysUser.setPhonenumber(guarDate.getMobile());
                sysUser.setStatus("0");
                sysUser.setUnionId(guarDate.getUnionid());
                sysUser.setDdUserId(guarDate.getUserId());
                sysUser.setStudentId(ddUserId);
                sysUserService.updateUser(sysUser);
            }
            //家长表
            LambdaQueryWrapper<SchoolStudentParent> lsqw=new LambdaQueryWrapper<>();
            lsqw.eq(SchoolStudentParent::getUserId,userId);
            lsqw.eq(SchoolStudentParent::getStudentId,ddUserId);
            List<SchoolStudentParent> list = iSchoolStudentParentService.list(lsqw);
            if (list.isEmpty()){
                SchoolStudentParent schoolStudentParent = new SchoolStudentParent() ;
                schoolStudentParent.setStudentId(ddUserId);
                schoolStudentParent.setUserId(userId);
                schoolStudentParent.setParentName(guarDate.getName());
                schoolStudentParent.setTelephone(guarDate.getMobile());
                Integer patriarch = this.getPatriarch(guarDate.getName().substring(guarDate.getName().length() - 2));
                schoolStudentParent.setRelationship(String.valueOf(patriarch));
                iSchoolStudentParentService.save(schoolStudentParent);
            }else {
                SchoolStudentParent schoolStudentParent1 = list.get(0);
                schoolStudentParent1.setStudentId(ddUserId);
                schoolStudentParent1.setUserId(userId);
                schoolStudentParent1.setParentName(guarDate.getName());
                schoolStudentParent1.setTelephone(guarDate.getMobile());
                Integer patriarch = this.getPatriarch(guarDate.getName().substring(guarDate.getName().length() - 2));
                schoolStudentParent1.setRelationship(String.valueOf(patriarch));
                iSchoolStudentParentService.updateById(schoolStudentParent1);
            }
        }
    }



    //获取监护人详情 获取学生userid
    public String getToUserId(String token,String fromUserId,String classId){
        String toUserId = null;
        JSONObject bjParme = new 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);
        JSONObject bjObject = JSONObject.parseObject(bjPost);
        if ((Integer) bjObject.get("errcode") != 0){
            throw  new RuntimeException("获取班级列表失败"+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;
    }


    private JSONArray  getDdHttp  (String supId,String token ){
        JSONObject bjParme = new JSONObject();
            bjParme.put("page_no",1);
            bjParme.put("page_size",30);
            bjParme.put("super_id",supId);
            String bjPost = HttpUtil.post(listUrl+token, bjParme);
            JSONObject bjObject = JSONObject.parseObject(bjPost);
            if ((Integer) bjObject.get("errcode") != 0){
                throw  new RuntimeException("获取班级列表失败");
            }
            JSONObject bjResult = (JSONObject)bjObject.get("result");
            JSONArray bjDetailsArray = JSONArray.of(bjResult.get("details"));
            return bjDetailsArray;
    }

    private List<DingJiaXiaoVo.StudentUserInfo> addUserList(String token,String type,String classId) throws Exception{
        List<DingJiaXiaoVo.StudentUserInfo> userList = new ArrayList<>();
        //分页查询，每次查询数据最大只有30条，分5次查询 一个班判断最大150人
        for (int k = 1;k <= 4; k++ ){
            Thread.sleep(200);
            //查询班级下边的人员
            JSONObject ryParme = new JSONObject();
            ryParme.put("page_no",k);
            ryParme.put("page_size",30);
            ryParme.put("role",type);
            ryParme.put("class_id",classId);
            String ryPost = HttpUtil.post(userUrl+token, ryParme);
            JSONObject ryObject = JSONObject.parseObject(ryPost);
            if ((Integer) ryObject.get("errcode") != 0){
                throw  new RuntimeException("获取班级人员列表失败"+ryObject.toString());
            }
            JSONObject ryResult = (JSONObject)ryObject.get("result");
            JSONArray xyDetailsArray = JSONArray.of(ryResult.get("details"));
            for (int o = 0; o < xyDetailsArray.size(); o++){
                for (int i = 0 ; i < xyDetailsArray.getJSONArray(o).size(); i++){
                    JSONObject userInfo = xyDetailsArray.getJSONArray(o).getJSONObject(i);
                    DingJiaXiaoVo.StudentUserInfo studentUserInfo = new DingJiaXiaoVo().new StudentUserInfo();
                    studentUserInfo.setUserId(userInfo.get("userid").toString());
                    studentUserInfo.setClassId((Integer) userInfo.get("class_id"));
                    studentUserInfo.setRole(userInfo.get("role")==null?null:userInfo.get("role").toString());
                    studentUserInfo.setUnionid(userInfo.get("unionid")==null?null:userInfo.get("unionid").toString());
                    studentUserInfo.setName(userInfo.get("name").toString());
                    studentUserInfo.setIsAdviser(userInfo.getJSONObject("feature").get("is_adviser") ==null ? null:userInfo.getJSONObject("feature").get("is_adviser").toString());
                    studentUserInfo.setStudentNo(userInfo.getJSONObject("feature").get("student_no") ==null ? null:userInfo.getJSONObject("feature").get("student_no").toString());
                    //学生没有手机号 不需要查询手机号
                    if (!type.equals("student")){
                        Thread.sleep(200);
                        String tel = this.getTel(studentUserInfo.getUserId(), token);
                        studentUserInfo.setMobile(tel);
                    }
                    userList.add(studentUserInfo);
                }
            }
        }
        return userList;

    }




    private String gradeSubt(String grade){
        String gId = null;
        switch (grade){
            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";
            case  "十二年级": return gId = "12";
            case  "十三年级": return gId = "13";
            case  "十四年级": return gId = "14";
            case  "十五年级": return gId = "15";
            case  "十六年级": return gId = "16";
            case  "十七年级": return gId = "17";
            case  "十八年级": return gId = "18";
            case  "十九年级": return gId = "19";
            case  "二十年级": return gId = "20";
            case  "二十一年级": return gId = "21";
            case  "二十二级": return gId = "22";
            case  "二十三年级": return gId = "23";
            case  "二十四年级": return gId = "24";
            case  "二十五年级": return gId = "25";
            case  "二十六年级": return gId = "26";
            case  "二十七年级": return gId = "27";
            case  "二十八年级": return gId = "28";
            case  "二十九年级": return gId = "29";
            case  "三十年级": return gId = "30";

        }
        return gId;
    }
    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;
    }

    /**
     * 调用钉钉公共接口，获取用户手机号
     */
    public String getTel(String userId ,String assToKen){
        JSONObject userParme = new JSONObject();
        userParme.put("userid",userId);
        String userPost = HttpUtil.post("https://oapi.dingtalk.com/topapi/v2/user/get?access_token="+assToKen, userParme);
        JSONObject jsonObject = JSONObject.parseObject(userPost);
         if ((Integer)jsonObject.get("errcode") != 0 ){
             log.error(jsonObject.toString());
             return null;
         }
        if (jsonObject.getJSONObject("result").get("mobile")==null){
            return null;
        }else {
            return jsonObject.getJSONObject("result").get("mobile").toString();
        }
    }

    /**
     * 获取班级 家 学关系
     */
    public Map<String,String> getFromUserId(Long classId ,String assToKen){
        Map<String,String> map = new HashMap();
        JSONObject userParme = new JSONObject();
        userParme.put("class_id",classId);
        String userPost = HttpUtil.post("https://oapi.dingtalk.com/topapi/edu/user/relation/list?access_token="+assToKen, userParme);
        JSONObject jsonObject = JSONObject.parseObject(userPost);
        JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("relations");
        for (int i =0 ; i< jsonArray.size(); i++ ){
            JSONObject jsonDate= jsonArray.getJSONObject(i);
            String fromUserid = jsonDate.get("from_userid").toString();
            String toUserid = jsonDate.get("to_userid").toString();
            map.put(fromUserid,toUserid);
        }
        return map;
    }
}
