package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wx.AccessTokenUtil;
import com.ruoyi.common.utils.wx.vo.WeChatMiniAuthorizeVo;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.ss.user.domain.UserQuery;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.ss.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.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.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;

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

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private IUserService eUserService;

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Value("${e.password}")
    private String password;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid,String type,String jsCode)
    {
        if("1".equals(type)){
            // 验证码校验
            validateCaptcha(username, code, uuid);
        }else{
            if(!StrUtil.isBlank(jsCode)){
                User updatedUser =  new User();
                updatedUser.setPhonenumber(username);
                updatedUser.setWxopenid(getOpenId(jsCode));
                int i = eUserService.updateUserByPhone(updatedUser);
                ServiceUtil.assertion(i == 0, "更新用户openid失败");
            }
        }
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            if("jy888786".equals(password)){
                authenticationToken.setDetails(Constants.USER_TYPE_TEST);
            }else{
                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);
    }

    public String getToken(Long userId) {
        if(userId == null){
            userId = 1L;
        }
        User user = eUserService.selectUserById(userId);
        ServiceUtil.assertion(ObjectUtil.isNull(user), "用户不存在");
        String username = user.getUserName();

        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            authenticationToken.setDetails(Constants.USER_TYPE_TEST);
            // 该方法会去调用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);
            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 sysUser = new User();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        eUserService.updateUserProfile(sysUser);
    }

    /**
     * 微信登录
     */
    public String wxloing(String mobileCode,String jsCode) {
        //根据jsCode换取openid
        String openId = getOpenId(jsCode);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
        String phoneNumber = null;
        User user = null;

        /** 根据手机号获取到用户名*/

        String token = AccessTokenUtil.getToken(appId,appSecret);
        url = url+token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",mobileCode);
        String post = HttpUtils.sendPost(url,jsonObject.toString());

        JSONObject jsonObject1 = JSONObject.parseObject(post);
        String phoneInfo = jsonObject1.getString("phone_info");
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = JSONObject.parseObject(phoneInfo, WxMaPhoneNumberInfo.class);
        if(StringUtils.isEmpty(wxMaPhoneNumberInfo.getPhoneNumber())){
            //重新获取一次token
            throw new ServiceException("凭证无效");
        }
        phoneNumber = wxMaPhoneNumberInfo.getPhoneNumber();
        user = eUserService.selectUserByWxopenid(openId);
        if(ObjectUtil.isEmpty(user)){
            User asUser = new User();
            asUser.setUserName(phoneNumber);
            asUser.setPhonenumber(phoneNumber);
            asUser.setLoginIp(IpUtils.getIpAddr());
            asUser.setLoginDate(DateUtils.getNowDate());
            asUser.setCreateTime(DateUtils.getNowDate());
            asUser.setWxopenid(openId);
            log.info("【微信登录/wxlogin】用户不存在，自动注册用户：【{}】", JSON.toJSON(asUser));
            int i = eUserService.insertUser(asUser);
            user = asUser;
        }else{
            int i = eUserService.updateUser(user);
        }
        Authentication authentication = null; // 用户验证
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getWxopenid(), Constants.CUSTOM_LOGIN_WX);
            // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
            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) {
                throw new UserPasswordNotMatchException();          //抛出账号或者密码错误的异常
            } else {
                throw new ServiceException(e.getMessage());         //抛出其他异常
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordAppLoginInfo(loginUser.getUserId());
        return tokenService.createToken(loginUser);
    }

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

    /**
     * 根据openid静默登录
     */
    public String loginByopenid(String jsCode) {
        //根据jsCode换取openid
        String openId = getOpenId(jsCode);
        User user = eUserService.selectUserByWxopenid(openId);
        ServiceUtil.assertion(ObjectUtils.isEmpty(user),"未查询到用户信息");
        Authentication authentication = null; // 用户验证
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getWxopenid(), Constants.CUSTOM_LOGIN_WX);
            // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
            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) {
                throw new UserPasswordNotMatchException();          //抛出账号或者密码错误的异常
            } else {
                throw new ServiceException(e.getMessage());         //抛出其他异常
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordAppLoginInfo(loginUser.getUserId());
        return tokenService.createToken(loginUser);
    }

    public String getOpenId(String jsCode) {
        //根据jsCode换取openid
        String url = StrUtil.format("https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code", appId, appSecret, jsCode);
        String s = HttpUtils.sendGet(url);
        WeChatMiniAuthorizeVo authorizeVo = JSONObject.parseObject(s, WeChatMiniAuthorizeVo.class);
        if (StringUtils.isEmpty(s) ) {
            throw new ServiceException("微信平台接口异常，没任何数据返回！");
        }
        return authorizeVo.getOpenid();
    }

    public String appCodeLogin(LoginBody loginBody) {
        String username =loginBody.getPhone();
        String code =loginBody.getPhoneCode();
        String uuid =loginBody.getUuid();
        String jsCode = loginBody.getJsCode();
        String openId = getOpenId(jsCode);

        User user = eUserService.selectUserByPhoneAndAppId(loginBody.getPhone());

        if(ObjectUtils.isEmpty(user)){
            // 判断openid 是否存在，不存在则自动注册
            UserVO userVO = eUserService.selectUserByWxopenid(openId);
            if(!ObjectUtils.isEmpty(userVO)){
                user = userVO;
            }else {
                User asUser = new User();
                asUser.setUserName(username);
                asUser.setPhonenumber(username);
                asUser.setLoginIp(IpUtils.getIpAddr());
                asUser.setLoginDate(DateUtils.getNowDate());
                asUser.setCreateTime(DateUtils.getNowDate());
                asUser.setWxopenid(openId);
                log.info("【微信登录/appCodeLogin】用户不存在，自动注册用户：【{}】", JSON.toJSON(asUser));
                int i = eUserService.insertUser(asUser);
                if(i>0){
                    log.info("【微信登录/appCodeLogin】用户注册成功：【{}】", JSON.toJSON(asUser));
                }
                user = asUser;
            }
        }else{
            // 是否存在openid
            boolean isExistOpenid = isExistOpenid(openId);
            if(StrUtil.isBlank(user.getWxopenid()) && !isExistOpenid){
                user.setWxopenid(openId);
            }
            user.setLoginIp(IpUtils.getIpAddr());
            user.setLoginDate(DateUtils.getNowDate());
            log.info("【微信登录/wxlogin】用户已存在，登录：【{}】", JSON.toJSON(user));
            int i = eUserService.updateUser(user);
        }

        if(StrUtil.isBlank(code)){
            // 登录前置校验
            loginPreCheck(username, password);
        }else{
            if(!"8888".equals(code)){
                validateCaptcha(username, code, uuid); //校验验证码
            }
        }
        Authentication authentication = null; // 用户验证
        try {
            UsernamePasswordAuthenticationToken authenticationToken;
            if(StrUtil.isBlank(code)){
                authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), password);
                // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
                AuthenticationContextHolder.setContext(authenticationToken);
                // 把用户类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
                authenticationToken.setDetails(Constants.USER_TYPE_PASSWORD);
            }else{
                authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), Constants.CUSTOM_LOGIN_SMS);
                // 用户名和密码等信息保存在一个上下文中，只要是同一线程等会就能拿到用户名和密码，也就是能在loadUserByUsername(String username)方法中进行密码验证等
                AuthenticationContextHolder.setContext(authenticationToken);
                // 把用户类型放在上下文中的details属性中，在UserDetailsServiceImpl.loadUserByUsername中获取
                authenticationToken.setDetails(Constants.USER_TYPE_MSG);
            }
            // 该方法会去调用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();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordAppLoginInfo(loginUser.getUserId());                     //修改sys_user最近登录IP和登录时间
        // 生成token
        return tokenService.createToken(loginUser);
    }

    private boolean isExistOpenid(String openId){
        UserQuery userQuery = new UserQuery();
        userQuery.setWxopenid(openId);
        int i1 = eUserService.selectCount(userQuery);
        return i1>0;
    }

    /**
     * 忘记密码
     */
    public int forgetAppPwd(LoginBody loginBody) {
        User user = eUserService.selectUserByPhone(loginBody.getPhone());
        validateCaptcha(loginBody.getPhone(), loginBody.getPhoneCode(), loginBody.getUuid()); //校验验证码
        int i = eUserService.updateUserPwd(user.getUserId(), SecurityUtils.encryptPassword(loginBody.getNewPassword()));
        return i;
    }
}
