package com.easyproject.core.web.service;

import javax.annotation.Resource;

import com.easyproject.common.core.domain.AjaxClientResult;
import com.easyproject.common.core.domain.entity.ClientMember;
import com.easyproject.common.core.domain.model.LoginMember;
import com.easyproject.clientbus.service.member.IClientMemberService;
import com.easyproject.clientbus.service.config.IClientConfigService;
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.easyproject.common.constant.CacheConstants;
import com.easyproject.common.constant.Constants;
import com.easyproject.common.core.redis.RedisCache;
import com.easyproject.common.exception.ServiceException;
import com.easyproject.common.exception.user.CaptchaException;
import com.easyproject.common.exception.user.CaptchaExpireException;
import com.easyproject.common.exception.user.UserPasswordNotMatchException;
import com.easyproject.common.utils.DateUtils;
import com.easyproject.common.utils.MessageUtils;
import com.easyproject.common.utils.ServletUtils;
import com.easyproject.common.utils.StringUtils;
import com.easyproject.common.utils.ip.IpUtils;
import com.easyproject.core.manager.AsyncManager;
import com.easyproject.core.manager.factory.AsyncFactory;
import com.easyproject.core.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Value;

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

/**
 * 登录校验方法
 *
 * @author java001
 */
@Slf4j
@Component
public class MemberLoginService {
    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    @Autowired
    private MemberTokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IClientMemberService clientMemberService;

    @Autowired
    private IClientConfigService configService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public AjaxClientResult login(String username, String password, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用MemberDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("member.login.verify")));
                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("member.login.success")));
        LoginMember loginMember = (LoginMember) authentication.getPrincipal();
        recordLoginInfo(loginMember.getId());

        String memberNum = loginMember.getMember().getMemberNum();

        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginMember.getMember().getId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }

        // 生成本系统APP登录状态的token
        String token = tokenService.createToken(loginMember);

        //组装返回值
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.TOKEN, token);
        map.put("userId", memberNum);

        return AjaxClientResult.success(map);
    }

    /**
     * 校验验证码-登录
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CLIENT_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 memberId 用户ID
     */
    public void recordLoginInfo(Long memberId) {
        ClientMember clientMember = new ClientMember();
        clientMember.setId(memberId);
        clientMember.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        clientMember.setLoginDate(DateUtils.getNowDate());
        clientMemberService.updateUserProfile(clientMember);
    }
}
