package com.njcn.bpm.api.fallback;

import com.njcn.bpm.api.BpmProcessFeignClient;
import com.njcn.bpm.pojo.dto.BpmProcessInstanceCreateReqDTO;
import com.njcn.bpm.pojo.param.instance.BpmProcessInstanceCancelParam;
import com.njcn.bpm.utils.BpmEnumUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import feign.hystrix.FallbackFactory;

/**
 * @author denghuajun
 * @version 1.0.0
 * @date 2022/3/16
 */
@Slf4j
@Component
public class BpmProcessFeignClientFallbackFactory implements FallbackFactory<BpmProcessFeignClient> {
    @Override
    public BpmProcessFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if (throwable.getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = BpmEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new BpmProcessFeignClient() {
            @Override
            public HttpResult<String> createProcessInstance(String userId, BpmProcessInstanceCreateReqDTO reqDTO) {
                log.error("{}异常，降级处理，异常为：{}", "创建流程实例", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }

            @Override
            public HttpResult<Boolean> cancelProcessInstanceByStartUser(BpmProcessInstanceCancelParam cancelReqVO) {
                log.error("{}异常，降级处理，异常为：{}", "取消流程实例", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }

        };
    }
}
