package com.xunmei.auth.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xunmei.common.core.constant.CacheConstants;
import com.xunmei.common.core.constant.Constants;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.constant.UserConstants;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.enums.UserStatus;
import com.xunmei.common.core.exception.ServiceException;
import com.xunmei.common.core.text.Convert;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.utils.ip.IpUtils;
import com.xunmei.common.redis.utils.RedisUtils;
import com.xunmei.common.security.utils.AsymmetricEncryptionUtil;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.system.api.RemoteUserService;
import com.xunmei.system.api.domain.SysUser;
import com.xunmei.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.stereotype.Component;

import java.util.Date;

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

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;



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

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在",platformType);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

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

        LoginUser userInfo = userResult.getData();
        userInfo.setPlatformType(platformType);
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDeleted()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除",platformType);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(Integer.parseInt(user.getIsLock())))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员",platformType);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password,platformType);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功",platformType);
        return userInfo;
    }

    public void logout(String loginName,String platformType)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功",platformType);
    }

    public void checkLogin(String authCode) {
        if (SecurityUtils.isApp()) {
            return;
        }
        String decrypt = AsymmetricEncryptionUtil.decrypt(authCode);
        if (ObjectUtil.isEmpty(decrypt) || null == decrypt) {
            throw new RuntimeException("登录信息失效");
        }
        //如果redis中存在此key，说明已经登录过了
       /* BoundSetOperations<String, Object> operations = redisService.getBoundSetOperations("loginAuth");
        if (Boolean.TRUE.equals(operations.isMember(decrypt))) {
            throw new RuntimeException("登录信息失效");
        }*/
        //如果不满足此规则，说明是伪造的
        String[] split = decrypt.split(":");
        if (split.length != 2) {
            throw new RuntimeException("登录信息失效");
        }
        //如果不满足以下规则，说明是伪造的
        String timeStamp = split[1];
        if (!NumberUtil.isNumber(timeStamp)) {
            throw new RuntimeException("登录信息失效");
        }
        //三分钟内有效
        if (System.currentTimeMillis() - Long.parseLong(timeStamp) > 300000) {
            throw new RuntimeException("登录信息失效");
        }
        /*operations.add(decrypt);
        operations.expireAt(DateUtil.endOfDay(new Date()));
*/

    }
}
