package com.goldenwater.slgc.controller.proxy;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
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;
import jakarta.annotation.PostConstruct;

@Tag(name = "29. 涉河项目管理")
@RestController
@RequestMapping("/slgc/shgc")
public class ShgcController extends BaseController {

    private final RestTemplate restTemplate;
    private final ApiProperties apiProperties;

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

    @Autowired
    private DataSource dataSource;
    private JdbcTemplate jdbc;

    @PostConstruct
    public void init() {
        this.jdbc = new JdbcTemplate(dataSource);
    }

    @Operation(summary = "查询涉河项目列表")
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(defaultValue = "") String type,
                           @RequestParam(defaultValue = "") String name) {
        try {
            // 使用参数化查询防止 SQL 注入
            StringBuilder sql = new StringBuilder("select * from tba_gc_info where 1=1");
            java.util.List<Object> params = new java.util.ArrayList<>();
            if (!type.isEmpty()) {
                sql.append(" and type = ?");
                params.add(type);
            }
            if (!name.isEmpty()) {
                sql.append(" and name like ?");
                params.add("%" + name + "%");
            }
            List<Map<String, Object>> result = jdbc.queryForList(sql.toString(), params.toArray());
            return success(result);
        } catch (Exception e) {
            return success(Collections.emptyList());
        }
    }

    @Operation(summary = "查询直管工程信息（引排水量）")
    @GetMapping("/real/info")
    public AjaxResult realInfo() {
        try {
            String url = apiProperties.getYjzh() + "/SELECT_Engineering1";
            ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class);
            return success(parseJsonFromSoap(resp.getBody()));
        } catch (Exception e) {
            return success(Collections.emptyList());
        }
    }

    @SuppressWarnings("unchecked")
    private Object parseJsonFromSoap(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 nodes = (org.w3c.dom.NodeList) xpath.evaluate("//Table/string", doc, javax.xml.xpath.XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                String json = nodes.item(0).getTextContent().trim();
                com.alibaba.fastjson2.JSONArray arr = com.alibaba.fastjson2.JSONArray.parseArray(json);
                return arr != null ? arr : Collections.emptyList();
            }
        } catch (Exception ignored) {}
        return Collections.emptyList();
    }
}
