package com.miaxis.framework.web.service;

import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.domain.WxUserInfo;
import com.miaxis.common.core.domain.model.LoginUser;
import com.miaxis.common.core.redis.RedisCache;
import com.miaxis.common.enums.StudentLoginTypeEnum;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.exception.user.CaptchaException;
import com.miaxis.common.exception.user.CaptchaExpireException;
import com.miaxis.common.exception.user.UserPasswordNotMatchException;
import com.miaxis.common.utils.MessageUtils;
import com.miaxis.common.utils.RedisPrefixUtils;
import com.miaxis.common.utils.ServletUtils;
import com.miaxis.common.utils.StringUtils;
import com.miaxis.framework.manager.AsyncManager;
import com.miaxis.framework.manager.factory.AsyncFactory;
import com.miaxis.framework.security.token.OpenIdAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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 javax.annotation.Resource;

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

    @Resource
    private AuthenticationManager authenticationManager;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate redisTemplate;//redis模板引擎

    /**
     * 登录验证 (含验证码)
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + 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();
        }
        // 用户验证
        return authenticate(username,new UsernamePasswordAuthenticationToken(username, password));
    }
    /**
     * 登录验证 (不含验证码)
     *
     * @return 结果
     */
    public String login(String username, String password) {

        return authenticate(username,new UsernamePasswordAuthenticationToken(username, password));
    }




    /**
     * 学员登录验证
     *
     * @param principal 主体  可以是用户名,电话号码，openid等
     * @param credential 密码或者验证码
     * @param loginType 登录类型 1 学员用户名密码登录 2 学员手机验证码登录
     * @return 结果
     */
    public String login(String principal, String credential, String loginType) {

        ServletUtils.getRequest().setAttribute("loginType",loginType);

        // 用户验证
        if (StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode().equals(loginType)||StudentLoginTypeEnum.IOS_CODE_LOGIN.getCode().equals(loginType)
        ||StudentLoginTypeEnum.AUTHORIZATION_CODE_DY_LOGIN.getCode().equals(loginType)||StudentLoginTypeEnum.AUTHORIZATION_CODE_TT_LOGIN.getCode().equals(loginType)){
            return authenticate(principal,new OpenIdAuthenticationToken(principal));
        }
        else{
            throw new CustomException("loginType参数错误");
        }


    }

    private void validateCode(String principal, String credential) {
        if (StringUtils.isEmpty(credential)){
            throw new CustomException("验证码不能为空");
        }
        String cacheCode = (String) redisTemplate.opsForValue().get(RedisPrefixUtils.getSmsKeyPrefix("login", principal));
        if (StringUtils.isEmpty(cacheCode)){
            throw new CustomException("验证码已过期,请重新发送");
        }else if (!credential.equals(cacheCode)){
            throw new CustomException("验证码不正确");
        }
    }

    private String authenticate (String username , Authentication authenticationToken){
         Authentication authentication = null;
        try
        {

            // 该方法会去调用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
            {
                e.printStackTrace();
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);

    }


}
