package com.goldenwater.slgc.controller.proxy;

import java.util.Collections;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import com.goldenwater.slgc.config.ApiProperties;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "22. 工程监管")
@RestController
@RequestMapping("/slgc/zggc")
public class ZggcController extends BaseController {

    private final RestTemplate restTemplate;
    private final ApiProperties apiProperties;

    public ZggcController(RestTemplate restTemplate, ApiProperties apiProperties) {
        this.restTemplate = restTemplate;
        this.apiProperties = apiProperties;
    }

    @Operation(summary = "22.01 查询水情数据")
    @GetMapping("/station")
    public AjaxResult station(@RequestParam(defaultValue = "0") int statCode, String date) {
        String d = date != null ? date : new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        String[] codes = {"69642", "69485", "69462"};
        String stcd = statCode >= 0 && statCode < 3 ? codes[statCode] : "69642";
        try {
            String xml = restTemplate.getForObject(apiProperties.getZggc() + "/SYSW?strTime=" + d + "&stcd=" + stcd, String.class);
            return success(parseDiffgram(xml));
        } catch (Exception e) {
            return success(Collections.emptyList());
        }
    }

    @Operation(summary = "22.02 查询流量数据")
    @GetMapping("/flow")
    public AjaxResult flow(String date) {
        String d = date != null ? date : new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        try {
            String xml = restTemplate.getForObject(apiProperties.getZggc() + "/GetTGTQ?stime=" + d, String.class);
            return success(parseDiffgram(xml));
        } catch (Exception e) {
            return success(Collections.emptyList());
        }
    }

    @Operation(summary = "22.03 查询工程监管列表")
    @GetMapping("/list")
    public AjaxResult list(String date) {
        String d = date != null ? date : new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        try {
            String xml = restTemplate.getForObject(apiProperties.getZggc() + "/SYSW?strTime=" + d, String.class);
            return success(parseDiffgram(xml));
        } catch (Exception e) {
            return success(Collections.emptyList());
        }
    }

    @Operation(summary = "22.04 查询工程门户（三大站实时数据）")
    @GetMapping("/portal")
    public AjaxResult portal() {
        String d = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        String[] codes = {"69642", "69485", "69462"};
        String[] names = {"太浦闸", "望亭枢纽", "常熟水利枢纽"};
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        for (int i = 0; i < codes.length; i++) {
            try {
                String xml = restTemplate.getForObject(apiProperties.getZggc() + "/SYSW?strTime=" + d + "&stcd=" + codes[i], String.class);
                Object data = parseDiffgram(xml);
                java.util.Map<String, Object> map = new java.util.LinkedHashMap<>();
                map.put("stcd", codes[i]);
                map.put("name", names[i]);
                map.put("stationName", names[i]);
                map.put("data", data);
                result.add(map);
            } catch (Exception e) {
                // skip individual station failure
            }
        }
        return success(result);
    }

    private Object parseDiffgram(String xml) {
        if (xml == null || xml.isEmpty()) return Collections.emptyList();
        try {
            javax.xml.parsers.DocumentBuilder db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
            org.w3c.dom.Document doc = db.parse(new java.io.ByteArrayInputStream(xml.getBytes("UTF-8")));
            javax.xml.xpath.XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
            org.w3c.dom.NodeList rows = (org.w3c.dom.NodeList) xpath.evaluate("//NewDataSet/Table", doc, javax.xml.xpath.XPathConstants.NODESET);
            java.util.List<java.util.Map<String, String>> result = new java.util.ArrayList<>();
            for (int i = 0; i < rows.getLength(); i++) {
                org.w3c.dom.Element el = (org.w3c.dom.Element) rows.item(i);
                java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
                org.w3c.dom.NodeList children = el.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    if (children.item(j) instanceof org.w3c.dom.Element) {
                        org.w3c.dom.Element child = (org.w3c.dom.Element) children.item(j);
                        map.put(child.getTagName(), child.getTextContent());
                    }
                }
                result.add(map);
            }
            return result;
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
}
