package com.demo;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;

@WebServlet("/BookQueryServlet")
public class BookQueryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    // 数据库连接信息常量
//    private static final String DB_URL = "jdbc:mysql://47.242.181.61:33060/demo?useSSL=false&serverTimezone=UTC";
    private static final String DB_URL = "jdbc:mysql://47.242.181.61:33060/demo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "lotus";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String bookid = request.getParameter("bookid");
        if (bookid == null || bookid.trim().isEmpty()) {
            request.setAttribute("error", "图书ID不能为空");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM books WHERE bookid = ?");
        ) {
            pstmt.setString(1, bookid);
            
            try (ResultSet rst = pstmt.executeQuery()) {
                if (rst.next()) {
                    BookBean book = new BookBean();
                    book.setBookid(rst.getString("bookid"));
                    book.setTitle(rst.getString("title"));
                    book.setAuthor(rst.getString("author"));
                    book.setPrice(rst.getFloat("price"));
                    book.setPublisher(rst.getString("publisher"));
                    
                    request.setAttribute("book", book);
                    request.getRequestDispatcher("/displayBook.jsp").forward(request, response);
                } else {
                    request.setAttribute("error", "未找到ID为 " + bookid + " 的图书");
                    request.getRequestDispatcher("/error.jsp").forward(request, response);
                }
            }
        } catch (Exception e) {
            String errorMsg = "数据库操作失败: " + e.getMessage();
            log(errorMsg, e);
            request.setAttribute("error", errorMsg);
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    
    private Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
}
