package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import com.ruoyi.bst.app.domain.AppVO;
import com.ruoyi.bst.app.domain.enums.AppType;
import com.ruoyi.bst.app.service.AppConverter;
import com.ruoyi.bst.app.service.AppService;
import com.ruoyi.bst.userApp.service.UserAppService;
import com.ruoyi.common.auth.wx.WxAuthService;
import com.ruoyi.common.auth.wx.config.WxConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.WxLoginBody;
import com.ruoyi.common.core.domain.vo.UserVO;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.ApplicationConfig;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.system.config.service.ConfigService;
import com.ruoyi.system.user.service.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class SysLoginService
{

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    private final AuthenticationEntryPointImpl authenticationEntryPointImpl;

    private final ApplicationConfig applicationConfig;
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private AppService appService;

    @Autowired
    private AppConverter appConverter;

    @Autowired
    private WxAuthService wxAuthService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    SysLoginService(ApplicationConfig applicationConfig, AuthenticationEntryPointImpl authenticationEntryPointImpl, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.applicationConfig = applicationConfig;
        this.authenticationEntryPointImpl = authenticationEntryPointImpl;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        UserVO user = userService.selectUserByUserName(username);
        ServiceUtil.assertion(user == null, "用户不存在");

        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);

        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
            authenticationToken.setDetails(Constants.LOGIN_TYPE_PASSWORD);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }

        return afterLoginSuccess(authentication, user.getNickName());
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        User user = new User();
        user.setUserId(userId);
        user.setLoginIp(IpUtils.getIpAddr());
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }

    public String wxLogin(WxLoginBody body) {
        Long appId = body.getAppId();

        // 查询APP信息
        AppVO app = appService.selectAppById(appId);
        ServiceUtil.assertion(app == null, "ID为%s的APP信息不存在，请联系管理员", appId);
        ServiceUtil.assertion(!AppType.WX.getType().equals(app.getType()), "ID为%s的APP不是微信小程序", appId);

        // 转换为微信配置信息
        WxConfig wxConfig = appConverter.toWxConfig(app);
        ServiceUtil.assertion(wxConfig == null, "微信配置信息不存在，请联系管理员");

        // 获取微信openId
        String openId = wxAuthService.getOpenId(body.getLoginCode(), wxConfig);
        ServiceUtil.assertion(openId == null, "获取微信openId失败");

        UserVO user = null;
        String phone = null;

        // 优先使用手机号登录（如果提供了手机号验证码）
        if (StringUtils.hasText(body.getMobileCode())) {
            phone = wxAuthService.getWxPhoneNumber(body.getMobileCode(), wxConfig, true);

            // 查询用户
            user = userService.selectUserByUserName(phone);

            // 如果通过手机号找到用户，尝试绑定微信openId
            if (user != null) {
                this.tryBindApp(user.getUserId(), openId, appId);
            }
        }
            
        // 如果通过手机号没有找到用户，则尝试通过openId查询
        if (user == null) {
            user = userService.selectByAppOpenId(appId, openId);
        }
        // 如果用户仍然不存在，则注册新用户
        if (user == null) {
            user = userService.registerUser(phone, openId, appId);
        }

        ServiceUtil.assertion(user == null, "用户不存在", 401);

        // 信任登录
        Authentication auth = this.trustLogin(user.getUserId());

        return afterLoginSuccess(auth, user.getNickName());
    }

    // 信任登录
    private Authentication trustLogin(Long userId) {
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userId, Constants.LOGIN_TYPE_TRUST);
            // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
            authenticationToken.setDetails(Constants.LOGIN_TYPE_TRUST);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();          //抛出账号或者密码错误的异常
            } else {
                throw new ServiceException(e.getMessage());         //抛出其他异常
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        return authentication;
    }

    // 登录成功后处理
    private String afterLoginSuccess(Authentication authentication, String nickName) {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(nickName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    // 尝试绑定APP
    private int tryBindApp(Long userId, String openId, Long appId) {
        if (userId == null || appId == null || StringUtils.isBlank(openId)) {
            return 0;
        }
        try {
            return userAppService.bind(userId, appId, openId);
        } catch (Exception e) {
            log.error("绑定APP失败", e);
            return 0;
        }
    }

    public String loginById(Long userId) {
        UserVO user = userService.selectUserById(userId);
        ServiceUtil.assertion(user == null, "ID为%s的用户不存在，请联系管理员", userId);
        Authentication authentication = this.trustLogin(userId);
        return this.afterLoginSuccess(authentication, user.getNickName());
    }
}
