package org.wfc.auth.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wfc.common.core.constant.CacheConstants;
import org.wfc.common.core.constant.Constants;
import org.wfc.common.core.constant.SecurityConstants;
import org.wfc.common.core.constant.UserConstants;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.core.domain.R;
import org.wfc.common.core.enums.UserStatus;
import org.wfc.common.core.exception.ServiceException;
import org.wfc.common.core.text.Convert;
import org.wfc.common.core.utils.DateUtils;
import org.wfc.common.core.utils.MessageUtils;
import org.wfc.common.core.utils.StringUtils;
import org.wfc.common.core.utils.ip.IpUtils;
import org.wfc.common.core.web.form.RegisterBody;
import org.wfc.common.redis.service.RedisService;
import org.wfc.common.security.utils.SecurityUtils;
import org.wfc.system.api.RemoteUserService;
import org.wfc.system.api.domain.SysUser;

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

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser<SysUser> login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "user.password.not.blank");
            throw new ServiceException("user.password.not.blank");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.password.not.in.specified.range");
            throw new ServiceException("auth.password.not.in.specified.range");
        }
        // 用户名不在指定范围内 错误
//        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
//                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.username.not.in.specified.range");
//            throw new ServiceException("auth.username.not.in.specified.range");
//        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.ip.in.blacklist");
            throw new ServiceException("auth.ip.in.blacklist");
        }
        // 查询用户信息
        R<LoginUser<SysUser>> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.username.not.exists");
            String msg = MessageUtils.message("auth.username.not.exists", username);
            throw new ServiceException(msg);
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser<SysUser> userInfo = userResult.getData();
        SysUser user = userInfo.getUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.user.deleted");
            String msg = MessageUtils.message("auth.user.deleted", username);
            throw new ServiceException(msg);
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "auth.user.blocked.contact.admin");
            String msg = MessageUtils.message("auth.user.blocked", username);
            throw new ServiceException(msg);
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "auth.login.success");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        // 更新用户登录IP
        sysUser.setLoginIp(IpUtils.getIpAddr());
        // 更新用户登录时间
        sysUser.setLoginDate(DateUtils.getNowDate());
        remoteUserService.recordUserLogin(sysUser, SecurityConstants.INNER);
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "auth.logout.success");
    }

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("user.password.not.blank");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("auth.username.must.in.specified.range");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("auth.password.must.in.specified.range");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        // 额外携带
        sysUser.setAge(registerBody.getAge());
        sysUser.setAddress(registerBody.getAddress());
        sysUser.setEmail(registerBody.getEmail());
        sysUser.setFullName(registerBody.getFullName());
        sysUser.setSex(registerBody.getSex());
        sysUser.setPhonenumber(registerBody.getPhonenumber());

        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "auth.register.success");
    }
}
