package cn.iocoder.yudao.module.system.service.auth;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.common.util.string.StringUtil;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.api.wechat.CorpWechatApi;
import cn.iocoder.yudao.module.system.api.wechat.dto.CorpUserResponse;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantPackageDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialClientMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantPackageMapper;
import cn.iocoder.yudao.module.system.enums.common.BooleanEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.EnterpriseWeChatConstants;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.iocoder.yudao.module.system.enums.permission.RoleCodeEnum;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import cn.iocoder.yudao.module.system.service.biz.GroupsService;
import cn.iocoder.yudao.module.system.service.logger.LoginLogService;
import cn.iocoder.yudao.module.system.service.member.MemberService;
import cn.iocoder.yudao.module.system.service.oauth2.OAuth2TokenService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.social.SocialUserService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.system.util.http.HttpClientResult;
import cn.iocoder.yudao.module.system.util.http.HttpClientUtil;
import cn.iocoder.yudao.module.system.util.oauth2.AESUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.google.common.annotations.VisibleForTesting;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.singleton;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO.PACKAGE_ID_SYSTEM;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.oauth2.EnterpriseWeChatConstants.*;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * Auth Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private SocialUserService socialUserService;
    @Resource
    private MemberService memberService;
    @Resource
    private Validator validator;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private GroupsService groupsService;

    @Resource
    private RoleService roleService;

    @Resource
    private SocialClientMapper socialClientMapper;

    @Resource
    private CorpWechatApi corpWechatApi;

    @Resource
    private TenantMapper tenantMapper;

    @Resource
    private TenantPackageMapper tenantPackageMapper;

    /**
     * 验证码的开关，默认为 true
     */
    @Value("${yudao.captcha.enable:true}")
    private Boolean captchaEnable;

    @Override
    public AdminUserDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        AdminUserDO user;

        user = userService.getUserByMobile(username);
        if (user == null){
            user = userService.getUserByUsername(username);
        }

//        if (checkIsPhoneNumber(username)) {
//            user = userService.getUserByMobile(username);
//            if (user == null){
//                user = userService.getUserByUsername(username);
//            }
//        } else {
//            user = userService.getUserByUsername(username);
//        }
        // 校验账号是否存在
        if (user == null) {
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private boolean checkIsPhoneNumber(String username) {
        String regex = "^1[3-9]\\d{9}$";
        return username.matches(regex);
    }

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // 校验验证码
//        validateCaptcha(reqVO);

        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }
        // TODO 校验权限
        checkGroupsRole(user, reqVO.getUsername(), reqVO.getLoginPlatform(), reqVO.getLoginDevice());
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public AuthLoginRespVO mobileLogin(AuthLoginReqVO reqVO) {
        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public AuthLoginRespVO smsLogin(AuthSmsLoginReqVO reqVO) {
        // 校验验证码
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP()));

        // 获得用户信息
        AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE);
    }

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        AdminUserDO user = userService.getUser(userId);

        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        reqDTO.setNickName(user == null ? null : user.getNickname());
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogService.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, ServletUtils.getClientIP());
        }
    }

    @Override
    public AuthLoginRespVO socialLogin(AuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserService.getSocialUserByCode(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null || socialUser.getUserId() == null) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 获得用户
        AdminUserDO user = userService.getUser(socialUser.getUserId());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            return;
        }
        // 校验验证码
        ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification());
        ResponseModel response = captchaService.verification(captchaVO);
        // 验证不通过
        if (!response.isSuccess()) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType().getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    @Override
    public void checkGroupsRole(AdminUserDO user, String username, Integer loginPlatform, Integer loginDevice) {
        //todo 超级租户权限全开
        if (user.getIsHasAdmin().equals(BooleanEnum.TRUE.getValue())){
            return;
        }

        //处理登录平台是否跟租户一致性，集团账号只能集团登录
        TenantDO tenantDO = tenantMapper.selectById(user.getTenantId());
        if (tenantDO.getGroupsManager().equals(BooleanEnum.TRUE.getValue())){
            if (StringUtils.isBlank(user.getIsEnableEnterpriseLogin()) && !Objects.equals(tenantDO.getGroupsManager(), loginPlatform)){
                throw exception(AUTH_LOGIN_USER_NOT_PERMISSION);
            }
//            if (!Objects.equals(user.getIsEnableEnterpriseLogin(), BooleanEnum.TRUE.getValue()) && Objects.equals(loginPlatform, BooleanEnum.FALSE.getValue())){
//                throw exception(AUTH_LOGIN_USER_NOT_PERMISSION);
//            }
        }else {
            if (!Objects.equals(tenantDO.getGroupsManager(), loginPlatform)){
                throw exception(AUTH_LOGIN_USER_NOT_PERMISSION);
            }
        }

        //处理登录端是否有对应的角色权限
        log.info("租户ID ： {},用户ID ： {}======================>",user.getTenantId(),user.getId());
        List<RoleDO> roleList = roleService.getRoleListByDeviceTypeAndUserId(user.getTenantId(),user.getId());
        if (CollectionUtil.isEmpty(roleList)) {
            throw exception(AUTH_LOGIN_USER_NOT_PERMISSION);
        }

        // TODO 还未处理完
        if (!groupsService.checkGroupsRole(user, loginPlatform, loginDevice)) {
            createLoginLog(user.getId(), username, LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.USER_DISABLED);
//            throw exception(AUTH_LOGIN_USER_NOT_PERMISSION);
        }
    }

    @Override
    @TenantIgnore
    public String corpAuth2Redirect(String redirectUri) {
        TenantDO tenantDO = tenantMapper.selectOne(new LambdaQueryWrapperX<TenantDO>().eq(TenantDO::getPackageId, PACKAGE_ID_SYSTEM));
        SocialClientDO client = socialClientMapper.selectOne(SocialTypeEnum.WECHAT_ENTERPRISE.getType(), UserTypeEnum.ADMIN.getValue(), tenantDO.getId());
        Assert.notNull(client, String.format("第三方(%d) 不存在", SocialTypeEnum.WECHAT_ENTERPRISE.getType()));
//        redirectUri += "?todoUrl=" + todoUrl + "&processInstanceId=" + processInstanceId;
        // 进行encodeURIComponent编码
        try {
            redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw exception(COMMON_ERROR);
        }
        String formatUrl = String.format(EnterpriseWeChatConstants.OAUTH2_AUTHORIZE_URL, client.getClientId(), redirectUri, "", client.getAgentId());
        return formatUrl;
    }

    @Override
    @DSTransactional
    @TenantIgnore
    public AuthLoginRespVO corpAuth2Check(String code) {
        CorpUserResponse corpUserResponse = getUser(code);
        List<AdminUserDO> userList = authenticateCorpUser(corpUserResponse);
        // TODO 登陆授权s
//        List<AdminUserDO> userList = userService.getUserTenantIgnoreByMobile("13642730363");

        if (null == userList || userList.size() == 0) {
            throw exception(UNRECOGNIZED_LOGIN_IDENTITY);
        }

        List<TenantDO> tenantDOList =  getTenantList(userList);
        if (null == tenantDOList || tenantDOList.size() == 0) {
            throw exception(UNRECOGNIZED_LOGIN_IDENTITY);
        }
        Map<Long, TenantDO> tenantMap = tenantDOList.stream().collect(Collectors.toMap(TenantDO::getId, a -> a));
        Map<Long, AdminUserDO> adminUserMap = userList.stream()
                .collect(Collectors.toMap(
                        AdminUserDO::getTenantId, // 键字段（需检查实际冲突字段）
                        Function.identity(),
                        (existing, replacement) -> existing // 合并策略
                ));
        Integer loginPlatform = null;
        Integer loginFlag = null;

        AuthLoginRespVO tokenAfterLoginSuccess = new AuthLoginRespVO();
        // 有集团优先默认进集团，企业账号优先进企业
        // 只有一种情况直接进入
        if (userList.size() == 1) {
            AdminUserDO adminUserDO = userList.get(0);
            TenantDO tenantDO = tenantMap.get(adminUserDO.getTenantId());
            if (1 == tenantDO.getGroupsManager()) {
                loginFlag = 1;
                if (StringUtil.isNotEmptyORNull(adminUserDO.getIsEnableEnterpriseLogin())) {
                    loginFlag = 2;
                }

                loginPlatform = tenantDO.getGroupsManager();
            } else if (0 == tenantDO.getGroupsManager()){
                loginFlag = 0;
                loginPlatform = tenantDO.getGroupsManager();
            }
            checkGroupsRole(adminUserDO, adminUserDO.getUsername(), loginPlatform, null);


            TenantContextHolder.setTenantId(adminUserDO.getTenantId());
            tokenAfterLoginSuccess = createTokenAfterLoginSuccess(adminUserDO.getId(), adminUserDO.getUsername(), LoginLogTypeEnum.LOGIN_CORP);
            tokenAfterLoginSuccess.setTenantId(adminUserDO.getTenantId());
            tokenAfterLoginSuccess.setUsername(adminUserDO.getUsername());
            tokenAfterLoginSuccess.setTenantName(tenantDO.getName());
            tokenAfterLoginSuccess.setLoginPlatform(loginPlatform);
            tokenAfterLoginSuccess.setLoginFlag(loginFlag);
            return tokenAfterLoginSuccess;

        }

        tenantDOList.forEach(tenantDO -> {
            AdminUserDO adminUserDO = adminUserMap.get(tenantDO.getId());
            String[] packageIdArr = StringUtil.isEmptyORNull(tenantDO.getPackageId())? new String[]{} : tenantDO.getPackageId().split(",");
            List<TenantPackageDO> tenantPackageDOS = tenantPackageMapper.selectList(new LambdaQueryWrapperX<TenantPackageDO>().in(TenantPackageDO::getId, packageIdArr));
            // 拼接套餐名称
            String packageNames = tenantPackageDOS.stream().map(TenantPackageDO::getName).collect(Collectors.joining(","));
            tenantDO.setPackageNames(packageNames);
            if (1 == tenantDO.getGroupsManager()) {
                tenantDO.setLoginFlag(1);
                if (StringUtil.isNotEmptyORNull(adminUserDO.getIsEnableEnterpriseLogin())) {
                    tenantDO.setLoginFlag(2);
                }
            } else if (0 == tenantDO.getGroupsManager()){
                tenantDO.setLoginFlag(0);
            }
            try {
                tenantDO.setLoginUserId(AESUtils.encryptCbc(String.valueOf(adminUserDO.getId()), AESUtils.generateFixedKey()));
            } catch (Exception e) {
                e.printStackTrace();
                throw exception(UNRECOGNIZED_LOGIN_IDENTITY);

            }
        });

        tokenAfterLoginSuccess.setTenantDOList(tenantDOList);

        return tokenAfterLoginSuccess;
    }

    @Override
    @TenantIgnore
    public AuthLoginRespVO checkTenantLogin(Long tenantId, String tenantName, String loginUserId, Integer loginPlatform) {
        try {
            String decryptCbcStr = AESUtils.decryptCbc(loginUserId, AESUtils.generateFixedKey());
            if (StringUtil.isEmptyORNull(decryptCbcStr)) {
                throw exception(UNRECOGNIZED_LOGIN_IDENTITY);
            }

            AdminUserDO adminUserDO = userService.getUserTenantIgnore(Long.valueOf(decryptCbcStr));
            checkGroupsRole(adminUserDO, adminUserDO.getUsername(), loginPlatform, null);

            TenantContextHolder.setTenantId(adminUserDO.getTenantId());
            AuthLoginRespVO tokenAfterLoginSuccess = createTokenAfterLoginSuccess(adminUserDO.getId(), adminUserDO.getUsername(), LoginLogTypeEnum.LOGIN_CORP);
            tokenAfterLoginSuccess.setTenantId(adminUserDO.getTenantId());
            tokenAfterLoginSuccess.setUsername(adminUserDO.getUsername());
            tokenAfterLoginSuccess.setTenantName(tenantName);
            tokenAfterLoginSuccess.setLoginPlatform(loginPlatform);
            tokenAfterLoginSuccess.setLoginFlag(null);
            return tokenAfterLoginSuccess;
        } catch (Exception e) {
            e.printStackTrace();
            throw exception(UNRECOGNIZED_LOGIN_IDENTITY);

        }
    }

    private List<TenantDO> getTenantList(List<AdminUserDO> userList) {
        Set<Long> tenantIds = userList.stream().map(AdminUserDO::getTenantId).collect(Collectors.toSet());
        List<TenantDO> tenantDOS = tenantMapper.selectList(new LambdaQueryWrapperX<TenantDO>()
                .eq(TenantDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .in(TenantDO::getId, tenantIds));
        return tenantDOS;
    }


    private List<AdminUserDO> authenticateCorpUser(CorpUserResponse corpUserResponse) {
        List<AdminUserDO> userDOList = userService.getUserTenantIgnoreByMobile(corpUserResponse.getMobile());
//        if (null == userDOList || userDOList.size() == 0) {
//            throw exception(UNRECOGNIZED_LOGIN_IDENTITY);
//        }
//        AdminUserDO adminUserDO = userDOList.get(0);
//        if (adminUserDO == null) {
//            throw exception(UNRECOGNIZED_LOGIN_IDENTITY);
//        }
//        if (StringUtil.isEmptyORNull(adminUserDO.getCorpUserId())) {
//            UserSaveReqVO updateDO = new UserSaveReqVO();
//            updateDO.setId(adminUserDO.getId());
//            updateDO.setCorpUserId(corpUserResponse.getUserid());
//            userService.updateUser(updateDO);
//        }
        return userDOList;
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        AdminUserDO user = userService.getUser(userId);
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        reqDTO.setNickName(user == null ? null : user.getNickname());
        if (ObjectUtil.equal(getUserType().getValue(), userType)) {
            reqDTO.setUsername(getUsername(userId));
        } else {
            reqDTO.setUsername(memberService.getMemberUserMobile(userId));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(reqDTO);
    }

    private String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getUser(userId);
        return user != null ? user.getUsername() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }

    public CorpUserResponse getUser(String code) {
        CorpUserResponse corpUserResponse = corpWechatApi.getUserByCode(code);
        CorpUserResponse userByUserTicket = corpWechatApi.getUserByUserTicket(corpUserResponse.getUserTicket());
        return userByUserTicket;
    }


}
