package com.iformall.log;


import com.alibaba.fastjson.JSON;
import com.iformall.domain.po.PosActionLog;
import com.iformall.pay.WxPayConstant;
import com.iformall.service.PosActionLogService;
import com.iformall.utils.IPUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class SystemLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    private PosActionLogService posActionLogService;

    @Pointcut("@annotation(com.iformall.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }

    @Pointcut("@annotation(com.iformall.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }

    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        PosActionLog posActionLog = new PosActionLog();
        long startTime = System.currentTimeMillis();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipaddress = IPUtil.getIpAddr(request);
        posActionLog.setUrl(request.getRequestURL().toString());
        posActionLog.setIp(ipaddress);
        posActionLog.setMethod(request.getMethod());
        posActionLog.setReqJson(JSON.toJSONString(joinPoint.getArgs()[0]));
        posActionLog.setStartTime(startTime);

        try {
            Object o = joinPoint.proceed();
            posActionLog.setResJson(JSON.toJSONString(o));
            long endTime = System.currentTimeMillis();
            posActionLog.setEndTime(endTime);
            posActionLog.setCostTime(Long.valueOf(endTime - startTime).intValue());
            try {
                posActionLogService.saveOrUpdate(posActionLog);
            } catch (Exception e) {
                logger.error("save pos log error: " + e.getMessage());
            }
            return o;
        } catch (Throwable throwable) {
            logger.error("异常: " + throwable.getMessage());
            return null;
        }

    }

}
