package com.supServer.framework.security.service;

import com.supServer.common.constant.Constants;
import com.supServer.common.exception.ServiceException;
import com.supServer.common.exception.user.CaptchaException;
import com.supServer.common.exception.user.CaptchaExpireException;
import com.supServer.common.exception.user.UserPasswordNotMatchException;
import com.supServer.common.utils.MessageUtils;
import com.supServer.common.utils.StringUtils;
import com.supServer.framework.manager.AsyncManager;
import com.supServer.framework.redis.RedisCache;
import com.supServer.framework.security.mode.LoginUser;
import com.supServer.project.entity.UserInfo;
import com.supServer.project.service.SmsService;
import com.supServer.project.service.UserInfoService;
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;


/**
 * @description：
 * @Author: ly
 * @Date: 2022/3/29 11:21
 */
@Component
public class UserLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SmsService smsService;

    //免密常量
    public static final String CUSTOM_LOGIN_SMS = "CUSTOM_LOGIN_SMS";

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        //校验图形验证码
        validateCaptcha(code, uuid);
        //校验用户类型是否匹配
//        UserInfo userInfo = userInfoService.selectUserByUserName(username);
//        if(!ObjectUtils.isEmpty(userInfo)){
//            if (!type.equals(userInfo.getType())){
//                throw new ServiceException("登录错误，请检查用户类型");
//            }
//        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUserId();
        int i = userInfoService.updateLoginTime(userId);
        // 生成token
        return tokenService.createToken(loginUser);

    }

    /**
     * 校验验证码
     * @param code
     * @param uuid
     */
    public void validateCaptcha(String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    public String smsLogin(String phonenumber, String smsCode) {
        //校验用户类型是否匹配
        UserInfo userInfo = userInfoService.selectUserByPhone(phonenumber);
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userInfo.getAccount(), smsCode));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUserId();
        int i = userInfoService.updateLoginTime(userId);
        // 生成token
        return tokenService.createToken(loginUser);
    }



}
