package com.tmerclub.cloud.systemtest.util;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;

import java.util.List;

/**
 * @author lanhai
 */
public class CheckUtil {




    public static void check(HttpResponse response) {
        String body = getBody(response);
        ServerResponseEntity serverResponseEntity = Json.parseObject(body, ServerResponseEntity.class);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
    }

    public static <T>  T checkAndGetObject(HttpResponse response, Class<T> clazz) {
        String body = getBody(response);
        TypeReference<ServerResponseEntity<T>> typeReference = new TypeReference<ServerResponseEntity<T>>(clazz) {};
        ServerResponseEntity<T> serverResponseEntity = JSON.parseObject(body, typeReference);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
        return serverResponseEntity.getData();
    }

    public static <T> List<T> checkAndGetArray(HttpResponse response, Class<T[]> clazz) {
        String body = getBody(response);
        ServerResponseEntity<T> serverResponseEntity = Json.parseObject(body, ServerResponseEntity.class);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
        return Json.parseArray(Json.toJsonString(serverResponseEntity.getData()), clazz);
    }

    public static <T>  String  checkAndGetObjects(HttpResponse response) {
        String body = getBody(response);
        JSONObject jsonObject = JSON.parseObject(body);
        JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
        if(data.containsKey("records")){
            return data.get("records").toString();
        }else {
            return data.get("list").toString();
        }
    }

    private static String getBody(HttpResponse response){
        if (!response.isOk()) {
            throw new RuntimeException("请求异常");
        }
        System.out.println(response.body());
        return response.body();
    }
}
