package com.njcn.device.pq.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.pq.api.SubstationFeignClient;
import com.njcn.device.pq.pojo.dto.SubstationDTO;
import com.njcn.device.biz.utils.DeviceEnumUtil;
import com.njcn.device.pq.pojo.po.LineDetail;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年10月13日 19:55
 */
@Slf4j
@Component
public class SubstationFeignClientFallbackFactory implements FallbackFactory<SubstationFeignClient> {
    @Override
    public SubstationFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if (throwable.getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = DeviceEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new SubstationFeignClient(){
            @Override
            public HttpResult<List<SubstationDTO>> getSubstationById(List<String> id) {
                log.error("{}异常，降级处理，异常为：{}", "根据变电站ID获取变电站信息", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }

            @Override
            public HttpResult<List<LineDetail>> getMonitorByStationId(String stationId, Integer powerFlag) {
                log.error("{}异常，降级处理，异常为：{}", "根据变电站ID获取监测到信息", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }
        };
    }
}
