package gaf3.core.cloud.feign

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONValidator
import feign.FeignException
import feign.Response
import feign.codec.ErrorDecoder
import gaf3.core.exception.BusinessError
import gaf3.core.util.StringUtil
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType
import java.nio.charset.Charset

class GafErrorDecoder : ErrorDecoder{
    private val log = LoggerFactory.getLogger(GafErrorDecoder::class.java)

    override fun decode(methodKey: String, response: Response): Exception {
        val data = runCatching { IOUtils.toString(response.body().asInputStream(), Charset.defaultCharset()) }.getOrNull() ?: ""
        val isJson = response.headers()["content-type"]
                ?.stream()?.map { s -> MediaType.parseMediaType(s) }
                ?.anyMatch { c -> c.isCompatibleWith(MediaType.APPLICATION_JSON)}

        log.warn("HTTP Status {} - {}", response.status(), StringUtil.subString(data, 100))
        var exception = FeignException.errorStatus(methodKey, response) as Exception
        if(response.status() == 400 && isJson == true && JSONValidator.from(data).validate()) {
            // 处理Http 400错误
            val res = JSON.parseObject(data)
            exception = if (!res.containsKey("errcode")) {
                BusinessError(BusinessError.ERR_BADPARAM, "请求参数错误")
            } else {
                BusinessError(res.getInteger("errcode"), res.getString("errmsg"), res.getString("details"))
            }
        }
        return exception
    }
}