package com.ximai.mes.remote.config;

import com.ximai.common.exception.ServiceException;
import com.ximai.mes.remote.dto.ErpResponseResult;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;

@Component
public class CustomResponseEntityDecoder extends SpringDecoder {
    public CustomResponseEntityDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Object obj = super.decode(response, type);
        if(obj instanceof ErpResponseResult){
            ErpResponseResult result = (ErpResponseResult)obj;
            if(!result.isSuccess()){
                throw new ServiceException("api error："+result.getErrorMessage());
            }
        }
        return obj;
    }
}
