package com.njcn.event.api.fallback;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.pms.pojo.param.MonitorTerminalParam;
import com.njcn.event.api.TransientFeignClient;
import com.njcn.event.utils.EventlEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 暂态事件熔断降级
 * @author guofeihu
 * @date 2024-08-22
 */
@Slf4j
@Component
public class TransientFeignClientFallbackFactory implements FallbackFactory<TransientFeignClient> {

    @Override
    public TransientFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if (throwable.getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = EventlEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new TransientFeignClient() {
            @Override
            public HttpResult<byte[]> getTransientAnalyseWaveToByteArray(@RequestBody MonitorTerminalParam param) {
                log.error("{}异常，降级处理，异常为：{}", "暂态事件波形分析：", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }
        };
    }
}
