package javabean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Admin {

	/**
	 * 用户登录方法
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @return 登录结果的字符串
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	@SuppressWarnings("null")
	public String login(String username, String password) throws ClassNotFoundException, SQLException {

		// 参数校验
		if (username == null || username.trim().equals("")) {
			return "账号不能为空";
		} else if (password == null || password.trim().equals("")) {
			return "密码不能为空";
		}

		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		// SQL查询语句，验证用户和密码
		String sql = "select * from admin where username=? and password=? limit 1";
		connection = Base.getConnection();
		pstmt = (PreparedStatement) connection.prepareStatement(sql);
		pstmt.setString(1, username);
		pstmt.setString(2, Util.passMd5(password));  // 假设Util.passMd5()是对密码的加密方法
		resultSet = pstmt.executeQuery();

		try {
			if (resultSet.next()) {  // 如果有记录，说明登录成功
				return "1";
			}
		} catch (Exception e) {
			return "发生未知错误";
		} finally {
			// 关闭数据库连接资源
			if (Base.closeResource(connection, pstmt, resultSet) == false) {
				return "关闭失败";
			}
		}

		// 如果没有记录，账号或密码错误
		return "账号或密码错误";
	}

	/**
	 * 获取图书列表方法，带分页查询功能
	 *
	 * @param page 当前页
	 * @param limit 每页显示条数
	 * @param where 查询条件
	 * @return 返回包含数据和总条数的Map
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public Map getBookList(String page, String limit, Map where) throws ClassNotFoundException, SQLException {
		Map<String, Object> map = new HashMap<String, Object>();
		String whereString = "";
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		connection = Base.getConnection();
		int number = Integer.valueOf(page);  // 页码
		int size = Integer.valueOf(limit);  // 每页条数

		// 构建查询语句
		String sql = "select * from books ";
		if (where != null && !where.isEmpty()) {
			whereString += " where " + where.get("condition") + " like '%" + where.get("conditionValue") + "%' ";
			sql += whereString;  // 根据条件拼接查询语句
		}
		sql += "order by id desc limit ?,? ";  // 分页查询

		pstmt = (PreparedStatement) connection.prepareStatement(sql);
		pstmt.setInt(1, (number - 1) * size);  // 设置分页参数
		pstmt.setInt(2, size);  // 每页显示的记录数

		resultSet = pstmt.executeQuery();
		JSONObject json = new JSONObject();
		String result = "";
		int i = 1;

		// 遍历查询结果并构造JSON格式的返回数据
		while (resultSet.next()) {
			json.put("id", resultSet.getInt("id"));
			json.put("name", resultSet.getString("name"));
			json.put("author", resultSet.getString("author"));
			json.put("library_id", resultSet.getInt("library_id"));
			json.put("sort_id", resultSet.getInt("sort_id"));
			json.put("position", resultSet.getString("position"));
			json.put("status", resultSet.getInt("status"));
			json.put("description", resultSet.getString("description"));

			// 拼接多个JSON对象
			if (i == 1) {
				result = json.toString();
			} else {
				result += "," + json.toString();
			}
			i++;
		}

		map.put("data", result);

		// 获取总数
		int count = 0;
		sql = "select count(*) as count from books ";
		if (where != null && !where.isEmpty()) {
			sql += whereString;  // 根据条件计算总数
		}
		pstmt = connection.prepareStatement(sql);
		resultSet = pstmt.executeQuery();
		if (resultSet.next()) {
			count = resultSet.getInt("count");
		}

		map.put("count", count);
		Base.closeResource(connection, pstmt, resultSet);
		return map;
	}

	/**
	 * 根据分类ID获取分类名称
	 *
	 * @param id 分类ID
	 * @return 分类名称
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static String getSortName(String id) throws ClassNotFoundException, SQLException {
		if (id == null || id.equals("")) {
			return "参数错误";
		}

		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		String sql = null;
		String result = null;

		connection = Base.getConnection();
		sql = "select name from book_sort where id=?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, id);
		resultSet = pstmt.executeQuery();
		if (resultSet.next()) {
			result = resultSet.getString("name");
		} else {
			result = "查询失败";
		}

		Base.closeResource(connection, pstmt, null);
		return result;
	}

	/**
	 * 根据书籍ID获取书籍详细信息
	 *
	 * @param id 书籍ID
	 * @return 书籍信息的ResultSet对象
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static ResultSet getBookInfo(int id) throws ClassNotFoundException, SQLException {
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		String sql = "select * from books where id=?";
		connection = Base.getConnection();
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, id);
		resultSet = pstmt.executeQuery();
		connection.close();

		if (resultSet.next()) {
			return resultSet;  // 返回查询到的结果
		}

		return null;  // 没有找到对应的书籍
	}

	/**
	 * 获取规则信息（此方法未使用）
	 *
	 * @return 包含规则信息的JSONArray
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static JSONArray getRules() throws ClassNotFoundException, SQLException {
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		String sql = "select * from rules";
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();

		connection = Base.getConnection();
		pstmt = connection.prepareStatement(sql);
		resultSet = pstmt.executeQuery();

		// 遍历规则表，构造JSON对象
		while (resultSet.next()) {
			jsonObject.put("id", resultSet.getString("id"));
			jsonObject.put("borrow_num", resultSet.getString("borrow_num"));
			jsonObject.put("borrow_library", resultSet.getString("borrow_library"));
			jsonObject.put("overtime_fee", resultSet.getString("overtime_fee"));
			jsonArray.add(jsonObject);
			System.out.println(jsonArray.toString());
		}

		Base.closeResource(connection, pstmt, resultSet);
		return jsonArray;
	}

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Admin admin = new Admin();
		System.out.println(admin.getSortName("2"));  // 示例，获取分类名称
		// Map map =  admin.getBookList("1", "100");
		// System.out.println(map.get("count"));  // 示例，获取书籍数量
	}
}
