package servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.Connection;

import javabean.Base;
import javabean.Common;
import javabean.Util;

/**
 * Servlet 实现类，用于添加借阅规则
 *
 * 该 Servlet 用于处理前端发送的 POST 请求，接收借阅规则的数据并将其保存到数据库中。
 */
@WebServlet("/admin/ruleAdd")
public class RuleAdd extends HttpServlet {

	/**
	 * 处理 POST 请求，添加借阅规则
	 *
	 * 该方法接收前端传来的借阅规则数据，并将其保存到数据库中。
	 *
	 * @param req 请求对象
	 * @param resp 响应对象
	 * @throws ServletException 如果发生 Servlet 错误
	 * @throws IOException 如果发生 I/O 错误
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置响应内容类型为 JSON
		resp.setContentType("application/json; charset=utf8");

		// 初始化数据库连接相关变量
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		int result = 0;
		String sql = "";
		String borrow_library = "";

		// 返回的数据初始化
		int code = 1;  // 默认为失败
		String msg = "";  // 默认为错误信息

		// 获取数据：首先检查允许借阅的图书馆
		int num = 0;
		try {
			// 获取图书馆的配置信息
			Map<String, String> libraryMap = Common.getLibraryMap();
			// 遍历图书馆信息，获取前端传来的借阅图书馆
			for (String key : libraryMap.keySet()) {
				if (req.getParameter("borrow_library[" + key + "]") != null) {
					if (num == 0) {
						borrow_library += key;
						num++;
					} else {
						borrow_library += "、" + key;
					}
				}
			}
			// 检查是否选择了允许的图书馆
			if (borrow_library.isEmpty()) {
				msg = "允许图书馆不能为空";
			}
		} catch (SQLException e) {
			msg = "获取图书馆失败";
		}

		// 获取其他规则参数
		String borrow_num = req.getParameter("borrow_num");  // 借阅数量
		String limit_day = req.getParameter("limit_day");  // 限制天数
		String overtime_fee = req.getParameter("overtime_fee");  // 逾期费用

		// 如果借阅图书馆不为空，保存借阅规则
		if (msg.isEmpty()) {
			try {
				connection = Base.getConnection();
				sql = "insert into rules(borrow_num, limit_day, borrow_library, overtime_fee) values(?,?,?,?)";
				pstmt = connection.prepareStatement(sql);
				pstmt.setString(1, borrow_num);
				pstmt.setString(2, limit_day);
				pstmt.setString(3, borrow_library);
				pstmt.setString(4, overtime_fee);
				result = pstmt.executeUpdate();

				// 判断插入是否成功
				if (result == 1) {
					code = 0;
					msg = "success";
				}
			} catch (ClassNotFoundException e) {
				msg = "classnotfound";
			} catch (SQLException e) {
				msg = "SQL错误";
			} finally {
				try {
					// 关闭数据库资源
					Base.closeResource(connection, pstmt, null);
				} catch (SQLException e) {
					msg = "关闭失败";
				}
			}
		}

		// 将结果返回给前端
		PrintWriter out = resp.getWriter();
		out.print(Util.jsonResponse(code, msg, null));
	}
}
