<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="org.json.JSONObject" %>
<%@ page import="org.json.JSONArray" %>

<%
    // 跨域指标查询代理 JSP
    // 用途：调用 C# MetricsController 的 API 端点，解决跨域问题
    
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    
    String action = request.getParameter("action");
    String handoverNumber = request.getParameter("handoverNumber");
    String neutralWaybillNumber = request.getParameter("neutralWaybillNumber");
    String date = request.getParameter("date");
    String startDate = request.getParameter("startDate");
    String endDate = request.getParameter("endDate");
    String waybillsJson = request.getParameter("waybills");
    String callback = request.getParameter("callback");
    
    // 获取响应格式 (JSON 或 JSONP)
    String format = request.getParameter("format");
    if (format == null) {
        format = (callback != null && !callback.isEmpty()) ? "jsonp" : "json";
    }
    
    // 获取基础URL
    String environment = request.getParameter("env");
    if (environment == null) {
        environment = "test";
    }
    
    String baseUrl;
    if ("local".equals(environment)) {
        baseUrl = "http://localhost:5002";
    } else if ("production".equals(environment)) {
        baseUrl = "https://lr.tooexp.com";
    } else {
        baseUrl = "http://172.232.21.79:5002";
    }
    
    String apiUrl = null;
    JSONObject resultJson = new JSONObject();
    
    try {
        if ("getLabelRate".equals(action)) {
            // 获取标签率
            if (handoverNumber == null || handoverNumber.isEmpty()) {
                resultJson.put("success", false);
                resultJson.put("error", "handoverNumber is required");
            } else {
                apiUrl = baseUrl + "/api/metrics/label-rate?handoverNumber=" + URLEncoder.encode(handoverNumber, "UTF-8");
            }
        } 
        else if ("getOrderAssessment".equals(action)) {
            // 获取订单评估
            if (neutralWaybillNumber == null || neutralWaybillNumber.isEmpty()) {
                resultJson.put("success", false);
                resultJson.put("error", "neutralWaybillNumber is required");
            } else {
                apiUrl = baseUrl + "/api/metrics/order-assessment?neutralWaybillNumber=" + URLEncoder.encode(neutralWaybillNumber, "UTF-8");
            }
        }
        else if ("getDailySummary".equals(action)) {
            // 获取每日汇总
            if (date != null && !date.isEmpty()) {
                apiUrl = baseUrl + "/api/metrics/daily-summary?date=" + URLEncoder.encode(date, "UTF-8");
            } else {
                apiUrl = baseUrl + "/api/metrics/daily-summary";
            }
        }
        else if ("getDailySummaries".equals(action)) {
            // 获取日期范围汇总
            if ((startDate == null || startDate.isEmpty()) || (endDate == null || endDate.isEmpty())) {
                resultJson.put("success", false);
                resultJson.put("error", "startDate and endDate are required");
            } else {
                apiUrl = baseUrl + "/api/metrics/daily-summaries?startDate=" + URLEncoder.encode(startDate, "UTF-8") + 
                         "&endDate=" + URLEncoder.encode(endDate, "UTF-8");
            }
        }
        else if ("get24HCompletionRate".equals(action)) {
            // 获取24小时完成率
            if (date != null && !date.isEmpty()) {
                apiUrl = baseUrl + "/api/metrics/24h-completion-rate?date=" + URLEncoder.encode(date, "UTF-8");
            } else {
                apiUrl = baseUrl + "/api/metrics/24h-completion-rate";
            }
        }
        else if ("getDailyCompletionRate".equals(action)) {
            // 获取每日完成率
            if (date != null && !date.isEmpty()) {
                apiUrl = baseUrl + "/api/metrics/daily-completion-rate?date=" + URLEncoder.encode(date, "UTF-8");
            } else {
                apiUrl = baseUrl + "/api/metrics/daily-completion-rate";
            }
        }
        else if ("getDailyDashboard".equals(action)) {
            // 获取日汇总完整仪表盘数据
            if (date != null && !date.isEmpty()) {
                apiUrl = baseUrl + "/api/metrics/daily-dashboard?date=" + URLEncoder.encode(date, "UTF-8");
            } else {
                apiUrl = baseUrl + "/api/metrics/daily-dashboard";
            }
        }
        else if ("getBatchOrderMetrics".equals(action)) {
            // 批量获取订单指标
            if (waybillsJson == null || waybillsJson.isEmpty()) {
                resultJson.put("success", false);
                resultJson.put("error", "waybills is required");
            } else {
                apiUrl = baseUrl + "/api/metrics/batch-order-metrics";
            }
        }
        else if ("recalculateLabelRate".equals(action)) {
            // 重新计算标签率
            if (handoverNumber == null || handoverNumber.isEmpty()) {
                resultJson.put("success", false);
                resultJson.put("error", "handoverNumber is required");
            } else {
                apiUrl = baseUrl + "/api/metrics/recalculate-label-rate";
            }
        }
        else {
            resultJson.put("success", false);
            resultJson.put("error", "Unknown action: " + action);
        }
        
        // 如果没有错误，调用API
        if (apiUrl != null) {
            String method = "getBatchOrderMetrics".equals(action) || "recalculateLabelRate".equals(action) ? "POST" : "GET";
            String response_text = callApi(apiUrl, method, waybillsJson, handoverNumber);
            
            // 处理 JSONP 响应格式
            if ("jsonp".equals(format) && callback != null && !callback.isEmpty()) {
                if (callback.matches("^[a-zA-Z_$][a-zA-Z0-9_$]*$")) {
                    out.print(callback + "(" + response_text + ");");
                } else {
                    out.print("jsonp_error({\"error\": \"Invalid callback name\"});");
                }
            } else {
                out.print(response_text);
            }
            return;
        }
        
    } catch (Exception e) {
        resultJson.put("success", false);
        resultJson.put("error", e.getMessage());
    }
    
    // 输出结果（支持 JSONP 格式）
    if ("jsonp".equals(format) && callback != null && !callback.isEmpty()) {
        if (callback.matches("^[a-zA-Z_$][a-zA-Z0-9_$]*$")) {
            out.print(callback + "(" + resultJson.toString() + ");");
        } else {
            out.print("jsonp_error({\"error\": \"Invalid callback name\"});");
        }
    } else {
        out.print(resultJson.toString());
    }
%>

<%!
    private String callApi(String urlString, String method, String bodyForBatch, String handoverNumberForRecalc) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            
            // 如果是 POST 请求，发送请求体
            if ("POST".equals(method)) {
                connection.setDoOutput(true);
                
                String requestBody = null;
                if (bodyForBatch != null && !bodyForBatch.isEmpty()) {
                    // 批量订单指标请求
                    requestBody = bodyForBatch;
                } else if (handoverNumberForRecalc != null && !handoverNumberForRecalc.isEmpty()) {
                    // 重新计算标签率请求
                    org.json.JSONObject json = new org.json.JSONObject();
                    json.put("handoverNumber", handoverNumberForRecalc);
                    requestBody = json.toString();
                } else {
                    requestBody = "{}";
                }
                
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }
            }
            
            // 读取响应
            int responseCode = connection.getResponseCode();
            BufferedReader reader;
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
            }
            
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            connection.disconnect();
            
            return response.toString();
            
        } catch (Exception e) {
            org.json.JSONObject error = new org.json.JSONObject();
            try {
                error.put("success", false);
                error.put("error", e.getMessage());
            } catch (Exception ex) {
                // ignore
            }
            return error.toString();
        }
    }
%>
