package com.xindazhou.user.service.auth;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.xindazhou.framework.common.enums.CommonStatusEnum;
import com.xindazhou.framework.common.enums.TerminalEnum;
import com.xindazhou.framework.common.enums.UserTypeEnum;
import com.xindazhou.framework.common.util.monitor.TracerUtils;
import com.xindazhou.framework.common.util.servlet.ServletUtils;
import com.xindazhou.user.controller.app.auth.vo.*;
import com.xindazhou.user.convert.auth.AuthConvert;
import com.xindazhou.user.dal.dataobject.user.MemberUserDO;
import com.xindazhou.user.service.user.MemberUserService;
import com.xindazhou.framework.common.biz.infra.logger.LoginLogCommonApi;
import com.xindazhou.framework.common.biz.infra.logger.dto.LoginLogCreateReqDTO;
import com.xindazhou.user.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.xindazhou.framework.common.biz.system.oauth2.dto.OAuth2AccessTokenRespDTO;
import com.xindazhou.business.api.sms.SmsCodeApi;
import com.xindazhou.business.api.social.SocialClientApi;
import com.xindazhou.business.api.social.SocialUserApi;
import com.xindazhou.framework.social.core.dto.SocialUserBindReqDTO;
import com.xindazhou.framework.social.core.dto.SocialUserRespDTO;
import com.xindazhou.framework.social.core.dto.SocialWxPhoneNumberInfoRespDTO;
import com.xindazhou.business.enums.logger.LoginLogTypeEnum;
import com.xindazhou.business.enums.logger.LoginResultEnum;
import com.xindazhou.business.enums.oauth2.OAuth2ClientConstants;
import com.xindazhou.business.enums.sms.SmsSceneEnum;
import com.xindazhou.business.enums.social.SocialTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.xindazhou.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static com.xindazhou.user.enums.ErrorCodeConstants.*;

/**
 * 会员的认证 Service 接口
 *
 * @author hmy
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    @Resource
    private MemberUserService userService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private LoginLogCommonApi loginLogCommonApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private com.xindazhou.user.service.oauth2.OAuth2TokenService oauth2TokenService;

    @Resource
    private com.xindazhou.user.dal.mysql.user.MemberUserMapper memberUserMapper;

    @Resource
    private org.springframework.security.crypto.password.PasswordEncoder passwordEncoder;

    @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())).getCheckedData();
        }

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

    @Override
    @Transactional
    public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) {
        // 校验验证码
        String userIp = getClientIP();
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp)).checkError();

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp, getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }

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

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

    @Override
    @Transactional
    public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserApi.getSocialUserByCode(UserTypeEnum.MEMBER.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState()).getCheckedData();
        if (socialUser == null) {
            throw exception(AUTH_SOCIAL_USER_NOT_FOUND);
        }

        // 情况一：已绑定，直接读取用户信息
        MemberUserDO user;
        if (socialUser.getUserId() != null) {
            user = userService.getUser(socialUser.getUserId());
            // 情况二：未绑定，注册用户 + 绑定用户
        } else {
            user = userService.createUser(socialUser.getNickname(), socialUser.getAvatar(), getClientIP(), getTerminal());
            socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getType(), reqVO.getCode(), reqVO.getState())).checkError();
        }
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

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

    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) {
        // 获得对应的手机号信息
        SocialWxPhoneNumberInfoRespDTO phoneNumberInfo = socialClientApi.getWxMaPhoneNumberInfo(
                UserTypeEnum.MEMBER.getValue(), reqVO.getPhoneCode()).getCheckedData();
        Assert.notNull(phoneNumberInfo, "获得手机信息失败，结果为空");

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(),
                getClientIP(), TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 绑定社交用户
        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                SocialTypeEnum.WECHAT_MINI_PROGRAM.getType(), reqVO.getLoginCode(), reqVO.getState())).getCheckedData();

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

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(
                user.getId(), getUserType().getValue(), OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 转换为 DTO
        OAuth2AccessTokenRespDTO accessTokenRespDTO = com.xindazhou.framework.common.util.object.BeanUtils.toBean(
                accessTokenDO, OAuth2AccessTokenRespDTO.class);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
    }

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

    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 (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private void createLoginLog(Long userId, String mobile, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        try {
            // 插入登录日志（异步，不阻塞登录流程）
            LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
            reqDTO.setLogType(logType.getType());
            reqDTO.setTraceId(TracerUtils.getTraceId());
            reqDTO.setUserId(userId);
            reqDTO.setUserType(getUserType().getValue());
            reqDTO.setUsername(mobile);
            reqDTO.setUserAgent(ServletUtils.getUserAgent());
            reqDTO.setUserIp(getClientIP());
            reqDTO.setResult(loginResult.getResult());
            // 使用异步方法，即使失败也不影响登录流程
            loginLogCommonApi.createLoginLogAsync(reqDTO);
        } catch (Exception e) {
            // 日志记录失败不影响登录流程，只记录错误日志
            log.error("[createLoginLog][记录登录日志失败，不影响登录流程] userId={}, mobile={}, logType={}, loginResult={}", 
                    userId, mobile, logType, loginResult, e);
        }
        
        // 更新最后登录时间（这部分应该保留，因为不依赖日志表）
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            try {
                userService.updateUserLogin(userId, getClientIP());
            } catch (Exception e) {
                // 更新登录时间失败也不影响登录流程
                log.error("[createLoginLog][更新用户登录时间失败] userId={}", userId, e);
            }
        }
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.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());
            if (user != null && !Objects.equals(user.getId(), userId)) {
                throw exception(AUTH_MOBILE_USED);
            }
        }
        // 情况 2：如果是重置密码场景，需要校验手机号是存在的
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_RESET_PASSWORD.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile());
            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());
        }

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

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

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        // 转换为 DTO
        OAuth2AccessTokenRespDTO accessTokenRespDTO = com.xindazhou.framework.common.util.object.BeanUtils.toBean(
                accessTokenDO, OAuth2AccessTokenRespDTO.class);
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, null);
    }

    @Override
    @Transactional
    public AppAuthLoginRespVO register(AppAuthRegisterReqVO reqVO) {
        // 1. 校验手机号是否已注册
        MemberUserDO existUser = userService.getUserByMobile(reqVO.getMobile());
        if (existUser != null) {
            throw exception(AUTH_MOBILE_USED);
        }

        // 2. 校验验证码（如果提供了验证码才校验，暂时可选）
        String userIp = getClientIP();
        if (StrUtil.isNotEmpty(reqVO.getCode())) {
            // 如果提供了验证码，则进行校验
            com.xindazhou.business.api.sms.dto.code.SmsCodeUseReqDTO smsCodeUseReqDTO = 
                new com.xindazhou.business.api.sms.dto.code.SmsCodeUseReqDTO()
                    .setMobile(reqVO.getMobile())
                    .setCode(reqVO.getCode())
                    .setScene(SmsSceneEnum.MEMBER_REGISTER.getScene())
                    .setUsedIp(userIp);
            smsCodeApi.useSmsCode(smsCodeUseReqDTO).checkError();
        } else {
            // 未提供验证码，跳过校验（开发阶段，未接入验证码服务时使用）
            log.warn("注册时未提供验证码，跳过验证码校验（开发模式）");
        }

        // 3. 创建用户（带密码）
        MemberUserDO user = createUserWithPassword(reqVO.getMobile(), reqVO.getPassword(), userIp, getTerminal());
        Assert.notNull(user, "注册用户失败，结果为空");

        // 4. 校验是否禁用（虽然刚创建的用户应该是启用的，但为了安全还是检查一下）
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }

        // 5. 创建 Token 令牌，记录登录日志（注册成功后自动登录）
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE, null);
    }

    /**
     * 创建用户（带密码）
     */
    private MemberUserDO createUserWithPassword(String mobile, String password, String registerIp, Integer terminal) {
        // 插入用户
        MemberUserDO user = new MemberUserDO();
        user.setMobile(mobile);
        user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(passwordEncoder.encode(password)); // 加密密码
        user.setRegisterIp(registerIp).setRegisterTerminal(terminal);
        // 昵称为空时，随机一个名字
        user.setNickname("用户" + cn.hutool.core.util.RandomUtil.randomNumbers(6));
        memberUserMapper.insert(user);
        return user;
    }

    private void createLogoutLog(Long userId) {
        try {
            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());
            // 使用异步方法，即使失败也不影响登出流程
            loginLogCommonApi.createLoginLogAsync(reqDTO);
        } catch (Exception e) {
            // 日志记录失败不影响登出流程，只记录错误日志
            log.error("[createLogoutLog][记录登出日志失败，不影响登出流程] userId={}", userId, e);
        }
    }

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

}
