package thyyxxk.webserver.factory.electro;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.entity.examinations.inspections.request.ReportIndexInquiry;
import thyyxxk.webserver.factory.electro.model.ElectroIndex;

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

@Slf4j
public class ElectroService {
    private static final String URL = "http://172.16.32.167:9206/thyy/api/public/ecgReport?id={}&startTime={}&endTime={}";

    public List<ElectroIndex> queryOutpatientElectroIndex(ReportIndexInquiry request) {
        String url = StrUtil.format(URL, request.getSocialNo(), request.getReqStartTime(), request.getReqEndTime());
        List<ElectroIndex> electroIndexList = new ArrayList<>();
        JSONObject response = new RestTemplate().getForObject(url, JSONObject.class);
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        int code = response.getIntValue("code");
        if (code != 1) {
            throw new BizException(response.getString("message"));
        }
        JSONArray rows = response.getJSONArray("data");
        if (null != rows && !rows.isEmpty()) {
            for (int i = 0; i < rows.size(); i++) {
                JSONObject row = rows.getJSONObject(i);
                ElectroIndex electroIndex = JSONObject.toJavaObject(row, ElectroIndex.class);
                electroIndexList.add(electroIndex);
            }
        }
        return electroIndexList;
    }
}
