package com.njcn.process.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.process.api.FlowableDefineFeignClient;
import com.njcn.process.utils.ProcessEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 *
 * @author cdf
 * @date 2023/4/13
 */
@Slf4j
@Component
public class FlowableDefineFallbackFactory implements FallbackFactory<FlowableDefineFeignClient> {

    @Override
    public FlowableDefineFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if (throwable.getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = ProcessEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new FlowableDefineFeignClient() {

            @Override
            public HttpResult<String> start(String procDefId,
                                            String thsIndex,
                                            Map<String, Object> variables) {
                log.error("{}异常，降级处理，异常为：{}", "流程开始", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }
        };
    }
}
