package com.hotent.base.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hotent.base.annotation.NewVersion;
import com.hotent.base.controller.BaseController;
import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.ServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestControllerAdvice(basePackages = "com.hotent")
public class ResponseAdvice implements ResponseBodyAdvice  {

    @Autowired
    private ServletRequest servletRequest;

    private static final Logger logger=LoggerFactory.getLogger(ResponseAdvice.class);

    // 将结果缓存到map中去
    private static final Map<String,String> map=new ConcurrentHashMap<>();
    // 缓存结果
    private static final String key="newVersion";

    @Override
    public boolean supports(MethodParameter methodParameter, Class clazz) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class clazz, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String originURI =(String) servletRequest.getAttribute("originURI");
        // 默认是/*****/v1/，直接放行
        if (BeanUtils.isEmpty(originURI) ) {
            return o;
        }
        servletRequest.removeAttribute("originURI");
        // 如果没有开启新版本（v2），直接走默认返回类型
        if (map.get(key)!=null && !map.get(key).equals("true")){
           return o;
       }else if (map.get(key)==null){  // 缓存结果到map
            // 默认情况下，每个Controller都继承了BaseController
            Class<?> controllerClass = methodParameter.getDeclaringClass();
            if (BaseController.class.isAssignableFrom(controllerClass)){
                if (BaseController.class.isAnnotationPresent(NewVersion.class)){
                    NewVersion version = BaseController.class.getAnnotation(NewVersion.class);
                    String value = version.open();
                    map.put(key,value);
                }
            }
        }
        /*
        // 获取方法所在的类
        Class<?> controllerClass = methodParameter.getDeclaringClass();
        // 获取方法的返回类型
        Class<?> returnClass = methodParameter.getParameterType();
        logger.info("controller所在的类，{}",controllerClass);
        logger.info("controller的返回类型，{}",returnClass);
        */
        // 如果默认返回的是CommonResult，那就直接返回
        if (o instanceof CommonResult){
            CommonResult result=(CommonResult)o;
            if (result.getMessage() == null ||result.getMessage().equals("")){
                // 如果无返回提示，那么默认返回操作成功提示
                result.setMessage(ResponseErrorEnums.SUCCESS_OPTION.getMessage());
            }
            return o;
        }else if(o instanceof String){ // 如果是String类型，需要包装一下
            ObjectMapper om = new ObjectMapper();
            try {
                return om.writeValueAsString(CommonResult.ok().message(String.valueOf(o)).value(String.valueOf(o)));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                logger.error("增强返回类型出现错误，错误原因：{}",e.getMessage());
            }
        }
        // 如果返回的值为null，那就返回成功的操作
        if (BeanUtils.isEmpty(o)){
            return CommonResult.ok().value(String.valueOf(""));
        }
        // 其他情况，默认返回
        return CommonResult.ok().value(o);
    }
}
