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

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.auth.RemoteAuthService;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.QueryRequest;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.*;
import com.yida.data.common.core.entity.system.enums.RoleEnum;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStaffDept;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.*;
import com.yida.data.common.service.CommonService;
import com.yida.data.rabbit.util.RabbitUtil;
import com.yida.data.system.dto.MenuForUserDTO;
import com.yida.data.system.dto.SchoolAdminAccountSaveDTO;
import com.yida.data.system.dto.SchoolAdminAccountSelectPageDTO;
import com.yida.data.system.mapper.EduYidaAppMapper;
import com.yida.data.system.mapper.RoleMapper;
import com.yida.data.system.mapper.UserMapper;
import com.yida.data.system.service.*;
import com.yida.data.system.vo.SchoolAdminAccountSelectPageVO;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteTeacherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Slf4j
@Service("userService")
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, SystemUser> implements IUserService {

    private final RoleMapper roleMapper;
    private final SystemUserMenuService systemUserMenuService;
    private final IUserRoleService userRoleService;
    private final IUserDataPermissionService userDataPermissionService;
    private final PasswordEncoder passwordEncoder;
    private final IRoleService roleService;
    private final EduAppAccountService eduAppAccountService;
    private final EduYidaAppMapper eduYidaAppMapper;

    private final RemoteAuthService remoteAuthService;
    private final RemoteStaffService remoteStaffService;
    private final RemoteTeacherService remoteTeacherService;

    private final WxUtil wxUtil;
    private final RabbitUtil rabbitUtil;

    private final RedisService redisService;
    private final CommonService commonService;

    private final static String AUTH_CLIENT_ID = "febs";
    @Lazy
    @Resource
    private IDeptService deptService;

    @Override
    public SystemUser findByName(String username) {
        return this.baseMapper.findUserByUsername(username);
    }

    @Override
    public SystemUser findByMobile(String mobile) {
        return baseMapper.findUserByMobile(mobile);
    }

    @Override
    public IPage<SystemUser> findUserDetailList(SystemUser user, QueryRequest request) {
        Page<SystemUser> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "userId", FebsConstant.ORDER_DESC, false);
        // 返回数据
        IPage<SystemUser> returnPage;
        // 当前登陆用户数据
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        // 获取登陆用户的最大角色
        RoleEnum roleEnum = RoleUtil.getMaxRole(currentUser);

        if (RoleEnum.ROLE_ADMIN.equals(roleEnum)) {
            // 超级管理员
            returnPage = this.baseMapper.findUserDetailPage(page, user);
        } else {
            // 查询下级部门信息
            List<Long> childIdList = this.deptService.findListByParent(Collections.singletonList(currentUser.getDeptId()), 0)
                    .stream().map(Dept::getDeptId).collect(Collectors.toList());
            // 添加主部门id
            childIdList.add(currentUser.getDeptId());
            // 具有创建账号的数据   自己创建的账号+当前登陆账号部门及以下的账号
            returnPage = this.baseMapper.findUserPage(page, user, childIdList, currentUser);
        }
        return returnPage;
    }

    @Override
    public SystemUser findUserDetail(String username) {
        SystemUser param = new SystemUser();
        param.setUsername(username);
        List<SystemUser> users = this.baseMapper.findUserDetail(param);
        return CollectionUtils.isNotEmpty(users) ? users.get(0) : null;
    }

    @Override
    public void lockUser(Long id) {
        // TODO: 2021/5/6 权限校验
        SystemUser systemUser = getById(id);
        systemUser.setStatus("0".equals(systemUser.getStatus()) ? "1" : "0");
        updateById(systemUser);
    }

    @Override
    public void resetPwd(Long id) {
        SystemUser systemUser = getById(id);
        systemUser.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
//        systemUser.setStatus("0".equals(systemUser.getStatus()) ? "1" : "0");
        updateById(systemUser);

        // 撤销登录
        remoteAuthService.revokeApproval(systemUser.getUsername(), AUTH_CLIENT_ID);

//        EduNoticeSystem eduNotice = new EduNoticeSystem();
//
//        eduNotice.setContent("管理员已经将您的密码重置，重置后密码为ZBZ@2021，" +
//                "初始密码不安全，请尽快修改密码"
//        );
//        Long noticeId = eduNoticeSystemService.insertNotice(eduNotice);
//        EduNoticeSystemUser eduNoticeSystemUser = new EduNoticeSystemUser();
//        eduNoticeSystemUser.setUserId(systemUser.getUserId());
//        eduNoticeSystemUser.setNoticeId(noticeId);
//        eduNoticeSystemUserService.insertNotice(eduNoticeSystemUser);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(String username) {
        SystemUser user = new SystemUser();
        user.setLastLoginTime(LocalDateTime.now());

        this.baseMapper.update(user, new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, username));
    }

    @Override
    public SystemUser createUser(SystemUser user) {
        if (FebsUtil.isLogin()) {
            CurrentUser currentUser = Objects
                    .requireNonNull(FebsUtil.getCurrentUser(), ResultMsgType.LOGIN_INFO_ERROR.getValue());
            // 代理商或教育局创建的学校账号不需要再次设置创建部门id或主部门id
            user.setCreateId(currentUser.getUserId());
            if (Objects.isNull(user.getCreateDeptId())) {
                user.setCreateDeptId(currentUser.getDeptId());
            }
            if (Objects.isNull(user.getMainDeptId())) {
                // 获取当前登陆用户最大的角色
                RoleEnum maxRole = RoleUtil.getMaxRole(currentUser);
                if (RoleEnum.ROLE_SCHOOL_PRINCIPAL.equals(maxRole) || RoleEnum.ROLE_EDUCATION_PRINCIPAL.equals(maxRole) ||
                        RoleEnum.ROLE_AGENT_ADMIN.equals(maxRole)) {
                    user.setMainDeptId(currentUser.getDeptId());
                } else if (Objects.nonNull(currentUser.getMainDeptId())) {
                    user.setMainDeptId(currentUser.getMainDeptId());
                }
            }

        } else {
            user.setMainDeptId(user.getDeptId());
        }

        // 创建用户
        user.setAvatar(SystemUser.DEFAULT_AVATAR);
        user.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        save(user);
        // 保存用户角色
        if (user.getRoleId() != null) {
            String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
            setUserRoles(user, roles);
        } else if (StrUtil.isNotBlank(user.getRoleName())) {
            Role role = roleMapper.selectOne(Wrappers.<Role>lambdaQuery().eq(Role::getRoleName, user.getRoleName()));
            if (role == null) {
                role = new Role();
                role.setRoleName(user.getRoleName());
                role.setRemark(user.getRoleName());
                roleService.createRole(role);
            }
            user.setRoleId(role.getRoleId().toString());
            setUserRoles(user, new String[]{role.getRoleId().toString()});
        } else {
            Role role = roleService.getOne(Wrappers.lambdaQuery(new Role()).eq(Role::getRoleName, "注册用户"));
            if (role == null) {
                role = new Role();
                role.setRoleName("注册用户");
                role.setRemark("默认注册用户");
                roleService.createRole(role);
            }
            user.setRoleId(role.getRoleId().toString());
            setUserRoles(user, new String[]{role.getRoleId().toString()});
        }
        // 保存用户数据权限关联关系
        String[] deptIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getDeptIds(), StringConstant.COMMA);
        if (ArrayUtil.isNotEmpty(deptIds)) {
            setUserDataPermissions(user, deptIds);
        }
//        // 保存用户对应菜单
//        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
//        List<String> list = Arrays.asList(roles);
//        List<Long> menuId = baseMapper.findRoleId(list);
//        List<SystemUserMenu> userMenuList = new ArrayList<>();
//        for (Long aLong : menuId) {
//            SystemUserMenu systemUserMenu = new SystemUserMenu();
//            systemUserMenu.setUserId(user.getUserId());
//            systemUserMenu.setMenuId(aLong);
//            userMenuList.add(systemUserMenu);
//        }
//        systemUserMenuService.saveBatch(userMenuList);
        return user;
    }

    @Override
    public void updateUser(SystemUser user) {

        // 更新用户
        user.setPassword(null);
        user.setUsername(null);
        updateById(user);

        String[] userIds = {String.valueOf(user.getUserId())};
        userRoleService.deleteUserRolesByUserId(userIds);
        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
        setUserRoles(user, roles);

        userDataPermissionService.deleteByUserIds(userIds);
        String[] deptIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getDeptIds(), StringConstant.COMMA);
        if (ArrayUtil.isNotEmpty(deptIds)) {
            setUserDataPermissions(user, deptIds);
        }

        // TODO: 2021/7/19 系统通知待修改
//        EduNoticeSystem eduNotice = new EduNoticeSystem();
//        String a = "";
//        for (int i = 0; i < roles.length; i++) {
//            a = a + roles[i];
//        }
        //eduNotice.setContent("管理员已将您添加为" + a);
        //Long noticeId = eduNoticeSystemService.insertNotice(eduNotice);
        //EduNoticeSystemUser eduNoticeSystemUser = new EduNoticeSystemUser();
        //eduNoticeSystemUser.setNoticeId(noticeId);
        //eduNoticeSystemUser.setUserId(user.getUserId());
        //eduNoticeSystemUserService.insertNotice(eduNoticeSystemUser);
        // 删除用户对应权限数据
        systemUserMenuService.remove(Wrappers.lambdaQuery(new SystemUserMenu())
                .in(SystemUserMenu::getUserId, user.getUserId()));
//        // 保存用户对应权限数据
//        List<Long> menuId = baseMapper.findRoleId(Arrays.asList(roles));
//        List<SystemUserMenu> userMenuList = new ArrayList<>();
//        for (Long aLong : menuId) {
//            SystemUserMenu systemUserMenu = new SystemUserMenu();
//            systemUserMenu.setUserId(user.getUserId());
//            systemUserMenu.setMenuId(aLong);
//            userMenuList.add(systemUserMenu);
//        }
//        systemUserMenuService.saveBatch(userMenuList);
    }

    @Override
    public void updateUserWithName(SystemUser user) {
        user.setPassword(null);
        updateById(user);
    }

    @Override
    public void deleteUsers(String[] userIds) {
        List<String> list = Arrays.asList(userIds);
        removeByIds(list);
        // 删除用户角色
        this.userRoleService.deleteUserRolesByUserId(userIds);
        this.userDataPermissionService.deleteByUserIds(userIds);
        // 删除用户对应权限数据
        systemUserMenuService.remove(Wrappers.lambdaQuery(new SystemUserMenu())
                .in(SystemUserMenu::getUserId, list));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(SystemUser user) throws FebsException {
        user.setPassword(null);
        user.setUsername(null);
        user.setStatus(null);
        if (isCurrentUser(user.getUserId())) {
            updateById(user);
        } else {
            throw new FebsException("您无权修改别人的账号信息！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAvatar(String avatar) {
        SystemUser user = new SystemUser();
        user.setAvatar(avatar);
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, currentUsername));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(String password) {
        SystemUser user = new SystemUser();
        user.setPassword(passwordEncoder.encode(password));
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, currentUsername));
    }

    @Override
    public void updatePassword(String password, String newPassword, String repeatPassword, String username) {
        SystemUser user = new SystemUser();
        SystemUser exist = getOne(Wrappers.lambdaQuery(new SystemUser()).eq(SystemUser::getUsername, username));
        Asserts.isTrue(StringUtils.equals(newPassword, repeatPassword), "两次输入的密码不一致");
        int errorCount = redisService.hasKey(CachePrefixConstant.PWD_ERROR + username) ? Integer.parseInt(
                redisService.get(CachePrefixConstant.PWD_ERROR + username).toString()) : 0;
        if (errorCount >= 3) {
            throw new FebsException("错误次数已达上限，请24小时后再试");
        }
        if (!passwordEncoder.matches(password, exist.getPassword())) {
            errorCount++;
            redisService.set(CachePrefixConstant.PWD_ERROR + username, errorCount, 86400L);
            throw new FebsException("密码错误，请重新输入");
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        this.baseMapper.update(user, new LambdaUpdateWrapper<SystemUser>().eq(SystemUser::getUsername, username));
        // 撤销登录
        remoteAuthService.revokeApproval(username, AUTH_CLIENT_ID);
//        String token = FebsUtil.getCurrentTokenValue();
//        redisService.del(FebsConstant.AUTH + token, FebsConstant.ACCCESS + token, FebsConstant.ACCESS_TO_REFRESH + token);
        // 发送系统通知
//        SysNoticeSaveDTO dto = new SysNoticeSaveDTO();
//        dto.setContent("您已修改账号密码！");
//        dto.setCreateDate(LocalDateTime.now());
//        dto.setUserId(Collections.singletonList(exist.getUserId()));
//        rabbitUtil.convertAndSendMsg(RabbitConstant.MSG_EXCHANGE, RabbitConstant.MSG_NOTICE_SYS_SAVE_KEY, dto);
    }

    @Override
    public void validatePassword(String password, String username) {
        SystemUser exist = getOne(Wrappers.lambdaQuery(new SystemUser()).eq(SystemUser::getUsername, username));
        int errorCount = redisService.hasKey(CachePrefixConstant.PWD_ERROR + username) ? Integer.parseInt(
                redisService.get(CachePrefixConstant.PWD_ERROR + username).toString()) : 0;
        if (errorCount >= 3) {
            throw new FebsException("错误次数已达上限，请24小时后再试");
        }
        if (!passwordEncoder.matches(password, exist.getPassword())) {
            errorCount++;
            redisService.set(CachePrefixConstant.PWD_ERROR + username, errorCount, 86400L);
            throw new FebsException("密码错误，请重新输入");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(String[] usernames) {
        SystemUser params = new SystemUser();
        params.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));

        List<String> list = Arrays.asList(usernames);
        this.baseMapper.update(params, new LambdaQueryWrapper<SystemUser>().in(SystemUser::getUsername, list));
//        String username = "";
//        for (int i = 0; i < usernames.length; i++) {
//            username = username + usernames[i];
//        }
//
//        EduNoticeSystem eduNotice = new EduNoticeSystem();
//
//        eduNotice.setContent("管理员已经将您的密码重置，重置后密码为ZBZ@2021，" +
//                "初始密码不安全，请尽快修改密码");
//        QueryWrapper<SystemUser> queryWrapper = new QueryWrapper<>();
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("userName", username);
//        queryWrapper.allEq(map);
//        Long noticeId = eduNoticeSystemService.insertNotice(eduNotice);
//        EduNoticeSystemUser eduNoticeSystemUser = new EduNoticeSystemUser();
//        eduNoticeSystemUser.setNoticeId(noticeId);
//        eduNoticeSystemUser.setUserId(userMapper.selectOne(queryWrapper).getUserId());
//        log.info("需要保存的通知关联user信息====================================: {}", eduNoticeSystemUser);
//        eduNoticeSystemUserService.insertNotice(eduNoticeSystemUser);
    }

    @Override
    public void subscribeYidaApp(String userId, Long schoolId, Integer type) {
        EduYidaAppAccount account = eduAppAccountService.getOne(
                Wrappers.lambdaQuery(new EduYidaAppAccount()).eq(EduYidaAppAccount::getSchoolId, schoolId)
                        .eq(EduYidaAppAccount::getType, type));
        EduYidaApp yidaApp = eduYidaAppMapper.getYidaAppBySchool(schoolId);
        AppUtil.subscribeFollow(account.getYidaAppAccountId(), userId, yidaApp);
    }

    private void setUserRoles(SystemUser user, String[] roles) {
        List<UserRole> userRoles = new ArrayList<>();
        Arrays.stream(roles).forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRoles.add(userRole);
        });
        userRoleService.saveBatch(userRoles);

        //新增用户时新增用户对应默认菜单
        List<Long> roleId = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            roleId.add(userRole.getRoleId());
        }
        Long[] arrRoleId = roleId.toArray(new Long[0]);
        List<Menu> list = roleMapper.listMenuByRole(arrRoleId);
        List<Long> menuIds = new ArrayList<>();
        for (Menu menu : list) {
            menuIds.add(menu.getMenuId());
        }
        MenuForUserDTO menuForUserDTO = new MenuForUserDTO();
        menuForUserDTO.setMenuId(menuIds);
        menuForUserDTO.setUserId(user.getUserId());
        systemUserMenuService.saveUserMenu(menuForUserDTO);
    }

    private void setUserDataPermissions(SystemUser user, String[] deptIds) {
        List<UserDataPermission> userDataPermissions = new ArrayList<>();
        Arrays.stream(deptIds).forEach(deptId -> {
            UserDataPermission permission = new UserDataPermission();
            permission.setDeptId(Long.valueOf(deptId));
            permission.setUserId(user.getUserId());
            userDataPermissions.add(permission);
        });
        userDataPermissionService.saveBatch(userDataPermissions);
    }

    private boolean isCurrentUser(Long id) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        return currentUser != null && id.equals(currentUser.getUserId());
    }

    /**
     * 保存学校负责人账号
     *
     * @param schoolAdminAccountSaveDTO 保存学校负责人账号请求类
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/9/28 11:08
     */
    @Override
    public ResultBean<String> saveSchoolAdminAccount(SchoolAdminAccountSaveDTO schoolAdminAccountSaveDTO) {

        SystemUser systemUser = new SystemUser();
        systemUser.setUserId(schoolAdminAccountSaveDTO.getUserId());
        systemUser.setDeptId(schoolAdminAccountSaveDTO.getDeptId());
        systemUser.setUsername(schoolAdminAccountSaveDTO.getUserName());
        systemUser.setNickname(schoolAdminAccountSaveDTO.getNickname());
        // 查询学校负责人角色数据
        Role role = this.roleService.getOne(
                Wrappers.lambdaQuery(new Role()).eq(Role::getRolePerms, RoleEnum.ROLE_SCHOOL_PRINCIPAL.getValue()));
        systemUser.setRoleId(String.valueOf(role.getRoleId()));

        if (Objects.isNull(systemUser.getUserId())) {
            // 新增
            systemUser.setCreateDate(LocalDateTime.now());
            systemUser.setMainDeptId(schoolAdminAccountSaveDTO.getDeptId());
            systemUser.setCreateDeptId(schoolAdminAccountSaveDTO.getDeptId());
            createUser(systemUser);
        } else {
            // 编辑
            systemUser.setUpdateDate(LocalDateTime.now());
            updateUser(systemUser);
        }
        return ResultBean.buildSuccess();
    }

    /**
     * 代理商查询学校管理员账号列表数据
     *
     * @param schoolAdminAccountSelectPageDTO 代理商查询学校管理员账号列表数据请求类
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yida.data.system.vo.SchoolAdminAccountSelectPageVO>
     * @author ZYJ
     * @date 2022/1/17 13:59
     */
    @Override
    public IPage<SchoolAdminAccountSelectPageVO> listSchoolAdminAccountPage(
            SchoolAdminAccountSelectPageDTO schoolAdminAccountSelectPageDTO) {
        return this.baseMapper.
                listSchoolAdminAccountPage(schoolAdminAccountSelectPageDTO.toPage(), schoolAdminAccountSelectPageDTO,
                        RoleEnum.ROLE_SCHOOL_PRINCIPAL.getValue());
    }

    @Override
    public void updateUserRoleByRoleName(Long userId, List<String> roleNames) {
        SystemUser user = getById(userId);
        Asserts.isNotNull(user, "用户不存在");
        List<Role> roles = roleService.list(Wrappers.<Role>lambdaQuery()
                .in(Role::getRoleName, roleNames));
        if (CollUtil.isNotEmpty(roles)) {
            userRoleService.remove(Wrappers.<UserRole>lambdaQuery()
                    .eq(UserRole::getUserId, userId));
            List<UserRole> saveList = new ArrayList<>();
            for (Role role : roles) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(role.getRoleId());
                userRole.setUserId(userId);
                saveList.add(userRole);
            }
            userRoleService.saveBatch(saveList);
        }
    }

    @Override
    public void createStaff(Long schoolId, String code) {
        // 学校信息
        Dept school = deptService.getById(schoolId);
        // 此处获取对应学校通讯录(人力资源)应用
        EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SELECT, null, schoolId);
        // 获取access token
        String accessToken = wxUtil.getAccessToken(school.getCorpId(), app.getWxSecret());
        // 获取访问用户身份
        JSONObject userInfo = wxUtil.getUserInfo(accessToken, code);
        // 获取访问用户敏感信息
        JSONObject sensitiveInfo = wxUtil.getUserSensitiveInfo(accessToken, userInfo.getStr("user_ticket"));
        String mobile = sensitiveInfo.getStr("mobile");
        if (StrUtil.isEmpty(mobile)) {
            throw new FebsException("请授权手机号码!");
        }
        // 成员UserID
        String userId = sensitiveInfo.getStr("userid");
        // 查询用户详细信息
        JSONObject userDetail = wxUtil.getUserDetail(wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret()), userId);
        String name = userDetail.getStr("name");
        String avatar = sensitiveInfo.getStr("avatar");
        String email = sensitiveInfo.getStr("email");
        // 企业微信性别 0表示未定义，1表示男性，2表示女性
        String gender = sensitiveInfo.getStr("gender");
        // 主部门信息
        String mainDepartment = userDetail.getStr("main_department");

        // 查询是否有职工数据
//        EduStaff eduStaff = remoteStaffService.getStaffByWxOrMobileOrOpenId(userId, null, null, school.getDeptId()).getData();
        EduStaff eduStaff = remoteStaffService.getStaffByWxOrMobileOrOpenId(null, mobile, null, school.getDeptId()).getData();
        if (Objects.isNull(eduStaff)) {
            eduStaff = new EduStaff();
            eduStaff.setName(name);
            eduStaff.setMobile(mobile);
            eduStaff.setAvatar(avatar);
            eduStaff.setEmail(email);
            eduStaff.setSex("1".equals(gender) ? "0" : "2".equals(gender) ? "1" : "2");
            eduStaff.setWxId(userId);
            eduStaff.setSchoolId(school.getDeptId());
            eduStaff.setSchoolName(school.getDeptName());
            eduStaff.setPosition(userDetail.getStr("position"));
        } else {
            // 修改不创建到企业微信的职工数据
            if (eduStaff.getWxPath() == 1) {
                // 修改手机号码、用户id
                eduStaff.setWxId(userId);
                eduStaff.setWxPath(0);
            }
        }

        // 判断是否存在登录用户信息
        SystemUser user = findUserDetail(mobile);
        if (user == null) {
            user = new SystemUser();
            user.setAvatar(avatar);
            user.setMobile(mobile);
            user.setEmail(email);
            user.setUsername(mobile);
            user.setNickname(name);
            user.setDeptId(school.getDeptId());
            user.setStatus("1");
            // 用户性别 0男, 1女, 2保密
            user.setSex("1".equals(gender) ? "0" : "2".equals(gender) ? "1" : "2");
            user.setUserOrigin(0);
            user.setUserType(1);
            createUser(user);
            eduStaff.setYidaAppUserId(user.getYidaAppUserId());
            eduStaff.setSysUserId(user.getUserId());
        } else {
            eduStaff.setSysUserId(user.getUserId());
        }

        // 成员部门信息
        JSONArray departmentList = userDetail.getJSONArray("department");
        JSONArray leaderInDept = userDetail.getJSONArray("is_leader_in_dept");
        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
                        : deptService.getSysDeptByDeptAndWx(Collections.singletonList(school.getDeptId()), staffDept.getDeptWxId()));
                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);
        }
        remoteTeacherService.saveStaffBySchoolAndWx(eduStaff);
    }
}

