package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.auth.ali.AliAuthService;
import com.ruoyi.common.core.domain.entity.SmUser;
import com.ruoyi.common.core.domain.model.AliLoginBody;
import com.ruoyi.common.core.domain.model.WxLoginBody;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.auth.wx.AccessTokenUtil;
import com.ruoyi.common.auth.wx.WxAuthService;
import com.ruoyi.ss.account.domain.Account;
import com.ruoyi.ss.store.service.StoreService;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.user.service.ISmUserService;
import com.ruoyi.ss.account.service.AccountService;
import com.ruoyi.ss.account.domain.enums.AccountType;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.domain.enums.config.ConfigKey;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
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.stereotype.Component;
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.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
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.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISmUserService smUserService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private StoreService smDeviceGroupService;

    @Autowired
    private WxAuthService wxAuthService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private AliAuthService aliAuthService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.Username中获取
            authenticationToken.setDetails(Constants.USER_TYPE_PC);
            // 该方法会去调用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();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @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);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            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)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 前台账号密码登录
     * @param username
     * @param password
     * @return
     */
    public String appLogin(String username, String password) {
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
            authenticationToken.setDetails(Constants.USER_TYPE_APP);
            // 该方法会去调用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();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 微信登录
     */
    public String wxLogin(WxLoginBody body) {

        // 通过openId查询用户
        String openId = wxAuthService.getOpenId(body.getLoginCode());
        ServiceUtil.assertion(openId == null, "获取微信openId失败");
        SmUserVO user = smUserService.selectSmUserByWxOpenId(openId);

        // 若用户不存在，则使用openId进行注册
        if (user == null || Objects.equals(user.getDelFlag(), UserStatus.DELETED.getCode())) {
            // 获取手机号
            boolean loginWithPhone = sysConfigService.getBoolean(ConfigKey.ARRIVAL_DELAY);
            String mobile = null;
            if (loginWithPhone && StringUtils.hasText(body.getMobileCode())) {
                mobile = wxAuthService.getWxPhoneNumber(body.getMobileCode());
            }
            // 用户注册
            user = smUserService.registerWx(openId, mobile);
        }
        ServiceUtil.assertion(user == null, "用户不存在");

        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserId(), Constants.CUSTOM_LOGIN_WX);
            // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
            authenticationToken.setDetails(Constants.USER_TYPE_WX);
            // 该方法会去调用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();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }


    public String userLogin(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录
        return this.appLogin(username, password);
    }

    public String aliLogin(AliLoginBody body) {
        // 通过支付宝openId查询用户
        String openId = aliAuthService.getOpenId(body.getLoginCode());
        ServiceUtil.assertion(openId == null, "获取支付宝openId失败");

        SmUserVO user = smUserService.selectSmUserByAliOpenId(openId);

        // 若用户不存在，则使用openId进行注册
        if (user == null || Objects.equals(user.getDelFlag(), UserStatus.DELETED.getCode())) {
            boolean loginWithPhone = sysConfigService.getBoolean(ConfigKey.ARRIVAL_DELAY);
            String mobile = null;
            if (loginWithPhone && StringUtils.hasText(body.getMobileCiphertext())) {
                mobile = aliAuthService.getPhoneNumber(body.getMobileCiphertext());
            }
            // 用户注册
            user = smUserService.registerAli(openId, mobile);
        }
        ServiceUtil.assertion(user == null, "用户不存在");

        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserId(), Constants.CUSTOM_LOGIN_ALI);
            // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
            AuthenticationContextHolder.setContext(authenticationToken);
            // 把用户登录类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
            authenticationToken.setDetails(Constants.USER_TYPE_ALI);
            // 该方法会去调用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();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);

    }
}
