package com.qmth.jkserver.core.aspect;

import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qmth.jkserver.core.ApiResult;
import com.qmth.jkserver.core.exception.ApiException;

/**
 * 接口切面
 * 
 * @author tianjun
 *
 */
@Aspect
@Component
public class ApiAspect {

	private Logger logger = LoggerFactory.getLogger(ApiAspect.class);

	@Around("execution(public * com.qmth.jkserver.controller.api.*Controller.*(..))")
	public Object aroundController(ProceedingJoinPoint joinPoint) throws Exception {
		ApiResult result = new ApiResult();
		// 请求目标对象方法
		try {
			MethodSignature msig = (MethodSignature) joinPoint.getSignature();
			Object target = joinPoint.getTarget();
			Class controllerClazz = target.getClass();
			Method currentMethod = controllerClazz.getMethod(msig.getName(), msig.getParameterTypes());
			RequestMapping reqa = currentMethod.getAnnotation(RequestMapping.class);
			String[] requestUrl = reqa.value();
			logger.debug("--------------------------------------request start---------------------------------------------------");
			logger.debug("request mapping : " + StringUtils.join(requestUrl, ","));
			logger.debug(joinPoint.getSignature() + " start!");
			result.returnData(joinPoint.proceed());
		} catch (ApiException e) {
			e.printStackTrace();
			logger.error(
					joinPoint.getTarget().getClass().getSimpleName() + joinPoint.getSignature().getName() + " error,",
					e);
			result.returnError(e.getCode(), e.getMessage());
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(
					joinPoint.getTarget().getClass().getSimpleName() + joinPoint.getSignature().getName() + " error,",
					e);
			result.returnError(ApiException.SYSTEM_EXCEPTION.getCode(),
					ApiException.SYSTEM_EXCEPTION.getMessage() + ":" + e);
		}
		ObjectMapper mapper = new ObjectMapper();
		String returnResult = mapper.writeValueAsString(result);
		logger.debug("响应信息:" + returnResult);
		logger.debug("------------------------------------request end---------------------------------------------");
		return result;
	}

}
