package thyyxxk.webserver.factory.examreport;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.factory.examreport.model.ExamDetailResponse;
import thyyxxk.webserver.factory.examreport.model.ExamIndexRequest;
import thyyxxk.webserver.factory.examreport.model.ExamIndexResponse;

import java.util.ArrayList;
import java.util.List;

public class ExamReportService {
    private static final String URL = "http://172.16.32.178/apis/third/report/query";

    public List<ExamIndexResponse> queryExamIndex(ExamIndexRequest request) {
        JSONObject response = new RestTemplate()
                .postForObject(URL + "/self", request, JSONObject.class);
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        Boolean code = response.getBoolean("code");
        if (null == code || !code) {
            throw new BizException(response.getString("message"));
        }
        JSONObject data = response.getJSONObject("data");
        JSONArray items = data.getJSONArray("items");
        List<ExamIndexResponse> examIndexList = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            ExamIndexResponse examIndexResponse = JSONObject.toJavaObject(item, ExamIndexResponse.class);
            examIndexList.add(examIndexResponse);
        }
        return examIndexList;
    }

    public ExamDetailResponse queryExamDetail(String reportId) {
        JSONObject params = new JSONObject();
        params.put("reportId", reportId);
        params.put("responseMode", "Json");
        JSONObject response = new RestTemplate().postForObject(
                URL + "/detail", params, JSONObject.class);
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        Boolean code = response.getBoolean("code");
        if (null == code || !code) {
            throw new BizException(response.getString("message"));
        }
        JSONObject data = response.getJSONObject("data");
        return JSONObject.toJavaObject(data, ExamDetailResponse.class);
    }
}

