package com.yuchen.saas.flow.api.utils;

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;

/**
 * @author zhouhanwei
 * @create 2024/3/4 10:36
 */
public class FlowFeignFallbackUtils {
    private static final Logger log = LoggerFactory.getLogger(FlowFeignFallbackUtils.class);

    public FlowFeignFallbackUtils() {
    }

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

    public static R printLogAndReturn(Throwable throwable) {
        if (throwable instanceof FeignException) {
            FeignException feignException = (FeignException) throwable;
            log.error("flow服务触发熔断：{}", feignException.contentUTF8(), throwable);
            JSONObject jsonObject = JSON.parseObject(feignException.contentUTF8());
            return R.fail(jsonObject.getString("message"));
        } else if (throwable instanceof RuntimeException) {
            log.error("flow服务触发熔断：{}", throwable.getMessage(), throwable);
            return R.fail(throwable.getMessage());
        }
        return R.fail(throwable.getMessage());
    }

    public static R printLogAndReturn(String returnMsg) {
        log.error("flow服务触发熔断：{}", returnMsg);
        return R.fail(returnMsg);
    }
}
