package cn.newfeifan.mall.module.member.service.auth;

import cn.hutool.core.util.ObjectUtil;
import cn.newfeifan.mall.framework.common.enums.CommonStatusEnum;
import cn.newfeifan.mall.framework.common.enums.UserTypeEnum;
import cn.newfeifan.mall.framework.common.util.monitor.TracerUtils;
import cn.newfeifan.mall.framework.common.util.servlet.ServletUtils;
import cn.newfeifan.mall.module.member.controller.app.auth.vo.*;
import cn.newfeifan.mall.module.member.convert.auth.AuthConvert;
import cn.newfeifan.mall.module.member.dal.dataobject.user.MemberUserDO;
import cn.newfeifan.mall.module.member.service.user.MemberUserService;
import cn.newfeifan.mall.module.system.api.logger.LoginLogApi;
import cn.newfeifan.mall.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.newfeifan.mall.module.system.api.oauth2.OAuth2TokenApi;
import cn.newfeifan.mall.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.newfeifan.mall.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.newfeifan.mall.module.system.api.sms.SmsCodeApi;
import cn.newfeifan.mall.module.system.api.social.SocialClientApi;
import cn.newfeifan.mall.module.system.api.social.SocialUserApi;
import cn.newfeifan.mall.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.newfeifan.mall.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.newfeifan.mall.module.system.dal.dataobject.config.SystemConfigDO;
import cn.newfeifan.mall.module.system.dal.dataobject.user.AdminUserDO;
import cn.newfeifan.mall.module.system.enums.logger.LoginLogTypeEnum;
import cn.newfeifan.mall.module.system.enums.logger.LoginResultEnum;
import cn.newfeifan.mall.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.newfeifan.mall.module.system.enums.sms.SmsSceneEnum;
import cn.newfeifan.mall.module.system.service.auth.AdminAuthService;
import cn.newfeifan.mall.module.system.service.config.SystemConfigService;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.newfeifan.mall.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.newfeifan.mall.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static cn.newfeifan.mall.module.member.enums.DictTypeConstants.*;
import static cn.newfeifan.mall.module.member.enums.ErrorCodeConstants.*;

/**
 * 会员的认证 Service 接口
 *
 * @author 非繁源码
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    @Resource
    private MemberUserService userService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private LoginLogApi loginLogApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private OAuth2TokenApi oauth2TokenApi;
    @Resource
    private AdminAuthService authService;
    @Resource
    private SystemConfigService configService;
    @Resource
    private AdminUserService adminUserService;

    @Override
    public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) {
        // 使用用户名 + 密码，进行登录。
        MemberUserDO user = login0(reqVO.getMobile(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

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

    @Override
    public String redirectLogin() {

        MemberUserDO user = userService.getUser(getLoginUserId());
        AdminUserDO systemUser = adminUserService.getUser(user.getSystemUsersId());
        // 判断是否绑定系统用户
        if (systemUser == null) {
            throw exception(MEMBER_USER_NOT_BINDING_SYSTEM_USER);
        }

        // 系统url配置
        SystemConfigDO redisConfig = configService.getRedisConfig();
        AuthLoginRespVO token = authService.createTokenAfterLoginSuccess(systemUser.getId(), systemUser.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);

        // 跳转地址
        String url = redisConfig.getPlatformDomain();
        if (!systemUser.getCategoryId().equals(1L)) {
            url = redisConfig.getMerchantDomain();
        }

        return url + "/login" + "?accessToken=" + token.getAccessToken() + "&refreshToken=" + token.getRefreshToken();
    }

    @Override
    public void deleteUser(Long loginUserId) {
        userService.deleteUserById(loginUserId);
    }

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String username,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), username, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getId()).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
    }

    @Override
    public String getSocialAuthorizeUrl(Integer type, String redirectUri) {
        return socialClientApi.getAuthorizeUrl(type, UserTypeEnum.MEMBER.getValue(), redirectUri);
    }

    private MemberUserDO login0(String mobile, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_MOBILE;
        // 校验账号是否存在
        MemberUserDO user = userService.getUserByMobile(mobile);
        if (user == null) {
            createLoginLog(null, mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (ObjectUtil.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private void createLoginLog(Long userId, String username, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, getClientIP());
        }
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.removeAccessToken(token);
        if (accessTokenRespDTO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenRespDTO.getUserId());
    }

    @Override
    public void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO) {
        // 情况 1：如果是修改手机场景，需要校验新手机号是否已经注册，说明不能使用该手机了
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile(), userId);
            if (user == null) {
                throw exception(USER_MOBILE_IS_ERROR);
            }
        }
        // 情况 2：如果是重置密码场景，需要校验手机号是存在的
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_RESET_PASSWORD.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile(), userId);
            if (user == null) {
                throw exception(USER_MOBILE_NOT_EXISTS);
            }
        }
        // 情况 3：如果是修改密码场景，需要查询手机号，无需前端传递
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_PASSWORD.getScene())) {
            MemberUserDO user = userService.getUser(userId);
            // TODO 非繁人：后续 member user 手机非强绑定，这块需要做下调整；
            reqVO.setMobile(user.getMobile());
        }
        //情况 4:如果是修改手机号时,输入新的手机号,需要校验手机号是否绑定上限
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_NEW_MOBILE.getScene())) {
            verifyMobileIsMaximize(reqVO.getMobile());
        }

        // 执行发送
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public void validateSmsCode(Long userId, AppAuthSmsValidateReqVO reqVO) {
        smsCodeApi.validateSmsCode(AuthConvert.INSTANCE.convert(reqVO));
    }

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenRespDTO accessTokenDO = oauth2TokenApi.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO, null);
    }

    @Override
    public AppAuthLoginRespVO smsRegister(AppAuthSmsRegisterReqVO reqVO) {
        //校验手机号是否存在
        verifyMobileIsExist(reqVO.getMobile());

        //校验用户名
        verifyUsername(reqVO.getUsername());

        //创建用户
        MemberUserDO user = userService.createUser(reqVO.getMobile(), reqVO.getUsername(), DEFAULT_AVATAR, getClientIP(), getTerminal(), reqVO.getLinkId(), reqVO.getUsername(), reqVO.getPassword());
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, null);
    }

    /**
     * 校验手机号是否达到上限
     *
     * @param mobile 手机号
     */
    private void verifyMobileIsMaximize(String mobile) {
        //如果手机号已经到达注册的上限了那就返回报错
        if (userService.getUserCountByMobile(mobile) >= MOBILE_REGISTER_MAX) {
            throw exception(MOBILE_IS_MAXIMIZE);
        }
    }

    /**
     * 校验用户名
     *
     * @param username 用户名
     */
    private void verifyUsername(String username) {
        if (userService.selectCountByUsername(username) > 0) {
            throw exception(AUTH_USERNAME_EXISTS);
        }
    }

    /**
     * 校验手机号
     *
     * @param mobile 手机号
     */
    private void verifyMobileIsExist(String mobile) {
        if (userService.getUserCountByMobile(mobile) >= 1) {
            throw exception(AUTH_MOBILE_USED);
        }
    }

    private void createLogoutLog(Long userId) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(LoginLogTypeEnum.LOGOUT_SELF.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(getMobile(userId));
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogApi.createLoginLog(reqDTO);
    }

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

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

}
