package com.app.admin.framework.log.aspect;

import com.app.admin.framework.log.model.SysOperationLog;
import com.app.admin.framework.log.service.SysOperationLogService;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.log.result.LogResult;
import com.app.framework.core.log.task.LogResultTask;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.utils.request.RequestUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class OperationLogTask extends LogResultTask {

    @Autowired
    SysOperationLogService sysOperationLogService;

    @Async("taskExecutor")
    public void handler(HttpServletRequest request, JoinPoint jp, LogOps annotation, String operationDate) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        if (loginUser == null) {
            loginUser = (LoginUser) request.getAttribute("apiLoginUser");
        }
        SysOperationLog logOper = this.toLogOper(loginUser);
        if (logOper == null) return;

        logOper.setOperationType(annotation.type());
        logOper.setOperationDate(operationDate);
        if (StringUtils.isNotBlank(annotation.description())) {//有置顶日志内容
            logOper.setContents(annotation.description());
        } else {//利用日志拦截器处理日志内容
            LogResult logResult = this.logResult(jp);
            if (logResult == null) {
                return;
            }
            logOper.setOperationDesc(logResult.getOperType());
            logOper.setContents(logResult.processLogColmnList());

            if (logResult.getOperatorId() != null) {
                logOper.setOperatorId(logResult.getOperatorId());
            }
            if (StringUtils.isNotBlank(logResult.getOperatorName())) {
                logOper.setOperatorName(logResult.getOperatorName());
            }
        }
        logOper.setIpAddress(RequestUtil.getIpAddr(request));
        sysOperationLogService.saveOperationLog(logOper);
    }

    /**
     * 组装SysOperationLog
     *
     * @param loginUser
     * @return
     */
    private SysOperationLog toLogOper(LoginUser loginUser) {
        if (loginUser != null) {
            SysOperationLog log = new SysOperationLog();
            log.setOrganizationId(loginUser.getOrganizationId());
            log.setOperatorId(loginUser.getId());
            log.setOperatorName(loginUser.getRealName());
            log.setOperatorAccount(loginUser.getUsername());
            return log;
        }
        return null;
    }

}
