package com.docus.server.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.docus.infrastructure.web.exception.ApiException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Objects;

//feign处理统一输出和异常
public class FeignResponseDecoder extends ResponseEntityDecoder {
    public FeignResponseDecoder(Decoder decoder) {
        super(decoder);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        String body;
        //response. body默认是InputStreamBody , 加了Feign 1og之后转为ByteArrayBody
        if (response.body().length() == null && response.body().asInputStream().available() == 0) {
            byte[] bodyData = Util.toByteArray(response.body().asInputStream());
            body = new String(bodyData);
        } else {
            body = response.body().toString();
        }
        if (!StringUtils.isEmpty(body)) {
            JSONObject responseobject = JSON.parseObject(body);
            if (responseobject.containsKey("code")) {
                Integer code = responseobject.getInteger("code");
                if (!Objects.equals(0, code)) {
                    String message = responseobject.getString("msg");
                    throw new ApiException(code, message);
                }
                String result = responseobject.getString("data");
                if (result == null || "null".equalsIgnoreCase(result)) {
                    return null;
                }
                response = response.toBuilder().body(result, Charset.forName("UTF-8")).build();
            }
        }
        return super.decode(response, type);
    }
}
