package com.securitycontrol.auth.service;

import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.utils.ServletUtils;
import com.securitycontrol.common.core.utils.aes.DateTimeHelper;
import com.securitycontrol.common.core.utils.ip.IpUtils;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.system.api.RemoteLogService;
import com.securitycontrol.system.api.domain.SysLog;
import com.securitycontrol.system.api.domain.SysUser;
import com.securitycontrol.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 记录日志方法
 *
 * @author czc
 */
@Component
public class SysRecordLogService {
    @Autowired
    private RemoteLogService remoteLogService;

    /**
     * 记录登录信息
     *
     * @param username  用户名
     * @param model     操作模块
     * @param detail    详情
     * @param operaType 1.登录 2.登出
     * @return
     */
    public void recordLogininfor(String username, Long userId, String model, String detail, int operaType) {
        SysLog sysLog = new SysLog();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        sysLog.setLogId(id);
        sysLog.setOperTime(DateTimeHelper.getNowTime());
        sysLog.setOperaUserName(username);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (null != loginUser && null != loginUser.getSysUser()) {
            SysUser sysUser = loginUser.getSysUser();
            sysLog.setUserId(sysUser.getUserId());
        }
        if(userId != null){
            sysLog.setUserId(userId);
        }
        sysLog.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysLog.setModel(model);
        sysLog.setOperType(model);
        sysLog.setOperateDetail(model);
        sysLog.setMethod(operaType == 1 ? "com.securitycontrol.auth.controller.login()" : "com.securitycontrol.auth.controller.logout()");
        sysLog.setResult(detail == null ? 0 : 1);
        sysLog.setOperUri(operaType == 1 ? "/auth/login" : "/auth/logout");
        sysLog.setFailureReason(detail);
        sysLog.setLogType(0);
        remoteLogService.saveSysLog(sysLog, SecurityConstants.INNER);
    }
}
