<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*, org.json.JSONArray, org.json.JSONObject" %>
<%
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "SchoolST", "123456");

        // 查询所有维度和题目
        String sql = "SELECT d.dimension_id, d.name AS dimension_name, d.weight, q.question_id, q.question_text " +
                     "FROM dimensions d " +
                     "JOIN questions q ON d.dimension_id = q.dimension_id " +
                     "ORDER BY d.dimension_id, q.question_id";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        JSONArray dimensions = new JSONArray();
        JSONObject currentDimension = null;
        int lastDimensionId = -1;

        while (rs.next()) {
            int dimensionId = rs.getInt("dimension_id");
            if (dimensionId != lastDimensionId) {
                // 新维度
                if (currentDimension != null) {
                    dimensions.put(currentDimension);
                }
                currentDimension = new JSONObject();
                currentDimension.put("dimension_id", dimensionId);
                currentDimension.put("dimension_name", rs.getString("dimension_name"));
                currentDimension.put("weight", rs.getFloat("weight"));
                currentDimension.put("questions", new JSONArray());
                lastDimensionId = dimensionId;
            }

            // 添加题目
            JSONObject question = new JSONObject();
            question.put("question_id", rs.getInt("question_id"));
            question.put("question_text", rs.getString("question_text"));
            currentDimension.getJSONArray("questions").put(question);
        }

        // 添加最后一个维度
        if (currentDimension != null) {
            dimensions.put(currentDimension);
        }

        rs.close();
        stmt.close();
        conn.close();

        // 输出调试信息
        System.out.println("Debug: Dimensions and questions loaded successfully.");
        System.out.println("Debug: JSON Data: " + dimensions.toString());

        out.print(dimensions.toString()); // 输出 JSON 数据
    } catch (Exception e) {
        e.printStackTrace();
        out.print("{\"error\": \"Failed to load questions.\"}");
    }
%>