package com.yuchen.saas.manage.user.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;

import java.util.Objects;

/**
 * @Author 蔡文强
 * @Date 2023/5/5 15:56
 * @Description 用户服务触发熔断配置类
 */
public class SaasUserFeignFallbackUtils {
    private static final Logger log = LoggerFactory.getLogger(SaasUserFeignFallbackUtils.class);

    public SaasUserFeignFallbackUtils() {
    }

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

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

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

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