package com.hys.app.framework.http;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.util.List;

/**
 * 请求第三方接口统一响应数据
 *
 * @author 张崧
 * @since v7.2.2
 */
@Data
public class ApiResponse {

    private HttpResponse httpResponse;

    /**
     * http响应体
     */
    private String body;

    /**
     * 接口是否成功
     */
    private boolean success;

    /**
     * 业务响应码
     */
    private String code;

    /**
     * 业务响应信息
     */
    private String msg;

    /**
     * 业务响应数据
     */
    private String data;

    public ApiResponse(HttpResponse httpResponse) {
        this.httpResponse = httpResponse;
        this.body = httpResponse.body();
    }

    public ApiResponse checkSuccess() {
        if (!success) {
            throw new ThirdApiException(code, msg);
        }
        return this;
    }

    public JSONObject get() {
        return JSON.parseObject(data);
    }

    public List<JSONObject> getList() {
        return JSON.parseArray(data, JSONObject.class);
    }

    public <T> T get(Class<T> clazz) {
        return JSON.parseObject(data, clazz);
    }

    public <T> List<T> getList(Class<T> clazz) {
        return JSON.parseArray(data, clazz);
    }
}
