package com.zcxk.core.common.util;

import com.zcxk.core.common.enums.RespCodeEnum;
import com.zcxk.core.common.exception.BusinessException;
import com.zcxk.core.common.pojo.AjaxMessage;

import java.util.Optional;
/**
 * @author Andy
 * @description: request
 * @date 2021/7/16
 * @version V1.0
 **/
public class ReqUtil {

    /**
     * 获取服务成功数据，服务状态非成功[0] 直接抛出异常
     *
     * @param response 服务调用返回结果
     * @return T
     * @author Richard
     **/
    public static <T> T getSuccessData(AjaxMessage<T> response) {
        if (!Optional.ofNullable(response).isPresent()) {
            throw BusinessException.builder(RespCodeEnum.ERROR_500);
        }
        if (RespCodeEnum.OK.getStatus() ==  response.getStatus()) {
            return response.getData();
        } else {
            throw BusinessException.builder(response.getStatus(), response.getMessage());
        }
    }

    /**
     * 获取返回成功数据状态[0]，非[0]存在返回null情况。
     * @param response 返回对象
     * @return T
     * @author Richard
     **/
    public static <T> T getData(AjaxMessage<T> response) {
        if (Optional.ofNullable(response).isPresent() &&
            RespCodeEnum.OK.getStatus() == response.getStatus()) {
            return response.getData();
        }
        return null;
    }
}
