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

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.notice.qywx.BaseStaffNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.Text;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.common.core.entity.user.*;
import com.yida.data.common.core.utils.AppUtil;
import com.yida.data.common.core.utils.DaHuaUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.dto.news.SysNoticeSaveDTO;
import com.yida.data.school.feign.news.RemoteNoticeSystemService;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.user.dto.StudentSyncErrorDTO;
import com.yida.data.user.mapper.EduParentMapper;
import com.yida.data.user.mapper.EduParentStudentMapper;
import com.yida.data.user.mapper.EduStudentMapper;
import com.yida.data.user.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业微信同步service
 *
 * @author ZYJ
 * @date 2022/9/16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QywxSyncServiceImpl implements QywxSyncService {

    private final EduStudentMapper eduStudentMapper;
    private final EduParentMapper eduParentMapper;
    private final EduParentStudentMapper eduParentStudentMapper;

    private final EduStaffService eduStaffService;
    private final EduUserDeptService eduUserDeptService;
    private final EduStaffDeptService eduStaffDeptService;
    private final EduParentTypeService eduParentTypeService;
    private final EduParentStudentService eduParentStudentService;

    private final RemoteDeptService remoteDeptService;
    private final RemoteNoticeSystemService remoteNoticeSystemService;

    private final WxUtil wxUtil;
    private final CommonService commonService;
    private final RedisService redisService;

    @Value("${febs.uploadUrl}")
    private String uploadUrl;

    @Value("${febs.authRedirectUrl}")
    private String authRedirectUrl;

    /**
     * 同步企业微信学生数据
     */
    @Override
    public void syncQywxStudent(Long schoolId) {
        log.info("开始同步学生数据");
        List<Dept> schoolList = new ArrayList<>();
        if (Objects.isNull(schoolId)) {
            // 查询所有绑定了企业微信的学校信息
            schoolList = remoteDeptService.listSchoolBySchoolType(Dept.TYPE_QYWX).getData();
        } else {
            Dept school = remoteDeptService.getInfoByIdNoPermission(schoolId).getData();
            schoolList.add(school);
        }

        List<StudentSyncErrorDTO> errorList = new ArrayList<>();

        if (CollUtil.isNotEmpty(schoolList)) {
            for (Dept school : schoolList) {
                log.info("[{}], schoolId:[{}]开始同步学生数据", school.getDeptName(), school.getDeptId());
                Map<Long, EduUserDept> classCache = new HashMap<>();
                EduApp qywxApp = commonService
                        .getAppByCodeAndSchool(AppConstant.CONTACT_SCHOOL, null, school.getDeptId());
                String accessToken = wxUtil.getAccessToken(qywxApp.getWxCorpId(), qywxApp.getWxSecret());
                // 判断学校是否绑定了大华
                boolean bindDaHuaFlag = false;
//                if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
//                    bindDaHuaFlag = true;
//                }
                // 所有的学生
                JSONArray studentList = wxUtil.getStudentList(accessToken, school.getWxId());
                Set<String> studentWxIds = new HashSet<>();
                Set<String> parentWxIds = new HashSet<>();
                for (Object studentO : studentList) {
                    JSONObject student = (JSONObject) studentO;
                    Long studentId = null;
                    try {
                        // 是否存在该学生
                        String studentWxId = student.getStr("student_userid");
                        String studentName = student.getStr("name");
                        JSONArray studentClass = student.getJSONArray("department");
                        JSONArray wxParents = student.getJSONArray("parents");
                        // 查出来的学生与家长
                        for (Object parent : wxParents) {
                            parentWxIds.add(((JSONObject) parent).getStr("parent_userid"));
                        }
                        studentWxIds.add(studentWxId);
                        EduStudent eduStudent = eduStudentMapper.getStudentWithParent(null, studentWxId, school.getDeptId());
                        if (eduStudent == null) {
                            eduStudent = new EduStudent();
                            eduStudent.setWxId(studentWxId);
                            eduStudent.setStuNumber(studentWxId);
                            eduStudent.setStuName(studentName);
                            eduStudent.setSchoolId(school.getDeptId());
                            eduStudent.setSchoolName(school.getDeptName());
                            // 部门
                            Long classWxId = Long.valueOf(studentClass.get(0).toString());
                            EduUserDept clazz;
                            if (classCache.containsKey(classWxId)) {
                                clazz = classCache.get(classWxId);
                            } else {
                                clazz = eduUserDeptService.getClassBySchoolAndWx(school.getDeptId(), classWxId);
                                classCache.put(classWxId, clazz);
                            }
                            if (clazz == null) {
                                continue;
                            }
                            EduUserDept grade = eduUserDeptService.getById(clazz.getParentId());
                            eduStudent.setGradeId(grade.getDeptId());
                            eduStudent.setGradeName(grade.getDeptName());
                            eduStudent.setClassId(clazz.getDeptId());
                            eduStudent.setClassName(clazz.getDeptName());
                            // 排除错误部门数据
                            EduUserDept section = null;
                            EduUserDept campus = null;
                            if (grade.getParentId() != -school.getDeptId()) {
                                section = eduUserDeptService.getById(grade.getParentId());
                                campus = eduUserDeptService.getById(section.getParentId());
                                eduStudent.setCampusId(campus.getDeptId());
                                eduStudent.setCampusName(campus.getDeptName());
                                eduStudent.setSectionId(section.getDeptId());
                                eduStudent.setSectionName(section.getDeptName());
                            }

                            // 调用大华接口
                            if (bindDaHuaFlag && Objects.nonNull(section)) {
                                String cardNum = DaHuaUtil.generateCardNum();
                                eduStudent.setDahuaCode(eduStudent.getStuNumber().length() > 20
                                        ? DaHuaUtil.generateCode()
                                        : eduStudent.getStuNumber());
                                eduStudent.setDahuaId(
                                        DaHuaUtil.addUser(eduStudent.getStuName(), eduStudent.getDahuaCode(),
                                                0, 1, cardNum,
                                                school.getDahuaId(), campus.getDaHuaId(), section.getDaHuaId(),
                                                grade.getDaHuaId(), clazz.getDaHuaId(), "")
                                );
                            }
                            eduStudentMapper.insert(eduStudent);
                            studentId = eduStudent.getId();
                        } else {
                            // 学生是否更改
                            boolean editFlag = false;
                            if (!eduStudent.getStuName().equals(studentName)) {
                                eduStudent.setStuName(studentName);
                                editFlag = true;
                            }
                            EduUserDept existClass = eduUserDeptService.getById(eduStudent.getClassId());
                            if (Objects.isNull(existClass) || !studentClass.contains(existClass.getWxId())) {
                                Long classWxId = Long.valueOf(studentClass.get(0).toString());
                                EduUserDept clazz;
                                if (classCache.containsKey(classWxId)) {
                                    clazz = classCache.get(classWxId);
                                } else {
                                    log.info("schoolId:[{}],classWxId:[{}]", school.getDeptId(), classWxId);
                                    clazz = eduUserDeptService.getClassBySchoolAndWx(school.getDeptId(), classWxId);
                                    classCache.put(classWxId, clazz);
                                }
                                if (clazz == null) {
                                    continue;
                                }
                                EduUserDept grade = eduUserDeptService.getById(clazz.getParentId());
                                eduStudent.setGradeId(grade.getDeptId());
                                eduStudent.setGradeName(grade.getDeptName());
                                eduStudent.setClassId(clazz.getDeptId());
                                eduStudent.setClassName(clazz.getDeptName());

                                // 排除错误部门数据
                                EduUserDept section = null;
                                EduUserDept campus = null;
                                if (grade.getParentId() != -school.getDeptId()) {
                                    section = eduUserDeptService.getById(grade.getParentId());
                                    campus = eduUserDeptService.getById(section.getParentId());
                                    eduStudent.setCampusId(campus.getDeptId());
                                    eduStudent.setCampusName(campus.getDeptName());
                                    eduStudent.setSectionId(section.getDeptId());
                                    eduStudent.setSectionName(section.getDeptName());
                                }

                                editFlag = true;
                                // 判断一天只处理一次
                                Object o = redisService.hget(CachePrefixConstant.SYNC_STUDENT, eduStudent.getId().toString());
                                // 调用大华接口
                                if (bindDaHuaFlag && Objects.nonNull(section) && Objects.isNull(o)) {
                                    if (Objects.nonNull(eduStudent.getDahuaId())) {
                                        DaHuaUtil.updateUser(eduStudent.getDahuaId(), eduStudent.getStuName(),
                                                eduStudent.getDahuaCode(), 0, 1,
                                                school.getDahuaId(), campus.getDaHuaId(), section.getDaHuaId(),
                                                grade.getDaHuaId(), clazz.getDaHuaId(), "");
                                    } else {
                                        String cardNum = DaHuaUtil.generateCardNum();
                                        eduStudent.setDahuaCode(eduStudent.getStuNumber().length() > 20
                                                ? DaHuaUtil.generateCode()
                                                : eduStudent.getStuNumber());
                                        eduStudent.setDahuaId(
                                                DaHuaUtil.addUser(eduStudent.getStuName(), eduStudent.getDahuaCode(),
                                                        0, 1, cardNum,
                                                        school.getDahuaId(), campus.getDaHuaId(), section.getDaHuaId(),
                                                        grade.getDaHuaId(), clazz.getDaHuaId(), "")
                                        );
                                    }
                                    studentId = eduStudent.getId();
                                }
                            }
                            // 学生被更改了 修改
                            if (editFlag) {
                                eduStudentMapper.updateById(eduStudent);
                            }
                        }
                        // 存到今天结束
                        LocalDateTime start = LocalDateTime.now();
                        LocalDateTime end = LocalDateTimeUtil.endOfDay(start);
                        Duration between = LocalDateTimeUtil.between(start, end);
                        redisService.hset(CachePrefixConstant.SYNC_STUDENT,
                                eduStudent.getId().toString(), 1, between.toMillis() / 1000);
                        List<EduParent> eduParentList = eduStudent.getParents();
                        List<Long> eduParentListCopy = CollUtil.isNotEmpty(eduParentList) ?
                                eduParentList.stream().map(EduParent::getId).collect(Collectors.toList()) : new ArrayList<>();
                        if (CollUtil.isNotEmpty(wxParents)) {
                            for (Object wxParentO : wxParents) {
                                JSONObject wxParent = (JSONObject) wxParentO;
                                boolean existParent = false;
                                // 是否存在该家长
                                if (CollUtil.isNotEmpty(eduParentList)) {
                                    for (EduParent parent : eduParentList) {
                                        if (wxParent.getStr("parent_userid").equals(parent.getWxId())) {
                                            // 修改了家长手机号
                                            if (!wxParent.getStr("mobile").equals(parent.getMobile())) {
                                                parent.setMobile(wxParent.getStr("mobile"));
                                                eduParentMapper.updateById(parent);
                                            }
                                            // 修改了关系  进行替换
                                            if (!wxParent.getStr("relation").equals(parent.getParentType())) {
                                                EduParentType parentType = eduParentTypeService
                                                        .getParentType(wxParent.getStr("relation"));
                                                eduParentStudentService.remove(Wrappers.<EduParentStudent>lambdaQuery()
                                                        .eq(EduParentStudent::getStudentId, eduStudent.getId())
                                                        .eq(EduParentStudent::getParentId, parent.getId()));
                                                EduParentStudent parentStudent = new EduParentStudent();
                                                parentStudent.setStudentId(eduStudent.getId());
                                                parentStudent.setParentId(parent.getId());
                                                parentStudent.setParentTypeId(parentType.getId());
                                                eduParentStudentService.save(parentStudent);
                                            }
                                            // 删除列表中的该元素
                                            eduParentListCopy.remove(parent.getId());
                                            existParent = true;
                                        }
                                    }
                                }
                                // 家长关系不存在
                                if (!existParent) {
                                    EduParent existEduParent = eduParentMapper.selectOne(Wrappers.<EduParent>lambdaQuery()
                                            .eq(EduParent::getWxId, wxParent.getStr("parent_userid"))
                                            .eq(EduParent::getSchoolId, school.getDeptId()));
                                    if (existEduParent == null) {
                                        existEduParent = new EduParent();
                                        existEduParent.setMobile(wxParent.getStr("mobile"));
                                        existEduParent.setSchoolId(school.getDeptId());
                                        existEduParent.setWxId(wxParent.getStr("parent_userid"));
                                        eduParentMapper.insert(existEduParent);
                                    }
                                    EduParentType relation = eduParentTypeService
                                            .getParentType(wxParent.getStr("relation"));
                                    EduParentStudent eduParentStudent = new EduParentStudent();
                                    eduParentStudent.setStudentId(eduStudent.getId());
                                    eduParentStudent.setParentId(existEduParent.getId());
                                    eduParentStudent.setParentTypeId(relation.getId());
                                    eduParentStudentService.save(eduParentStudent);
                                }
                            }
                        }
                        //家长还有剩余  关系需要被删除
                        if (CollUtil.isNotEmpty(eduParentListCopy)) {
                            eduParentStudentService.remove(Wrappers.<EduParentStudent>lambdaQuery()
                                    .eq(EduParentStudent::getStudentId, eduStudent.getId())
                                    .in(EduParentStudent::getParentId, eduParentListCopy));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (Objects.nonNull(studentId)) {
                            redisService.hdel(CachePrefixConstant.SYNC_STUDENT, studentId.toString());
                        }
                        log.error("同步学生信息: {}==>错误: {}", student.getStr("name"), student, e);
                        StudentSyncErrorDTO dto = new StudentSyncErrorDTO();
                        dto.setSchoolId(school.getDeptId());
                        dto.setSchoolName(school.getDeptName());
                        dto.setStuName(student.getStr("name"));
                        dto.setStuId(studentId);
                        dto.setWxStudent(student.toString());
                        dto.setErrorMessage(e.getMessage());

                        errorList.add(dto);
                    }
                }
                // 删除多余的学生与家长
                eduStudentMapper.delete(Wrappers.<EduStudent>lambdaQuery().eq(EduStudent::getSchoolId, school.getDeptId())
                        .notIn(EduStudent::getWxId, studentWxIds));
                eduParentMapper.delete(Wrappers.<EduParent>lambdaQuery().eq(EduParent::getSchoolId, school.getDeptId())
                        .notIn(EduParent::getWxId, parentWxIds));
                eduParentStudentMapper.delNotExistRaltion();
            }
        }

        // 判断是否有多余的错误数据
        if (CollUtil.isNotEmpty(errorList)) {
            // 错误信息文件名称
            String fileName = FileUtil.getLocalUploadAddress() + UUID.randomUUID() + ".xlsx";
            EasyExcel.write(fileName, StudentSyncErrorDTO.class)
                    .sheet("错误信息")
                    .doWrite(errorList);
            // 上传到媒资
            String url = FileUtil.uploadFileToMediaServer(uploadUrl, new File(fileName));
            // 保存导入不成功的数据和原因
            remoteNoticeSystemService.sendNotice(
                    SysNoticeSaveDTO.builder()
                            .userId(Collections.singletonList(4049L))
                            .content("企业微信学生数据部分同步失败. 详情信息请点击下载  <a style='color: blue' href='" + url + "'>学生同步错误信息.xlsx</a>")
                            .createDate(LocalDateTime.now())
                            .build());
        }

        log.info("同步学生数据结束");
    }

    @Override
    public void syncQywxStaff(Long schoolId) {
        log.info("开始同步职工数据");
        List<Dept> schoolList = new ArrayList<>();
        if (Objects.isNull(schoolId)) {
            // 查询所有绑定了企业微信的学校信息
            schoolList = remoteDeptService.listSchoolBySchoolType(Dept.TYPE_QYWX).getData();
        } else {
            Dept school = remoteDeptService.getInfoByIdNoPermission(schoolId).getData();
            schoolList.add(school);
        }

        for (Dept school : schoolList) {
            log.info("[{}], schoolId:[{}]开始同步职工数据", school.getDeptName(), school.getDeptId());
            // 判断学校是否绑定了app
            boolean bindAppFlag = false;
            EduYidaAppAccount yidaAppAccount = commonService.getYidaAppAccount(school.getDeptId(), 1);
            EduYidaApp yidaApp = commonService.getYidaApp(school.getDeptId());
            if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                bindAppFlag = true;
            }

            String accessToken = commonService.getAddressListToken(school.getDeptId());
            // 获取学校通讯录应用
            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null, school.getDeptId());
            if (Objects.isNull(app.getTemplateId())) {
                // 自建应用, 查询企业通讯录的成员列表
                JSONArray userList = wxUtil.getUserList(accessToken, 1L);
                for (Object staff : userList) {
                    Map<Long, Dept> deptCache = new HashMap<>();
                    // 遍历企业微信成员
                    JSONObject staffJson = (JSONObject) staff;
                    String staffWxId = staffJson.getStr("userid");
                    // 职工是否存在
                    EduStaff existStaff = eduStaffService.getOne(Wrappers.<EduStaff>lambdaQuery().eq(EduStaff::getWxId, staffWxId)
                            .eq(EduStaff::getSchoolId, school.getDeptId()));
                    EduStaff eduStaff = existStaff != null ? existStaff : new EduStaff();

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

                    // 学校绑定了易达app
                    if (bindAppFlag) {
                        eduStaff.setYidaAppUserId(AppUtil.userSave(eduStaff.getMobile(), eduStaff.getName(), yidaApp));
                        AppUtil.subscribeFollow(yidaAppAccount.getYidaAppAccountId(), eduStaff.getYidaAppUserId(), yidaApp);
                    }
                    eduStaffService.saveOrUpdate(eduStaff);

                    // 成员部门信息
                    JSONArray department = staffJson.getJSONArray("department");
                    JSONArray isLeader = staffJson.getJSONArray("is_leader_in_dept");
                    if (CollUtil.isNotEmpty(department)) {
                        eduStaffDeptService.remove(
                                Wrappers.<EduStaffDept>lambdaQuery().eq(EduStaffDept::getStaffId, eduStaff.getId()));
                        List<EduStaffDept> staffDeptList = new ArrayList<>();
                        for (int i = 0; i < department.size(); i++) {
                            // 成员的每个部门信息
                            EduStaffDept staffDept = new EduStaffDept();
                            staffDept.setStaffId(eduStaff.getId());
                            staffDept.setStaffName(eduStaff.getName());
                            staffDept.setDeptWxId(Long.valueOf(department.get(i).toString()));
                            Dept dept = deptCache.containsKey(staffDept.getDeptWxId()) ? deptCache.get(staffDept.getDeptWxId())
                                    : (department.getLong(i) == 1L ? school : remoteDeptService.getDeptBySchoolAndWxId(school.getDeptId(),
                                    Long.valueOf(department.get(i).toString())).getData());
                            staffDept.setDeptId(dept.getDeptId());
                            staffDept.setDeptName(dept.getDeptName());
                            staffDept.setIsLeader(isLeader.getInt(i));
                            staffDept.setIsMain(ObjectUtil.equal(staffJson.get("main_department"), department.get(i)) ? 0 : 1);
                            staffDeptList.add(staffDept);
                        }
                        eduStaffDeptService.saveBatch(staffDeptList);
                    }
                    // 保存系统用户信息
                    eduStaffService.saveSystemUser(eduStaff);
//                SystemUser systemUser = remoteUserService.getInfoByUsernameNoPermission(eduStaff.getMobile()).getData();
//                if (ObjectUtil.isNull(systemUser)) {
//                    systemUser = saveSystemUser(eduStaff);
//                    eduStaff.setYidaAppUserId(systemUser.getYidaAppUserId());
//                }
//                eduStaff.setSysUserId(systemUser.getUserId());
//                saveOrUpdate(eduStaff);
                }
            } else {
                // 代开发应用调用获取成员ID列表接口
                JSONArray jsonArray = JSONUtil.createArray();
                JSONArray userIdList = wxUtil.getUserIdList(accessToken, "", "100", jsonArray);
                log.info("成员id列表数据====================: {}", userIdList);

                if (CollUtil.isNotEmpty(userIdList)) {
                    // 此处获取对应学校通讯录(人力资源)应用
                    EduApp contactSelectApp = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SELECT, null, school.getDeptId());

                    for (int x = 0; x < userIdList.size(); x++) {
                        JSONObject wxUser = JSONUtil.parseObj(userIdList.get(x));
                        String userId = wxUser.getStr("open_userid");
                        // 查询是否有职工数据
                        EduStaff eduStaff = eduStaffService.getOne(Wrappers.lambdaQuery(new EduStaff())
                                .eq(EduStaff::getWxId, userId));
                        if (Objects.isNull(eduStaff)) {
                            // 新增职工
                            String authUrl = commonService.setAuthUrl(school.getCorpId(), authRedirectUrl + "?schoolId=" + school.getDeptId(), contactSelectApp.getWxAgentId());
                            // 发送授权消息给创建人员
                            BaseStaffNotice textSchoolNotice = new BaseStaffNotice();
                            Text text = new Text();
                            textSchoolNotice.setText(text);
                            textSchoolNotice.setAgentid(contactSelectApp.getWxAgentId());
                            text.setContent("<a href='" + authUrl + "'>智慧校园系统信息授权：请点击授权（请务必授权手机号！）</a>");
                            textSchoolNotice.setTouser(userId);
                            // 此处获取对应学校通讯录(人力资源)应用
                            wxUtil.pushStaffNotice(wxUtil.getAccessToken(contactSelectApp.getWxCorpId(), contactSelectApp.getWxSecret()), textSchoolNotice);
                        } else {
                            // 编辑职工
                            // 查询用户详细信息
                            JSONObject userDetail = wxUtil.getUserDetail(
                                    wxUtil.getAccessToken(contactSelectApp.getWxCorpId(), contactSelectApp.getWxSecret()), userId);
                            // 姓名
                            String name = userDetail.getStr("name");
                            eduStaff.setName(name);
                            // 职位
                            eduStaff.setPosition(userDetail.getStr("position"));

                            // 成员部门信息
                            JSONArray departmentList = userDetail.getJSONArray("department");
                            JSONArray leaderInDept = userDetail.getJSONArray("is_leader_in_dept");
                            // 主部门信息
                            String mainDepartment = userDetail.getStr("main_department");
                            if (ArrayUtil.isNotEmpty(departmentList)) {
                                List<EduStaffDept> staffDeptList = new ArrayList<>();
                                for (int i = 0; i < departmentList.size(); i++) {
                                    // 部门id
                                    String deptId = String.valueOf(departmentList.get(i));
                                    // 成员的每个部门信息
                                    EduStaffDept staffDept = new EduStaffDept();
                                    staffDept.setStaffName(eduStaff.getName());
                                    staffDept.setDeptWxId(Long.valueOf(deptId));
                                    Dept sysDept = ("1".equals(deptId)
                                            ? school
                                            : remoteDeptService.getDeptBySchoolAndWxId(school.getDeptId(), staffDept.getDeptWxId()).getData());
                                    staffDept.setDeptId(sysDept.getDeptId());
                                    staffDept.setDeptName(sysDept.getDeptName());
                                    staffDept.setIsLeader(Integer.valueOf(String.valueOf(leaderInDept.get(i))));
                                    staffDept.setIsMain(ObjectUtil.equal(mainDepartment, deptId) ? 0 : 1);
                                    staffDeptList.add(staffDept);
                                }
                                eduStaff.setStaffDept(staffDeptList);
                            }
                            eduStaffService.saveStaffBySchoolAndWx(eduStaff);
                            // 保存系统用户信息
                            eduStaffService.saveSystemUser(eduStaff);
                        }
                    }
                }
            }
        }
        log.info("结束同步职工数据");
    }
}
