package com.neusoft.smart.pos.framework.aop;

import com.google.common.collect.Lists;
import com.neusoft.smart.pos.framework.constants.CommonErrorCode;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * @author zcf
 * @date 2017-08-13 10：43
 * @description hibernate validate校验aop拦截
 */
@Aspect
@Component
public class ValidateAspect {

    @Around("@annotation(org.springframework.web.bind.annotation.GetMapping)||"
    		+ "@annotation(org.springframework.web.bind.annotation.PostMapping)||"
    		+ "@annotation(org.springframework.web.bind.annotation.PutMapping)||"
    		+ "@annotation(org.springframework.web.bind.annotation.DeleteMapping)||"
    		+ "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object validateBindingResult(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] arguments = joinPoint.getArgs();
        if (arguments != null) {
            for (Object argument : arguments) {
                if(null == argument)
                    continue;
                if (argument instanceof BindingResult) {
                    BindingResult bindingResult = (BindingResult) argument;
                    if (bindingResult.hasErrors()) {
                        List<String> errorMessages = Lists.newArrayList();
                        for (ObjectError objectError : bindingResult.getAllErrors()) {
                            errorMessages.add(objectError.getDefaultMessage());
                        }
                        throw new BusinessCommonException(CommonErrorCode.PARAMETER_ERROR.getCode(), StringUtils.arrayToDelimitedString(errorMessages.toArray(), " & "));
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}
