package com.yuchen.saas.integration.feign.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.nest.springwrap.core.tool.api.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Integration服务触发熔断配置类
 */
public class SaasIntegrationFeignFallbackUtils {
    private static final Logger log = LoggerFactory.getLogger(SaasIntegrationFeignFallbackUtils.class);

    public SaasIntegrationFeignFallbackUtils() {
    }

    public static R printLogAndReturn(String logMsg, String returnMsg) {

        log.error("Integration服务触发熔断：{}", logMsg);
        returnMsg = StringUtils.isEmpty(returnMsg) ? "Integration服务接口因异常触发熔断，请联系管理员！" : returnMsg;
        return R.fail(returnMsg);

    }

    public static R printLogAndReturn(Throwable throwable) {

        if (throwable instanceof FeignException) {

            FeignException feignException = (FeignException) throwable;
            log.error("Integration服务触发熔断：{}", feignException.contentUTF8(), throwable);
            JSONObject jsonObject = JSON.parseObject(feignException.contentUTF8());
            return R.fail(jsonObject.getString("message"));

        } else if (throwable instanceof RuntimeException) {
            log.error("Integration服务触发熔断：{}", throwable.getMessage(), throwable);
            return R.fail(throwable.getMessage());
        }

        return R.fail(throwable.getMessage());
    }

    public static R printLogAndReturn(String returnMsg) {

        log.error("Integration服务触发熔断：{}", returnMsg);
        return R.fail(returnMsg);

    }

}
