package com.ema.admin.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.ema.admin.modules.system.converter.SysOperLogConverter;
import com.ema.admin.modules.system.service.SysAuthService;
import com.ema.admin.modules.system.service.SysOperLogService;
import com.ema.admin.modules.system.vo.SysUserVo;
import com.ema.common.aspect.logger.LoggerHandler;
import com.ema.common.aspect.logger.LoggerVo;
import com.ema.common.consts.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 操作日志处理器
 */
@Slf4j
@Component
public class OperLoggerHandler implements LoggerHandler {


    @Resource(name = CommonConst.ASYNC_POOL)
    private ThreadPoolTaskExecutor threadPoolExecutor;
    @Resource
    private SysAuthService sysAuthService;
    @Resource
    private SysOperLogService sysOperLogService;
    @Resource
    private SysOperLogConverter sysOperLogConverter;

    @Override
    public void handler(LoggerVo loggerVo) {
        if (StpUtil.isLogin()) {
            SysUserVo userVo = sysAuthService.getCurrentUser();
            threadPoolExecutor.execute(() -> {
                sysOperLogService.save(sysOperLogConverter.toSysOperLog(userVo.getId(), userVo.getName(), loggerVo));
            });
        } else {
            threadPoolExecutor.execute(() -> {
                sysOperLogService.save(sysOperLogConverter.toSysOperLog(null, null, loggerVo));
            });
        }
    }
}
