package com.leromro.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.leromro.common.config.WeiXinConfig;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
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.leromro.common.constant.CacheConstants;
import com.leromro.common.constant.Constants;
import com.leromro.common.constant.UserConstants;
import com.leromro.common.core.domain.entity.SysUser;
import com.leromro.common.core.domain.model.LoginUser;
import com.leromro.common.core.redis.RedisCache;
import com.leromro.common.exception.ServiceException;
import com.leromro.common.exception.user.BlackListException;
import com.leromro.common.exception.user.CaptchaException;
import com.leromro.common.exception.user.CaptchaExpireException;
import com.leromro.common.exception.user.UserNotExistsException;
import com.leromro.common.exception.user.UserPasswordNotMatchException;
import com.leromro.common.utils.DateUtils;
import com.leromro.common.utils.MessageUtils;
import com.leromro.common.utils.StringUtils;
import com.leromro.common.utils.ip.IpUtils;
import com.leromro.framework.manager.AsyncManager;
import com.leromro.framework.manager.factory.AsyncFactory;
import com.leromro.framework.security.context.AuthenticationContextHolder;
import com.leromro.system.service.ISysConfigService;
import com.leromro.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Slf4j
@Component
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 WeiXinConfig weiXinConfig;

    /**
     * 登录验证
     *
     * @param code 临时登录凭证
     * @return 结果
     */
    public String login(String code)
    {

        //拼接请求参数，获取唯一用户标识openid
        Map<String, Object> result = new HashMap<>();
        String url = StrUtil.format("{}/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code",
                this.weiXinConfig.getUrl(),
                this.weiXinConfig.getAppId(),
                this.weiXinConfig.getSecret(),
                code);

        //请求微信服务端获取openid
        HttpResponse response = HttpRequest.get(url).timeout(20000)
                .execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        if (jsonObject.get("errcode") != null) {
            log.info("code:"+code);
            throw new ServiceException("传入的code错误，登录失败！");
        }

        String openId = jsonObject.getStr("openid");
        SysUser user = this.userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserOpenId, openId));
        if (null == user) {
            //该用户是新用户，需要新增数据到数据库
            user = new SysUser();
            user.setUserOpenId(openId);
            user.setNickName("微信用户");
            user.setUserName(IdUtil.getSnowflakeNextIdStr());
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            //注册新微信用户：平台默认是0(小程序)
            user.setUserPlatform(0);
            this.userService.save(user);
            result.put("isNew", true);
        } else {
            result.put("isNew", false);
        }
        String username = user.getUserName();
        String password = user.getPassword();
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, "123456");
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用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 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);
            // 该方法会去调用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();
        }
        //记录登录成功日志，AsyncFactory异步工厂，来创建任务
        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)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
