package com.qmth.file.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qmth.file.exception.FileServerException;
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 java.lang.reflect.Method;

/**
 * 包装Ajax请求的返回值,并处理所有的错误信息
 *
 * @author tianjun
 */
@Aspect
@Component
public class SystemControllerAspect {
    private static final Logger logger = LoggerFactory.getLogger(SystemControllerAspect.class);

    @Around("execution(public * com.qmth.file.controller.*.*(..))")
    public Object aroundController(ProceedingJoinPoint joinPoint) throws Exception {
        // 请求目标对象方法
        SystemResult result = new SystemResult();
        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 (FileServerException 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(FileServerException.SYSTEM_EXCEPTION.getCode(), "系统错误");
            logger.debug(
                    "---------------------------------------------request end--------------------------------------------");
        }
        ObjectMapper mapper = new ObjectMapper();
        String returnResult = mapper.writeValueAsString(result);
        logger.debug("响应信息:" + returnResult);
        logger.debug("---------------------------------------request end------------------------------------------");
        return result;
    }

}
