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

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.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.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.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.user.AdminUserDO;
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.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.PermissionService;
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 com.alibaba.fastjson.JSONObject;
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.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
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 PermissionService permissionService;
    @Resource
    private RoleService roleService;
    @Resource
    private PasswordEncoder passwordEncoder;



    /**
     * 验证码的开关，默认为 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 = 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 AdminUserDO authenticateApp(String username, String password,Long tenantId) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        AdminUserDO user = userService.getUserByUsername(username,tenantId);
        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 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 AuthLoginRespVO loginApp(AuthLoginReqVO reqVO,Long tenantId) {
        // 校验验证码
        validateCaptcha(reqVO);
        // 使用账号密码，进行登录
        AdminUserDO user = authenticateApp(reqVO.getUsername(), reqVO.getPassword(),tenantId);
        // 如果 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 (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) {
        // 插入登录日志
        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 || 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);
    }

    private AuthLoginRespVO createTokenAfterLoginSuccessCustomer(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, UserTypeEnum.MEMBER.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 AuthLoginRespVO wxLogin(String decryptResult, String openId, Long inviteId) {
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
        String phoneNumber =  jsonObject.getString("phoneNumber");
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        AdminUserDO wxUser = userService.selectUserByPhone(phoneNumber);
        //如果查不到，则新增，查到了，则更新
        return createTokenAfterLoginSuccess(wxUser.getId(), wxUser.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

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


    /**
     * 检测模块微信登录
     *
     * @param decryptResult 登录凭证 只能用一次
     * @return
     */
    public AuthLoginRespVO wxLoginRescue(String decryptResult,String openId,Long inviteId){
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
        System.out.println(jsonObject);
        System.out.println("openId"+openId);
        String phoneNumber =  jsonObject.getString("phoneNumber");
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        AdminUserDO wxUser = userService.getUserByMobile(phoneNumber);
        //如果查不到，则新增，查到了，则更新
        UserSaveReqVO user = new UserSaveReqVO();
        if (wxUser == null) {
            // 新增
            user.setUsername(phoneNumber);
            user.setNickname(phoneNumber);
            user.setMobile(phoneNumber);
            user.setPassword(passwordEncoder.encode("123456"));
            user.setRescueOpenId(openId);
            user.setId(1L);
            if (null!=inviteId){
                //绑定上级
                user.setInviteId(inviteId);
                //给上级进行积分奖励
//                userBalanceService.inviteRewards(inviteId);
            }
            user.setDeptId(100L);
            userService.createUser(user);

            List<RoleDO> jcyh = roleService.getRoleListByCodes(Collections.singletonList("jcyh"));
            Set<Long> ids = new HashSet<>();
            ids.add(jcyh.get(0).getId());
            permissionService.assignUserRole(user.getId(),ids);
        }else {
            //更新
            user.setId(wxUser.getId());
            user.setNickname(phoneNumber);
            user.setMobile(phoneNumber);
            user.setRescueOpenId(openId);
            user.setId(1L);
            if (ObjectUtil.isEmpty(user.getInviteId())){
                if (null!=inviteId){
                    //绑定上级
                    user.setInviteId(inviteId);
                    //给上级进行积分奖励
//                    userBalanceService.inviteRewards(inviteId);
                }
            }
            userService.updateUser(user);
        }

        // 生成token
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    @Override
    public AuthLoginRespVO wxLoginJc(String decryptResult, String openId, Long inviteId) {
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
        System.out.println(jsonObject);
        System.out.println("openId"+openId);
        String phoneNumber =  jsonObject.getString("phoneNumber");
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        AdminUserDO wxUser = userService.getUserByMobileWithoutTenant(phoneNumber);
        //如果查不到，则新增，查到了，则更新
        UserSaveReqVO user = new UserSaveReqVO();
        if (wxUser == null) {
            // 新增
            user.setUsername(phoneNumber);
            user.setNickname(phoneNumber);
            user.setMobile(phoneNumber);
            user.setPassword(passwordEncoder.encode("123456"));
            user.setJcOpenId(openId);
            user.setTenantId(180L);
            if (null!=inviteId){
                //绑定上级
                user.setInviteId(inviteId);
                //给上级进行积分奖励
//                userBalanceService.inviteRewards(inviteId);
            }
            user.setDeptId(100L);
            Long uid = userService.createUser(user);

            wxUser = new AdminUserDO();
            wxUser.setId(uid);
            wxUser.setUsername(phoneNumber);

            List<RoleDO> jcyh = roleService.getRoleListByCodes(Collections.singletonList("jcyh"));
            Set<Long> ids = new HashSet<>();
            ids.add(jcyh.get(0).getId());
            permissionService.assignUserRole(uid,ids);
        }else {
            //更新
            user.setId(wxUser.getId());
            user.setNickname(phoneNumber);
            user.setJcOpenId(openId);
            if (ObjectUtil.isEmpty(user.getInviteId())){
                if (null!=inviteId){
                    //绑定上级
                    user.setInviteId(inviteId);
                    //给上级进行积分奖励
//                    userBalanceService.inviteRewards(inviteId);
                }
            }
            userService.updateUser(user);
        }

        // 生成token
        return createTokenAfterLoginSuccess(wxUser.getId(), wxUser.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    /**
     * 根据用户id自动登录
     *
     * @param userId   用户id
     * @param userName 用户名称
     * @return cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO
     * @author vinjor-M
     * @date 12:17 2024/9/24
     **/
    @Override
    public AuthLoginRespVO wxLoginByUserId(Long userId, String userName) {
        // 生成token
        return createTokenAfterLoginSuccessCustomer(userId, userName, LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    /**
     * 微信小程序自动注册账号并登录
     *
     * @param decryptResult
     * @param openId        openId
     * @param inviteId
     * @return cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO
     * @author vinjor-M
     * @date 15:10 2024/9/27
     **/
    @Override
    public AuthLoginRespVO wxLoginRepair(String decryptResult, String openId, Long inviteId) {
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
        String phoneNumber =  jsonObject.getString("phoneNumber");
        //还可以获取其他信息
        //根据手机号判断数据库中是否有该用户
        AdminUserDO wxUser = userService.getUserByMobileWithoutTenant(phoneNumber);
        //如果查不到，则新增，查到了，则更新
        UserSaveReqVO user = new UserSaveReqVO();
        if (wxUser == null) {
            // 直接新注册一个账号
            user.setUsername(phoneNumber);
            user.setNickname(phoneNumber);
            user.setMobile(phoneNumber);
            user.setPassword(passwordEncoder.encode("123456"));
            user.setRepairOpenId(openId);
            //TODO 客户后期没有租户ID
            user.setTenantId(180L);
            if (null!=inviteId){
                //绑定上级
                user.setInviteId(inviteId);
                //给上级进行积分奖励
//                userBalanceService.inviteRewards(inviteId);
            }
            user.setDeptId(100L);
            Long uid = userService.createUser(user);
            wxUser = new AdminUserDO();
            wxUser.setId(uid);
            wxUser.setUsername(phoneNumber);
        }else {
            //更新
            user.setId(wxUser.getId());
            user.setRepairOpenId(openId);
            if (ObjectUtil.isEmpty(user.getInviteId())){
                if (null!=inviteId){
                    //绑定上级
                    user.setInviteId(inviteId);
                    //给上级进行积分奖励
//                    userBalanceService.inviteRewards(inviteId);
                }
            }
            userService.updateUser(user);
        }
        // 生成token
        return createTokenAfterLoginSuccess(wxUser.getId(), wxUser.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }
}
