package com.quantgroup.asset.distribution.config.annotation;

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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.quantgroup.asset.distribution.exception.QGException;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.alarm.IAlarmService;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常捕获处理AOP
 * @author liwenbin
 *
 */
@Aspect
@Component
@Slf4j
public class HandleExceptionAspect {
	
	@Autowired
	private IAlarmService alarmService;
	
	@Pointcut("@annotation(com.quantgroup.asset.distribution.config.annotation.HandleException)")
	private void fundModulePointCut() {
	}
	
	@Around("fundModulePointCut()")
	public GlobalResponse handleException(ProceedingJoinPoint point) {
		try {
			return (GlobalResponse)point.proceed();
		} catch (QGException qe) {
			log.error("资方模块接口出现错误, class : {}, method : {}, 错误信息捕获 : {}", point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), qe.qgExceptionType.code + "->" + qe.detail);
			alarmService.dingtalkAlarm("Warn", "资方模块接口出现错误", "class : " + point.getTarget().getClass().getSimpleName() + " , method : " + 
					point.getSignature().getName() + " , 错误信息 : " + qe.qgExceptionType.code + "->" + qe.detail);
			return GlobalResponse.create(qe);
		} catch (Exception e) {
			log.error("资方模块接口出现异常, class : {}, method : {}", point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), e);
			alarmService.dingtalkAlarm("Error", "资方模块接口出现异常", "class : " + point.getTarget().getClass().getSimpleName() + " , method : " + 
					point.getSignature().getName() + " , 出现未知异常, 请查看!");
			return GlobalResponse.error(QGExceptionType.COMMON_SERVER_ERROR);
		} catch (Throwable e) {
			log.error("资方模块接口出现异常, class : {}, method : {}", point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), e);
			alarmService.dingtalkAlarm("Error", "资方模块接口出现异常", "class : " + point.getTarget().getClass().getSimpleName() + " , method : " + 
					point.getSignature().getName() + " , 出现未知异常, 请查看!");
			return GlobalResponse.error(QGExceptionType.COMMON_SERVER_ERROR);
		}
	}
}
