package com.pj.current.global;
import java.util.Map;

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.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.pj.project4sp.apilog.SpApilogUtil;
import com.pj.utils.sg.AjaxJson;

/**
 * API全局日志, Controller 层切面 
 *
 * @author kong
 */
@Aspect
@Component
public class ApilogAspect {
    
	/**
	 * 定义AOP签名 --> 项目代码(所有class名称以 Controller 字符结尾的)
	 */
	@Pointcut("execution(* com.pj..*Controller.*(..))")
    public void webLogProject(){}

    /**
     * 环绕日志 
     * @param pjp
     * @return 
     * @throws Throwable
     */
	@Around("webLogProject()")
    public Object surround(ProceedingJoinPoint pjp) throws Throwable {
        try {
        	// 1、执行 
            Object obj =  pjp.proceed();
            
            // 2、解析返回结果 
            // 如果是 AjaxJson 
            if(obj instanceof AjaxJson){
            	AjaxJson aj = (AjaxJson) obj;
            	SpApilogUtil.endRequest(aj.getCode(), aj.getMsg(), aj);
            } 
            // 如果是 Map  
            else if (obj instanceof Map) {	
                @SuppressWarnings("unchecked")
            	AjaxJson aj = new AjaxJson().setMap((Map<String, ?>)obj);
            	SpApilogUtil.endRequest(aj.getCode(), aj.getMsg(), aj);
            } 
            // 如果是 String  
            else if (obj instanceof String) {	
            	SpApilogUtil.endRequest(200, "ok", obj);
            } 
            // 如果是 ModelAndView  
            else if (obj instanceof ModelAndView) {	
            	ModelAndView mv = (ModelAndView) obj;
            	SpApilogUtil.endRequest(200, "View：" + mv.getViewName(), "View 视图模板：" + mv.getViewName());
            } 
            // 如果都不是 
            else {	 
            	SpApilogUtil.endRequest(200, "ok", obj);
            }
            return obj;
        } catch (Throwable e) {
        	throw e;
        }
    }
    
}