package cn.freemud.aop;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.enums.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 判断返回message是否转换为英文
 *
 * @author wanghanghang
 * @date 2021/04/01
 */
@Aspect
@Component
public class IsConvertEnAspect implements Ordered {
    @Pointcut("@annotation(cn.freemud.annotations.IsConvertEN)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object convertMessage(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = currentRequest();
        String language = request.getHeader("lang");
        BaseResponse baseResponse = (BaseResponse) joinPoint.proceed();
        //表示返回英文提示
        if ("en-US".equals(language)) {
            /**此处注释**/
            String enMessage = ResponseResult.getResponseResult(baseResponse.getCode()).getEnMessage();
            if (!StringUtils.isEmpty(enMessage)) {
                baseResponse.setMessage(enMessage);
            }
        }
        return baseResponse;
    }

    private HttpServletRequest currentRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Optional.ofNullable(servletRequestAttributes).map(ServletRequestAttributes::getRequest).orElse(null);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
