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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.StrUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
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.sms.dto.code.SmsCodeUseReqDTO;
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.controller.admin.auth.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.authentication.vo.AuthenticationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.authentication.AuthenticationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.authentication.AuthenticationMapper;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserBindMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
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.OAuth2ClientConstants;
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.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.social.SocialUserService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.system.util.DingtalkUtil;
import com.dingtalk.api.response.OapiV2UserGetResponse;
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.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 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 SocialUserBindMapper socialUserBindMapper;
    @Value("${oa.user}")
    private String oaUser;
    /**
     * 验证码的开关，默认为 true
     */
    @Value("${yudao.captcha.enable:true}")
    @Setter // 为了单测：开启或者关闭验证码
    private Boolean captchaEnable;

    @Resource
    private AuthenticationMapper authenticationMapper;
    @Resource
    private AdminUserMapper userMapper;

    @Override
    public AdminUserDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        AdminUserDO 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;
    }

    @Override
    public AuthLoginRespVO simpleLogin(Long id) {
        AdminUserDO user = userService.getUser(id);

        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public AuthLoginRespVO oaLogin() {
        AdminUserDO user = userService.getUserByUsername(oaUser);
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @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()));
        }
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 如果是重置密码场景，需要校验图形验证码是否正确
        if (Objects.equals(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene(), reqVO.getScene())) {
            ResponseModel response = doValidateCaptcha(reqVO);
            if (!response.isSuccess()) {
                throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, response.getRepMsg());
            }
        }

        // 登录场景，验证是否存在
        UserPageReqVO userReqVO = new UserPageReqVO();
        userReqVO.setMobile(reqVO.getMobile());
        List<AdminUserDO> users = userService.users(userReqVO);
        if (CollUtil.isEmpty(users)) {
            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());
        UserPageReqVO userReqVO = new UserPageReqVO();
        userReqVO.setMobile(reqVO.getMobile());
        List<AdminUserDO> users = userService.users(userReqVO);
        if (CollUtil.isEmpty(users)) {
            throw exception(USER_NOT_EXISTS);
        }
        Long pmsUserId = null;
        // 根据手机号获取用户信息
        try {
            String dingUserId = DingtalkUtil.getUserInfoByMobile(reqVO.getMobile());
            if (StrUtil.isBlank(dingUserId)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 根据钉钉用户id 查询用户详情
            OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(dingUserId);
            if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 工号
            String jobNumber = userDetail.getJobNumber();
            List<Long> userIds = new ArrayList<>();
            users.forEach(user -> {
                if (StrUtil.isNotBlank(jobNumber) && jobNumber.equals(user.getUsername())) {
                    userIds.add(user.getId());
                }
            });
            if (CollUtil.isEmpty(userIds)) {
                throw exception(USER_NOT_EXISTS);
            }
            pmsUserId = userIds.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjUtil.isEmpty(pmsUserId)) {
            throw exception(USER_NOT_EXISTS);
        }
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(pmsUserId, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE);
    }

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        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 ) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }
        try {
            // 获得绑定用户
            SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(UserTypeEnum.ADMIN.getValue(),
                    socialUser.getUserId());
            AdminUserDO user;
            if (Objects.isNull(socialUserBind)) {
                String userId = DingtalkUtil.getUserIdByUnion(socialUser.getUnionId());
                OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(userId);
                user = userService.getUserByUsername(userDetail.getJobNumber());
                // 绑定钉钉
                SocialUserBindDO newSocialUserBind = SocialUserBindDO.builder()
                        .userId(user.getId()).userType(UserTypeEnum.ADMIN.getValue())
                        .socialUserId(socialUser.getUserId()).socialType(SocialTypeEnum.DINGTALK.getType()).build();
                socialUserBindMapper.insert(newSocialUserBind);
            } else {
                user = userService.getUser(socialUserBind.getUserId());
            }
            // 获得用户
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            // 创建 Token 令牌，记录登录日志
            return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AuthLoginRespVO appSocialLogin(AuthSocialLoginReqVO reqVO) {
        try {
            String accessToken = DingtalkUtil.getUserToken(reqVO.getCode());
            System.out.println("通过授权码获取 accessToken：" + accessToken);
            // 通过 accessToken 获取 用户信息 对比数据库中存储的用户信息 发放平台 token
            if (StrUtil.isEmpty(accessToken)) {
                throw exception(USER_NOT_EXISTS);
            }
            Map<String, String> resultMap = DingtalkUtil.getUserInfo(accessToken);
            if (CollUtil.isEmpty(resultMap)) {
                throw exception(USER_NOT_EXISTS);
            }
            String mobile = resultMap.get("mobile");
            String unionId = resultMap.get("unionId");
            // 根据unionId查询钉钉用户id
            String dingUserId = DingtalkUtil.getUserIdByUnion(unionId);
            // 根据钉钉用户id 查询用户详情
            OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(dingUserId);
            if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 工号
            String jobNumber = userDetail.getJobNumber();
            // 查询当前用户表中 此手机号 是否存在
            // AdminUserDO user = userService.getUserByMobile(mobile);

            UserPageReqVO userReqVO = new UserPageReqVO();
            userReqVO.setMobile(mobile);
            List<AdminUserDO> users = userService.users(userReqVO);
            if (CollUtil.isEmpty(users)) {
                throw exception(USER_NOT_EXISTS);
            }
            List<Long> userIds = new ArrayList<>();
            List<String> usernames = new ArrayList<>();
            users.forEach(loginUser -> {
                if (StrUtil.isNotBlank(jobNumber) && jobNumber.equals(loginUser.getUsername())) {
                    userIds.add(loginUser.getId());
                    usernames.add(jobNumber);
                }
            });
            if (CollUtil.isEmpty(userIds) || CollUtil.isEmpty(usernames)) {
                throw exception(USER_NOT_EXISTS);
            }
            Long pmsUserId = userIds.get(0);
            String username = usernames.get(0);

            // 创建 Token 令牌，记录登录日志
            return createTokenAfterLoginSuccess(pmsUserId, username, LoginLogTypeEnum.LOGIN_DING_APP);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AuthLoginRespVO h5SocialLogin(AuthSocialLoginReqVO reqVO) {
        // h5页面获取免登录授权码code 后台通过code查询用户信息
        String validCode = StrUtils.xssEncode(reqVO.getCode());
        try {
            // 钉钉用户id
            String userId = DingtalkUtil.getUserIdByAuthCode(validCode);
            if (StrUtil.isBlank(userId)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 根据钉钉用户id 查询用户详情
            OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(userId);
            if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 工号
            String jobNumber = userDetail.getJobNumber();
            // 手机号
            String mobile = userDetail.getMobile();
            if (StrUtil.isBlank(mobile)) {
                throw exception(USER_NOT_EXISTS);
            }
            // 查询当前用户表中 此手机号 是否存在
            // AdminUserDO user = userService.getUserByMobile(mobile);
            // 可能多个用户使用了相同的手机号
            UserPageReqVO userReqVO = new UserPageReqVO();
            userReqVO.setMobile(mobile);
            List<AdminUserDO> users = userService.users(userReqVO);
            if (CollUtil.isEmpty(users)) {
                throw exception(USER_NOT_EXISTS);
            }
            List<Long> userIds = new ArrayList<>();
            List<String> usernames = new ArrayList<>();
            users.forEach(user -> {
                if (StrUtil.isNotBlank(jobNumber) && jobNumber.equals(user.getUsername())) {
                    userIds.add(user.getId());
                    usernames.add(jobNumber);
                }
            });
            if (CollUtil.isEmpty(userIds) || CollUtil.isEmpty(usernames)) {
                throw exception(USER_NOT_EXISTS);
            }
            Long pmsUserId = userIds.get(0);
            String username = usernames.get(0);
            // 创建 Token 令牌，记录登录日志 h5钉钉微应用登录
            return createTokenAfterLoginSuccess(pmsUserId, username, LoginLogTypeEnum.LOGIN_DING_H5);
        } catch (Exception e) {
            // 调用钉钉接口报错 提示 登录失败
            e.printStackTrace();
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public AuthLoginRespVO portalLogin(AuthPortalLoginReqVO reqVO) {
        try {
            if (StrUtil.isBlank(reqVO.getUsername())) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 查询当前用户表中 用户 是否存在
            AdminUserDO user = userMapper.selectByUsername(reqVO.getUsername());
            if (ObjUtil.isEmpty(user)) {
                throw exception(USER_NOT_EXISTS);
            }
            // 创建 Token 令牌，记录登录日志 portal
            return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_PORTAL);
        } catch (Exception e) {
            // 调用钉钉接口报错 提示 登录失败
            e.printStackTrace();
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public AuthLoginRespVO portalSsoLogin(AuthPortalSsoLoginReqVO reqVO) {
        if (StrUtil.isBlank(reqVO.getCode())) {
            // 查询不到用户详情 返回 登录失败
            throw exception(OAUTH2_CODE_NOT_EXISTS);
        }
        AuthenticationPageReqVO authReqVO = new AuthenticationPageReqVO();
        authReqVO.setRandomCode(reqVO.getCode());
        List<AuthenticationDO> authentications = authenticationMapper.selectList(authReqVO);
        if (CollUtil.isNotEmpty(authentications)) {
            AuthenticationDO auth = authentications.get(0);
            // 如果随机码的创建时间 距离现在已经超过5分钟 则失效
            LocalDateTime createTime = auth.getCreateTime();
            LocalDateTime now = LocalDateTime.now();
            // 计算时间差，如果超过5分钟则返回null
            Duration duration = Duration.between(createTime, now);
            if (duration.toMinutes() > 5) {
                // 随机码已失效，不再生成token
                return null;
            }
            // 创建 Token 令牌，记录登录日志 portal
            return createTokenAfterLoginSuccess(auth.getUserid(), auth.getJobNumber(), LoginLogTypeEnum.LOGIN_PORTAL);
        }
        return null;
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        ResponseModel response = doValidateCaptcha(reqVO);
        // 校验验证码
        if (!response.isSuccess()) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    private ResponseModel doValidateCaptcha(CaptchaVerificationReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            return ResponseModel.success();
        }
        ValidationUtils.validate(validator, reqVO, CaptchaVerificationReqVO.CodeEnableGroup.class);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification());
        return captchaService.verification(captchaVO);
    }

    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);
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        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;
    }

    @Override
    public AuthLoginRespVO register(AuthRegisterReqVO registerReqVO) {
        // 1. 校验验证码
        validateCaptcha(registerReqVO);

        // 2. 校验用户名是否已存在
        Long userId = userService.registerUser(registerReqVO);

        // 3. 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(userId, registerReqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @VisibleForTesting
    void validateCaptcha(AuthRegisterReqVO reqVO) {
        ResponseModel response = doValidateCaptcha(reqVO);
        // 验证不通过
        if (!response.isSuccess()) {
            throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(AuthResetPasswordReqVO reqVO) {
        // AdminUserDO userByMobile = userService.getUserByMobile(reqVO.getMobile());

        UserPageReqVO userReqVO = new UserPageReqVO();
        userReqVO.setMobile(reqVO.getMobile());
        List<AdminUserDO> users = userService.users(userReqVO);

        if (CollUtil.isEmpty(users)) {
            throw exception(USER_MOBILE_NOT_EXISTS);
        }
        Long pmsUserId = null;
        // 根据手机号获取钉钉用户id
        try {
            String dingUserId = DingtalkUtil.getUserInfoByMobile(reqVO.getMobile());
            if (StrUtil.isBlank(dingUserId)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_MOBILE_NOT_EXISTS);
            }
            // 根据钉钉用户id 查询用户详情
            OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(dingUserId);
            if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_MOBILE_NOT_EXISTS);
            }
            // 工号
            String jobNumber = userDetail.getJobNumber();
            List<Long> userIds = new ArrayList<>();
            users.forEach(user -> {
                if (StrUtil.isNotBlank(jobNumber) && jobNumber.equals(user.getUsername())) {
                    userIds.add(user.getId());
                }
            });
            if (CollUtil.isEmpty(userIds)) {
                throw exception(USER_MOBILE_NOT_EXISTS);
            }
            pmsUserId = userIds.get(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjUtil.isEmpty(pmsUserId)) {
            throw exception(USER_MOBILE_NOT_EXISTS);
        }

        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO()
                .setCode(reqVO.getCode())
                .setMobile(reqVO.getMobile())
                .setScene(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene())
                .setUsedIp(getClientIP())
        );

        userService.updateUserPassword(pmsUserId, reqVO.getPassword());
    }

    @Override
    public String ssoGetToken(AuthPortalLoginReqVO reqVO) {
        // 如果 当前用户表中存在 username 则返回随机 uuid 并存储到表 system_authentication
        // 查询当前用户表中 用户 是否存在
        AdminUserDO user = userMapper.selectByUsername(reqVO.getUsername());
        if (ObjUtil.isEmpty(user)) {
            throw exception(USER_NOT_EXISTS);
        }
        // 这里不生成pms令牌 先返回随机code
        String randomCode = UUID.randomUUID().toString();
        AuthenticationDO authentication = new AuthenticationDO();
        authentication.setUserid(user.getId());
        authentication.setJobNumber(reqVO.getUsername());
        authentication.setRandomCode(randomCode);
        authenticationMapper.insert(authentication);
        return randomCode;
    }
}
