package com.sdut.labex.config;

import com.sdut.labex.common.LogThread;
import com.sdut.labex.entity.LogEntity;
import com.sdut.labex.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutorService;

import static java.lang.System.currentTimeMillis;

/**
 * File: AppConfig
 * Created: 2023/6/21
 * Author: springforest
 * Description:
 */
@Configuration
@Aspect
@EnableAspectJAutoProxy
public class AppConfig {
    @Resource
    private LogService logService;
    @Resource
    private DataSource dataSource;

    @Resource
    private ExecutorService es;

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("execution(* com.sdut.labex.controller.*.*(..))")
    public void syslog() {

    }

    @Around("syslog()")
    public Object first(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getName();

        long statTime = currentTimeMillis();
        Object proceed = joinPoint.proceed(joinPoint.getArgs());
        long endTime = currentTimeMillis();

        String date = sdf.format(statTime);
        long cost = endTime - statTime;

        System.out.println("方法" + name + "执行时间为" + cost + "毫秒");

        LogEntity log = new LogEntity();
        log.setContent(name);
        log.setDate(date);
        log.setCost(cost);
        //另开一个线程运行日志入库的操作，因为该操作耗时较长
        LogThread logThread = new LogThread(log, dataSource);
        es.submit(logThread);
        //
        return proceed;
    }

}
