package com.njcn.web.config;

import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.EnumUtils;
import com.njcn.common.utils.PubUtils;
import com.njcn.web.utils.RequestUtil;
import feign.RequestInterceptor;
import feign.Util;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年08月24日 15:07
 */
@Configuration
@RequiredArgsConstructor
public class FeignConfig {


    /**
     * 自定义拦截器
     */
    @Bean
    public RequestInterceptor authTokenInterceptor() {
        return template -> {
            if(Objects.nonNull(RequestUtil.getRequest())){
                String jwtPayload = RequestUtil.getRequest().getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
                String realIp = RequestUtil.getRealIp();
                template.header(SecurityConstants.JWT_PAYLOAD_KEY, jwtPayload);
                template.header(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP, realIp);
            }
        };
    }

    /**
     * 自定义openfeign的解码器
     */
    @Bean
    public Decoder feignDecoder() {
        return (response, type) -> {

            String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
            //对结果进行转换
            HttpResult<Object> result = PubUtils.json2obj(bodyStr, type);
            //如果返回错误，且为内部错误，则直接抛出异常
            CommonResponseEnum commonResponseEnum;
            if(result.getCode().equals(CommonResponseEnum.DYNAMIC_RESPONSE_ENUM.getCode())){
                commonResponseEnum = CommonResponseEnum.DYNAMIC_RESPONSE_ENUM;
                commonResponseEnum.setMessage(result.getMessage());
            }else{
                commonResponseEnum = EnumUtils.getCommonResponseEnumByCode(result.getCode());
            }
            switch (commonResponseEnum) {
                case SUCCESS:
//                case NO_DATA:
//                case FAIL:
                    return result;
                default:
                    throw new BusinessException(result);
            }
        };
    }
}
