package com.ruoyi.web.controller.oa;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

/**
 * 招投标代理接口控制器（方案2优化版）
 * 核心优化：自动资源关闭、参数校验、异常处理、响应流优化、连接复用
 */
@RestController
public class CmcBidController {

    // 连接超时时间（毫秒）
    private static final int CONNECT_TIMEOUT = 5000;
    // 读取超时时间（毫秒）
    private static final int READ_TIMEOUT = 10000;

    @GetMapping("/oa/bid/list")
    public void proxyUrl(String url, HttpServletResponse response) {
        // 1. 参数校验（方案2核心：防非法URL、空参数）
        if (url == null || url.trim().isEmpty()) {
            setErrorResponse(response, "请求参数异常：URL不能为空");
            return;
        }
        // 基础URL合法性校验（可根据实际业务补充白名单）
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            setErrorResponse(response, "请求参数异常：URL必须以http/https开头");
            return;
        }

        // 2. 响应头基础配置（方案2：强化编码和缓存控制）
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 禁止缓存，避免前端获取旧数据
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        HttpURLConnection conn = null;
        // 3. 资源自动关闭（方案2核心：try-with-resources 语法）
        try (
            // 声明需要自动关闭的资源
            InputStream inputStream = getTargetUrlInputStream(url);
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                    inputStream, 
                    StandardCharsets.UTF_8 // 强制UTF-8，避免编码乱码
                )
            )
        ) {
            // 4. 响应流优化（方案2：批量写入，减少IO次数）
            StringBuilder responseContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseContent.append(line).append("\n");
            }
            // 一次性写入响应流，提升性能
            response.getWriter().write(responseContent.toString());
            response.getWriter().flush();

        } catch (IllegalArgumentException e) {
            setErrorResponse(response, "URL格式非法：" + e.getMessage());
        } catch (IOException e) {
            setErrorResponse(response, "网络请求异常：" + e.getMessage());
        } catch (Exception e) {
            setErrorResponse(response, "服务内部异常：" + e.getMessage());
        } finally {
            // 5. 连接关闭（方案2：确保连接释放，避免连接泄漏）
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 获取目标URL的输入流（封装连接逻辑，方案2：解耦核心逻辑）
     */
    private InputStream getTargetUrlInputStream(String url) throws IOException {
        URL targetUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
        
        // 3. 连接配置优化（方案2：连接复用、请求头强化）
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        
        // 启用HTTP连接复用（方案2核心：减少TCP握手开销）
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Keep-Alive", "timeout=10, max=100");
        
        // 模拟浏览器请求头（强化版，降低拦截概率）
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        
        // Cookie配置（建议从配置文件/缓存获取，方案2：避免硬编码）
        conn.setRequestProperty("Cookie", "bidguid=cad034bd-ad01-4dce-a4ca-1a1252f0dbf1; Hm_lvt_9954aa2d605277c3e24cb76809e2f856=1775527126,1775629118,1775700867; HMACCOUNT=68D47FA6AE336EBB; Hm_lpvt_9954aa2d605277c3e24cb76809e2f856=1775703005");

        // 4. GZIP解压（方案2：兼容更多编码场景）
        InputStream inputStream = conn.getInputStream();
        String contentEncoding = conn.getContentEncoding();
        if (contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.trim())) {
            inputStream = new GZIPInputStream(inputStream);
        }
        return inputStream;
    }

    /**
     * 统一异常响应处理（方案2核心：标准化错误返回）
     */
    private void setErrorResponse(HttpServletResponse response, String message) {
        try {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("<html><body><h3>请求失败</h3><p>" + message + "</p></body></html>");
            response.getWriter().flush();
        } catch (IOException e) {
            // 记录日志（建议接入项目日志框架，如logback/log4j2）
            System.err.println("异常响应写入失败：" + e.getMessage());
        }
    }
}