package com.goldenwater.slgc.controller.proxy;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ProxyHelper {

    private static final RestTemplate rt = new RestTemplate();

    public static Object fetchJson(String url) {
        try {
            ResponseEntity<String> resp = rt.getForEntity(url, String.class);
            String body = resp.getBody();
            if (body != null && !body.isEmpty()) {
                body = body.trim();
                if (body.startsWith("[")) {
                    return com.alibaba.fastjson2.JSONArray.parseArray(body);
                } else if (body.startsWith("{")) {
                    return com.alibaba.fastjson2.JSONObject.parseObject(body);
                }
            }
        } catch (Exception ignored) {}
        return Collections.emptyList();
    }

    public static Object fetchSoapXmlToJson(String url) {
        try {
            ResponseEntity<String> resp = rt.getForEntity(url, String.class);
            String xml = resp.getBody();
            if (xml == null || xml.isEmpty()) return Collections.emptyList();

            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            XPath xpath = XPathFactory.newInstance().newXPath();

            NodeList strings = (NodeList) xpath.evaluate("//Table/string", doc, XPathConstants.NODESET);
            if (strings.getLength() > 0) {
                String json = strings.item(0).getTextContent().trim();
                if (json.startsWith("[")) return com.alibaba.fastjson2.JSONArray.parseArray(json);
                if (json.startsWith("{")) return com.alibaba.fastjson2.JSONObject.parseObject(json);
            }

            NodeList rows = (NodeList) xpath.evaluate("//NewDataSet/Table | //DocumentElement/Table", doc, XPathConstants.NODESET);
            if (rows.getLength() > 0) {
                List<Map<String, String>> result = new ArrayList<>();
                for (int i = 0; i < rows.getLength(); i++) {
                    Element el = (Element) rows.item(i);
                    Map<String, String> map = new LinkedHashMap<>();
                    NodeList children = el.getChildNodes();
                    for (int j = 0; j < children.getLength(); j++) {
                        if (children.item(j) instanceof Element) {
                            Element child = (Element) children.item(j);
                            map.put(child.getTagName(), child.getTextContent());
                        }
                    }
                    result.add(map);
                }
                return result;
            }
        } catch (Exception ignored) {}
        return Collections.emptyList();
    }
}
