package com.dhcc.finance.aop;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.model.CurrencyMeta;
import com.dhcc.common.model.response.RestfulResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @功能描述：日志及响应状态处理
 * @author chenrui
 * @date 2018年5月23日 上午10:24:03
 * @修改日志：
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class RestfulResponseAspect {

    /**
     * 切面
     */
    private static final String POINT_CUT = "execution(* com.dhcc.finance.service.controller..*(..))";

    @Pointcut(POINT_CUT)
    private void pointcut() {}
	
	/**
	 * 
	 * @Title: resetResponseMetaStatusCode
	 * @Description: 当出现'服务端异常, 请稍后再试'的错误时，视为非业务逻辑性异常，修改其状态码让上游服务捕获
	 * @param object
	 * @throws Throwable void
	 * @author chenrui
	 * @date 2018年12月10日 下午4:19:11
	 * @modifyLog：
	 */
    @AfterReturning(returning = "object", pointcut = "pointcut()")
    public void resetResponseMetaStatusCode(Object object) throws Throwable {
    	if( object instanceof RestfulResponse) {
	        RestfulResponse<Object,CurrencyMeta> restfulResponse =(RestfulResponse<Object,CurrencyMeta>) object;
	        if (restfulResponse.getCode() != null && restfulResponse.getCode() == SysConstants.CODE.FAIL && restfulResponse.getMeta().getStatusCode() == SysStatusCode.SERVER_UNKNOWN_ERROR.statusCode() ) {
            	log.info("\r\n{}",restfulResponse.getMsg());
                ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                res.getResponse().setStatus(HttpStatus.BAD_REQUEST.value());
            }
       }
    }
        
}
