package org.springblade.modules.app.utils;

import com.alibaba.fastjson.JSONObject;
import com.wn.common.datamodel.ResultDTO;
import com.wn.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;

/**
 * Rest接口返回处理类
 *
 * @author liuqian
 */
@Slf4j
public class ResponseHandelUtil {

    public static final int SUCCESS = 200;
    public static final String CODE_SUCCESS = "0";

    public static <T> T handel(ResponseEntity<ResultDTO<T>> response) {
        if (null == response) {
            throw new BusinessException("999900", "http请求返回为空");
        }
        if (response.getStatusCodeValue() != SUCCESS) {
            throw new BusinessException("999900", "http请求返回为空");
        }
        ResultDTO<T> result = response.getBody();
        if (null == result) {
            throw new BusinessException("999900", "http请求返回为空");
        }
        log.info("response-result:" + JSONObject.toJSONString(result));
        String code = result.getCode();
        if (StringUtils.isNotBlank(code) && code.equals(CODE_SUCCESS)) {
            return result.getData();
        }
        throw new BusinessException(code, result.getMessage());
    }

    public static <T> T handel(ResultDTO<T> result) {
        if (null == result) {
            throw new BusinessException("999900", "http请求的数据返回为空");
        }
        log.info("【response-result】:" + JSONObject.toJSONString(result));
        String code = result.getCode();
        if (StringUtils.isNotBlank(code) && code.equals(CODE_SUCCESS)) {
            return result.getData();
        }
        throw new BusinessException(code, result.getMessage());
    }

    public static <T> T handelResp(ResponseEntity<ResultDTO<T>> response) {
        if (null == response) {
            throw new BusinessException("999900", "http的请求返回为空");
        }
        log.info("【response】:" + JSONObject.toJSONString(response));
        if (response.getStatusCodeValue() != SUCCESS) {
            throw new BusinessException("999900", "http的请求返回为空");
        }
        ResultDTO<T> result = response.getBody();
        if (null == result) {
            throw new BusinessException("999900", "http的请求返回为空");
        }
        String code = result.getCode();
        if (StringUtils.isNotBlank(code) && code.equals(CODE_SUCCESS)) {
            return result.getData();
        }
        throw new BusinessException(code, result.getMessage());
    }
}
