package com.bonus.auth.service;

import com.bonus.common.core.constant.*;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.enums.UserStatus;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.text.Convert;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.ip.IpUtils;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser;

import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author bonus
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        long startTime = System.currentTimeMillis();
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.saveLogs(username, startTime, "用户名/密码为空","用户名/密码必须填写",null,null);
            throw new ServiceException("用户名/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < ValidateUtils.MIN_LENGTH
                || password.length() > ValidateUtils.MAX_LENGTH) {
            recordLogService.saveLogs(username,startTime, "密码格式不正确","用户名/密码格式不正确",null,null);
            throw new ServiceException("用户名/密码格式不正确");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.saveLogs(username, startTime, "用户名格式不正确","用户名/密码格式不正确",null,null);
            throw new ServiceException("用户名/密码格式不正确");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.saveLogs(username, startTime, "访问IP已被列入系统黑名单","很遗憾，访问IP已被列入系统黑名单",null,null);
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.saveLogs(username,startTime, "登录用户不存在","用户名/密码错误",null,null);
            throw new ServiceException("用户名/密码错误");
        }
        if (R.FAIL == userResult.getCode()) {
            recordLogService.saveLogs(username, startTime, "系统错误",userResult.getMsg(),null,null);
            throw new ServiceException(userResult.getMsg());
        }
        
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.saveLogs(username, startTime, "账号已被删除","用户不存在",null,null);
            throw new ServiceException("用户不存在");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.saveLogs(username, startTime, "用户已停用","用户不存在",null,null);
            throw new ServiceException("用户不存在");
        }
        passwordService.validate(user, password,startTime);
        //登录成功 5分钟 会进行ip校验
        String nowIp=IpUtils.getIpAddr();
        Long times= 5L;
        String hisIp=redisService.getCacheObject("IP:"+user.getUserId().toString());
        if(StringUtils.isNotEmpty(nowIp) && !nowIp.equals(hisIp)){
            recordLogService.saveErrorLogs(username, startTime,user.getUserId().toString());
        }
        redisService.setCacheObject("IP:"+user.getUserId().toString(),nowIp,times, TimeUnit.MINUTES);
        recordLogService.saveLogs(username, startTime, "登陆成功","登陆成功",user.getUserId().toString(),"登陆成功");
        return userInfo;
    }

    public void logout(String loginName,String userId) {
        recordLogService.saveLogout(loginName,"退出成功","退出成功",userId,"退出成功");
   }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }
}
