package com.jiayue.ssi.factory;

import com.jiayue.ssi.constant.Constants;
import com.jiayue.ssi.entity.SysLogininfor;
import com.jiayue.ssi.service.SysLogininforService;
import com.jiayue.ssi.util.*;
import eu.bitwalker.useragentutils.UserAgent;

import java.util.Date;


/**
* 登录日志工厂
*
* @author xsl
* @since 2023/03/29
*/
public class LoginFactory {
    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @return 任务task
     */
    public static void recordLogininfor(final String username, final String status, final String message) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IPUtils.getIpAddr();
        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(username));
        s.append(getBlock(status));
        s.append(getBlock(message));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(message);
        logininfor.setLoginTime(new Date());
        logininfor.setCreateBy(username);
        // 日志状态
        if (RyStringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
        {
            logininfor.setStatus(Constants.SUCCESS);
        }
        else if (Constants.LOGIN_FAIL.equals(status))
        {
            logininfor.setStatus(Constants.FAIL);
        }
        // 插入数据
        SpringUtils.getBean(SysLogininforService.class).insertLogininfor(logininfor);
    }

    public static String getBlock(Object msg)
    {
        if (msg == null)
        {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }
}
