package servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
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 javabean.Base;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet 实现类，用于获取借阅卡列表
 *
 * 该 Servlet 处理管理员请求获取借阅卡列表的操作。支持分页和条件查询，返回符合条件的借阅卡数据。
 */
@WebServlet("/admin/cardList")
public class CardList extends HttpServlet {

	/**
	 * 处理 GET 请求，获取借阅卡列表
	 *
	 * 该方法处理分页和条件查询，查询借阅卡表中的数据，并返回符合条件的借阅卡信息。
	 *
	 * @param req 请求对象
	 * @param resp 响应对象
	 * @throws ServletException 如果发生 Servlet 错误
	 * @throws IOException 如果发生 I/O 错误
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置响应内容类型为 JSON，字符编码为 UTF-8
		resp.setContentType("application/json; charset=utf8");

		// 接收查询参数：limit, page, condition 和 conditionValue
		String limit = req.getParameter("limit");
		String page = req.getParameter("page");
		String condition = req.getParameter("condition");
		String conditionValue = req.getParameter("conditionValue");

		// 初始化 SQL 查询条件
		String where = null; // 无限制条件

		// 设置默认值
		if (page == null) {
			page = "1";
		}
		if (limit == null) {
			limit = "10";
		}

		// 初始化数据库连接和 SQL 语句
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		int code = 1;
		String msg = "error";
		int count = 0;
		String sql = "";

		// 准备返回数据的 JSON 对象
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonResult = new JSONObject();

		try {
			// 获取数据库连接
			connection = (Connection) Base.getConnection();

			// 初始 SQL 查询语句
			sql = "select id, password, reader, rule_id, status from borrow_card";

			// 如果有查询条件，构造 where 子句
			if (condition != null && conditionValue != null && !condition.isEmpty() && !conditionValue.isEmpty()) {
				where = " where " + condition + " like '%" + conditionValue + "%'";
				sql = sql + where;
			}

			// 构造分页查询
			sql += " order by id desc limit ?,?";

			pstmt = connection.prepareStatement(sql);
			try {
				// 设置分页参数
				pstmt.setInt(1, (Integer.parseInt(page) - 1) * Integer.parseInt(limit));
				pstmt.setInt(2, Integer.parseInt(limit));
			} catch (NumberFormatException | SQLException e1) {
				// 异常捕获，避免参数错误影响执行
			}

			// 执行查询
			resultSet = pstmt.executeQuery();
			while (resultSet.next()) {
				// 构造每一条借阅卡记录的 JSON 数据
				jsonObject.put("id", resultSet.getString("id"));
				jsonObject.put("password", resultSet.getString("password"));
				jsonObject.put("reader", resultSet.getString("reader"));
				jsonObject.put("rule_id", resultSet.getString("rule_id"));
				jsonObject.put("status", resultSet.getString("status"));
				jsonArray.add(jsonObject);
			}

			// 获取借阅卡总数，用于分页
			sql = "select count(*) as count from borrow_card";
			if (where != null) {
				sql = sql + where;
			}

			pstmt = connection.prepareStatement(sql);
			resultSet = pstmt.executeQuery();
			if (resultSet.next()) {
				count = resultSet.getInt("count");
			}

			// 判断查询结果是否为空
			if (!jsonArray.isEmpty()) {
				code = 0;
				msg = "查询成功";
			}
		} catch (ClassNotFoundException e) {
			msg = "数据库连接失败";
			e.printStackTrace();
		} catch (SQLException e) {
			msg = "SQL 错误";
		} finally {
			// 关闭数据库连接和资源
			try {
				Base.closeResource(connection, pstmt, resultSet);
			} catch (SQLException e) {
				msg = "资源关闭失败";
			}
		}

		// 构造返回的 JSON 数据
		jsonResult.put("code", code);
		jsonResult.put("count", count);
		jsonResult.put("msg", msg);
		jsonResult.put("data", jsonArray.toString());

		// 输出响应
		PrintWriter out = resp.getWriter();
		out.print(jsonResult.toString());
	}
}
