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.DeviceTreeClient;
import com.njcn.device.pq.pojo.vo.TerminalTree;
import com.njcn.device.biz.utils.DeviceEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * pqs
 *
 * @author cdf
 * @date 2022/1/13
 */
@Slf4j
@Component
public class DeviceTreeClientFallbackFactory implements FallbackFactory<DeviceTreeClient> {

    @Override
    public DeviceTreeClient create(Throwable cause) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if(cause.getCause() instanceof BusinessException){
            BusinessException businessException = (BusinessException) cause.getCause();
            exceptionEnum = DeviceEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new DeviceTreeClient() {
            @Override
            public HttpResult<TerminalTree> getTerminalTreeForFive() {
                log.error("{}异常，降级处理，异常为：{}","获取终端五层树失败",cause.toString());
                throw new BusinessException(finalExceptionEnum);
            }

            @Override
            public HttpResult<List<TerminalTree>> getTerminalTree() {
                log.error("{}异常，降级处理，异常为：{}","获取终端树",cause.toString());
                throw new BusinessException(finalExceptionEnum);
            }


        };
    }
}
