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 用于处理编辑借阅规则的请求，接收规则的 ID 和修改后的信息，
 * 然后根据 ID 更新对应的借阅规则数据。
 */
@WebServlet("/admin/ruleEdit")
public class RuleEdit extends HttpServlet {

	/**
	 * 处理 POST 请求，编辑借阅规则
	 *
	 * 该方法接收前端传来的规则 ID 和修改后的数据，根据 ID 更新数据库中的借阅规则。
	 *
	 * @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");
		String id = req.getParameter("id");

		// 执行数据库更新操作
		try {
			connection = Base.getConnection();
			sql = "update rules set borrow_num=?, limit_day=?, borrow_library=?, overtime_fee=? where id=?";
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, borrow_num);
			pstmt.setString(2, limit_day);
			pstmt.setString(3, borrow_library);
			pstmt.setString(4, overtime_fee);
			pstmt.setString(5, id);
			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));
	}
}
