package com.fdkankan.scene.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.callback.OnError;
import com.dtflys.forest.callback.OnSuccess;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/4/25
 **/
@Slf4j
public class FdkkMiniReqErrorCallback implements OnError {

    @Override
    public void onError(ForestRuntimeException e, ForestRequest forestRequest,
        ForestResponse forestResponse) {
        JSONObject jsonObject = JSON.parseObject(forestResponse.getContent());
        Integer status = jsonObject.getInteger("status");
        if(status != null && status == 500){
            log.error("v3接口报错,status:{},error:{}", status, jsonObject.getString("error"));
            throw new BusinessException(ServerCode.SYSTEM_ERROR);
        }
        Result result = JSON.parseObject(forestResponse.getContent(), Result.class);
        if(result.getCode() != ServerCode.SUCCESS.code()){
            throw new BusinessException(result.getCode(), result.getMsg());
        }
        log.error("跨服务请求失败！", e);
        throw new BusinessException(ServerCode.FEIGN_REQUEST_FAILD);
    }
}
