package servlet.admin;

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

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.JDBCBean;
import net.sf.json.JSONObject;

/**
 * Servlet 实现类，用于管理员添加借阅卡
 *
 * 该 Servlet 处理管理员请求添加新的借阅卡的操作。接收借阅卡的相关信息（读者、密码、规则、状态），
 * 向数据库中插入一条新的借阅卡记录，并返回插入结果。
 */
@WebServlet("/admin/cardAdd")
public class CardAdd 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，字符编码为 UTF-8
		resp.setContentType("application/json; charset=utf8");

		// 获取传递的参数
		String reader = req.getParameter("reader");     // 读者
		String password = req.getParameter("password"); // 密码
		String rule_id = req.getParameter("rule_id");   // 借阅规则 ID
		String status = req.getParameter("status");     // 借阅卡状态

		// 初始化返回信息
		String code = "1";
		String msg = "error";
		String data = "";
		JSONObject json = new JSONObject();
		JSONObject jsonData = new JSONObject();

		// 数据库连接对象
		Connection connection = null;
		Connection connection1 = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		String sql = null;
		int result = 0;
		ResultSet dataSet = null;

		// 参数不能为空校验
		if(reader == null || password == null || rule_id == null || status == null) {
			code = "1";
			msg = "值不能为空";
		} else {
			try {
				// 获取数据库连接
				connection = (Connection) Base.getConnection();

				// 插入借阅卡的 SQL 语句
				sql = "insert into borrow_card(password, reader, rule_id, status) values(?,?,?,?)";
				pstmt = connection.prepareStatement(sql);
				pstmt.setString(1, password);
				pstmt.setString(2, reader);
				pstmt.setString(3, rule_id);
				pstmt.setString(4, status);

				// 执行插入操作
				result = pstmt.executeUpdate();

				// 获取插入记录的 ID
				connection1 = (Connection) Base.getConnection();
				String findIdSql = "select id from borrow_card where password=? and reader=? and rule_id=? and status=? limit 1";
				pstmt1 = connection1.prepareStatement(findIdSql);
				pstmt1.setString(1, password);
				pstmt1.setString(2, reader);
				pstmt1.setString(3, rule_id);
				pstmt1.setString(4, status);
				dataSet = pstmt1.executeQuery();

				// 获取插入记录的 ID
				if(dataSet.next()) {
					jsonData.put("id", dataSet.getString("id"));
				}
			} catch (ClassNotFoundException e) {
				msg = "发生异常";
			} catch (SQLException e) {
				msg = "sql错误";
				System.out.println("sql失败");
			} finally {
				// 关闭数据库资源
				try {
					Base.closeResource(connection, pstmt, null);
					Base.closeResource(connection1, pstmt1, dataSet);
				} catch (SQLException e) {
					msg = "关闭资源失败";
				}
			}

			// 根据插入结果更新响应消息
			if(result == 1 && !jsonData.isNullObject() && !jsonData.isEmpty()) {
				code = "0";
				msg = "添加成功";
			} else {
				code = "1";
				msg = "执行失败";
			}
		}

		// 构造 JSON 响应
		json.put("code", code);
		json.put("msg", msg);
		json.put("data", jsonData.toString());

		// 输出 JSON 响应到客户端
		PrintWriter out = resp.getWriter();
		out.print(json.toString());
	}
}
