package com.cmeeting.aspect;

import com.cmeeting.ad.entity.RobotSecurityUser;
import com.cmeeting.ad.util.SecurityUtil;
import com.cmeeting.annotation.OperLog;
import com.cmeeting.constant.RecordTemplateConstant;
import com.cmeeting.pojo.OperationLog;
import com.cmeeting.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


@Aspect
@Slf4j
@Component
public class OperLogAspect {

    @Autowired
    private OperationLogService operationLogService;

    @After(value = "@annotation(operLog)")
    public void after(JoinPoint point, OperLog operLog) {
        Date now = new Date();
        RobotSecurityUser user = SecurityUtil.getUser();

        new Thread(() -> {
            String location = operLog.location();
            String operation = operLog.operation();

            OperationLog operationLog = new OperationLog();
            operationLog.setLocation(location);
            operationLog.setOperation(operation);
            operationLog.setUserId(user.getId());
            if (user.getRole().equals(RecordTemplateConstant.TEMPLATE_TYPE_SYSTEM)) {
                operationLog.setUserName("管理员");
            } else {
                operationLog.setUserName(user.getUsername());
            }
            operationLog.setCreateTime(now);

            operationLogService.save(operationLog);
        }).start();

    }
}
