package aaa3;

import java.text.SimpleDateFormat;
import java.util.*;

// 图书馆管理系统类
class LibraryManagementSystem {
    private Map<String, User> users;
    private List<Book> books;
    private Scanner scanner;

    public LibraryManagementSystem() {
        this.users = new HashMap<>();
        this.books = new ArrayList<>();
        this.scanner = new Scanner(System.in);
    }

    // 用户注册
    public User userRegister() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        if (users.containsKey(username)) {
            System.out.println("该用户名已存在，请重新注册。");
            return null;
        }
        User newUser = new User(username, password);
        users.put(username, newUser);
        System.out.println("注册成功！自动为您登录。");
        return newUser;
    }

    // 用户登录
    public User userLogin() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        User user = users.get(username);
        if (user != null && user.password.equals(password)) {
            System.out.println("登录成功！");
            return user;
        } else {
            System.out.println("用户名或密码错误，请重试。");
            return null;
        }
    }

    // 管理员登录
    public boolean adminLogin() {
        System.out.print("请输入管理员用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入管理员密码: ");
        String password = scanner.nextLine();
        if (username.equals("admin") && password.equals("admin123")) {
            System.out.println("管理员登录成功！");
            return true;
        } else {
            System.out.println("管理员用户名或密码错误，请重试。");
            return false;
        }
    }

    // 查找所有书籍
    public void findAllBooks() {
        if (books.isEmpty()) {
            System.out.println("图书馆暂无书籍。");
        } else {
            for (Book book : books) {
                System.out.println("书名: " + book.title + (book.isBorrowed ? " (已借出)" : " (可借阅)") + "，库存: " + book.inventory);
            }
        }
    }

    // 用户借阅书籍
    public void borrowBook(User user) {
        // 新增：显示可借阅的书籍列表
        System.out.println("可借阅的书籍如下：");
        List<Book> availableBooks = new ArrayList<>();
        for (Book book : books) {
            if (!book.isBorrowed && book.inventory > 0) {
                availableBooks.add(book);
                System.out.println("书名: " + book.title + "，库存: " + book.inventory);
            }
        }
        if (availableBooks.isEmpty()) {
            System.out.println("目前没有可借阅的书籍。");
            return;
        }

        System.out.print("请输入要借阅的书籍名称: ");
        String title = scanner.nextLine();
        for (Book book : availableBooks) {  // 修改：直接遍历可借阅列表
            if (book.title.equals(title)) {
                book.isBorrowed = true;
                book.borrower = user.username;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                book.borrowDate = sdf.format(new Date());
                user.borrowedBooks.add(book);
                book.borrowHistory.add(user.username + " 于 " + book.borrowDate + " 借阅");
                book.inventory--;
                System.out.println("借阅成功！借阅日期为：" + book.borrowDate);
                return;
            }
        }
        System.out.println("该书不可借阅或不存在。");
    }

    // 新增方法：根据书名借阅书籍
    public void borrowBookWithTitle(User user, String title) {
        for (Book book : books) {
            if (book.title.equals(title)) {
                if (!book.isBorrowed && book.inventory > 0) {
                    book.isBorrowed = true;
                    book.borrower = user.username;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    book.borrowDate = sdf.format(new Date());
                    user.borrowedBooks.add(book);
                    book.borrowHistory.add(user.username + " 于 " + book.borrowDate + " 借阅");
                    book.inventory--;
                    System.out.println("借阅成功！借阅日期为：" + book.borrowDate);
                    return;
                }
            }
        }
        System.out.println("该书不可借阅或不存在。");
    }

    // 用户归还书籍
    public void returnBook(User user) {
        System.out.println("当前你的在借书籍如下：");
        queryBorrowedBooks(user);
        System.out.print("请输入要归还的书籍名称: ");
        String title = scanner.nextLine();
        for (Book book : user.borrowedBooks) {
            if (book.title.equals(title)) {
                book.isBorrowed = false;
                book.borrower = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                book.returnDate = sdf.format(new Date());
                book.borrowHistory.add(" 于 " + book.returnDate + " 归还");
                user.borrowedBooks.remove(book);
                book.inventory++;
                System.out.println("归还成功！归还日期为：" + book.returnDate);
                return;
            }
        }
        System.out.println("你没有借阅这本书。");
    }

    // 查询用户在借书籍
    public void queryBorrowedBooks(User user) {
        if (user.borrowedBooks.isEmpty()) {
            System.out.println("你没有借阅任何书籍。");
        } else {
            for (Book book : user.borrowedBooks) {
                System.out.println("书名: " + book.title + ", 借阅日期: " + book.borrowDate);
            }
        }
    }

    // 管理员新增书籍
    public void addBook() {
        System.out.print("请输入要新增的书籍名称: ");
        String title = scanner.nextLine();
        for (Book book : books) {
            if (book.title.equals(title)) {
                book.inventory++;
                System.out.println("书籍库存增加成功，当前库存: " + book.inventory);
                return;
            }
        }
        books.add(new Book(title));
        System.out.println("书籍添加成功！当前库存: 1");
    }

    // 新增方法：根据书名添加书籍
    public void addBookWithTitle(String title) {
        for (Book book : books) {
            if (book.title.equals(title)) {
                book.inventory++;
                System.out.println("书籍库存增加成功，当前库存: " + book.inventory);
                return;
            }
        }
        books.add(new Book(title));
        System.out.println("书籍添加成功！当前库存: 1");
    }

    // 管理员替用户归还书籍
    public void adminReturnBook() {
        System.out.println("所有用户的在借书籍名单如下：");
        boolean hasBorrowedBooks = false;
        for (User user : users.values()) {
            if (!user.borrowedBooks.isEmpty()) {
                hasBorrowedBooks = true;
                System.out.println("用户: " + user.username);
                for (Book book : user.borrowedBooks) {
                    System.out.println("  书名: " + book.title + ", 借阅日期: " + book.borrowDate);
                }
            }
        }
        if (!hasBorrowedBooks) {
            System.out.println("所有用户都没有借阅书籍。");
            return;
        }

        System.out.print("请输入要操作的用户姓名: ");
        String username = scanner.nextLine();
        User user = users.get(username);
        if (user == null) {
            System.out.println("该用户不存在。");
            return;
        }
        System.out.print("请输入要归还的书籍名称: ");
        String title = scanner.nextLine();
        for (Book book : user.borrowedBooks) {
            if (book.title.equals(title)) {
                book.isBorrowed = false;
                book.borrower = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                book.returnDate = sdf.format(new Date());
                book.borrowHistory.add(" 于 " + book.returnDate + " 归还");
                user.borrowedBooks.remove(book);
                book.inventory++;
                System.out.println("替用户归还成功！归还日期为：" + book.returnDate);
                return;
            }
        }
        System.out.println("该用户没有借阅这本书。");
    }

    // 管理员查询所有用户的在借书籍
    public void adminQueryAllBorrowedBooks() {
        boolean hasBorrowedBooks = false;
        for (User user : users.values()) {
            if (!user.borrowedBooks.isEmpty()) {
                hasBorrowedBooks = true;
                System.out.println("用户: " + user.username);
                for (Book book : user.borrowedBooks) {
                    System.out.println("  书名: " + book.title + ", 借阅日期: " + book.borrowDate);
                }
            }
        }
        if (!hasBorrowedBooks) {
            System.out.println("所有用户都没有借阅书籍。");
        }
    }

    // 管理员帮用户注册
    public void adminRegisterUser() {
        System.out.print("请输入要注册的用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入要注册的用户密码: ");
        String password = scanner.nextLine();
        if (users.containsKey(username)) {
            System.out.println("该用户名已存在，请重新注册。");
        } else {
            users.put(username, new User(username, password));
            System.out.println("管理员帮用户注册成功！");
        }
    }

    // 新增方法：根据用户名和密码注册用户
    public void adminRegisterUserWithInfo(String username, String password) {
        if (users.containsKey(username)) {
            System.out.println("该用户名已存在，请重新注册。");
        } else {
            users.put(username, new User(username, password));
            System.out.println("管理员帮用户注册成功！");
        }
    }

    // 新增方法：根据用户名获取用户对象
    public User getUserByName(String username) {
        return users.get(username);
    }

    // 管理员查看用户借阅历史
    public void adminViewBorrowHistory() {
        System.out.println("所有书籍的借阅历史如下：");
        for (Book book : books) {
            System.out.println("书名: " + book.title);
            if (book.borrowHistory.isEmpty()) {
                System.out.println("  暂无借阅历史。");
            } else {
                for (String history : book.borrowHistory) {
                    System.out.println("  " + history);
                }
            }
        }
    }

    // 管理员添加已借出的书籍
    public void addBorrowedBook() {
        System.out.print("请输入要添加的已借出书籍名称: ");
        String title = scanner.nextLine();
        System.out.print("请输入借阅人姓名: ");
        String borrower = scanner.nextLine();
        User user = users.get(borrower);
        if (user == null) {
            System.out.println("该用户不存在，请先注册用户。");
            return;
        }

        // 检查书籍是否存在
        Book existingBook = null;
        for (Book book : books) {
            if (book.title.equals(title)) {
                existingBook = book;
                break;
            }
        }

        if (existingBook == null) {
            System.out.println("没有该书籍,无法借出");
            return;
        }

        if (existingBook.inventory > 0) {
            existingBook.isBorrowed = true;
            existingBook.borrower = borrower;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            existingBook.borrowDate = sdf.format(new Date());
            user.borrowedBooks.add(existingBook);
            existingBook.borrowHistory.add(borrower + " 于 " + existingBook.borrowDate + " 借阅");
            existingBook.inventory--;
            System.out.println("已借出书籍添加成功！当前库存: " + existingBook.inventory);
        } else {
            System.out.println("该书籍无库存，无法借出。");
        }
    }

    // 管理员查看用户数量
    public void adminViewUserCount() {
        System.out.println("当前系统中的用户数量为: " + users.size());
        System.out.println("用户列表：");
        for (String username : users.keySet()) {
            System.out.println("==>" + username);
        }
    }

    // 管理员删除书籍
    public void adminDeleteBook() {
        System.out.print("请输入要删除的书籍名称: ");
        String title = scanner.nextLine();

        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            if (book.title.equals(title)) {
                if (book.isBorrowed) { // 检查是否已被借阅
                    System.out.println("该书已被借阅，无法删除！");
                    return;
                }
                iterator.remove();
                System.out.println("书籍 \"" + title + "\" 删除成功！");
                return;
            }
        }
        System.out.println("未找到书籍 \"" + title + "\" 或该书籍已被删除。");
    }

    // 主菜单
    public void mainMenu() {
        while (true) {
            System.out.println("\n--- 图书馆管理系统 ---");
            System.out.println("1. 用户注册");
            System.out.println("2. 用户登录");
            System.out.println("3. 管理员登录");
            System.out.println("4. 退出系统");
            System.out.print("请选择操作: ");
            int choice;
            while (true) { // 新增循环确保输入整数
                try {
                    choice = scanner.nextInt();
                    scanner.nextLine(); // 消耗换行符
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("无效的选择，请输入1 - 9的整数: ");
                    scanner.nextLine(); // 清除无效输入
                }
            }
            switch (choice) {
                case 1:
                    User newUser = userRegister();
                    if (newUser != null) {
                        userMenu(newUser);
                    }
                    break;
                case 2:
                    User user = userLogin();
                    if (user != null) {
                        userMenu(user);
                    }
                    break;
                case 3:
                    if (adminLogin()) {
                        adminMenu();
                    }
                    break;
                case 4:
                    System.out.println("退出系统，感谢使用！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    // 用户菜单
    public void userMenu(User user) {
        while (true) {
            System.out.println("--- 用户菜单 ---");
            System.out.println("1. 查找所有书籍");
            System.out.println("2. 借阅书籍");
            System.out.println("3. 归还书籍");
            System.out.println("4. 查询在借书籍");
            System.out.println("5. 退出登录");
            System.out.print("请选择操作: ");
            int choice;
            while (true) { // 新增循环确保输入整数
                try {
                    choice = scanner.nextInt();
                    scanner.nextLine(); // 消耗换行符
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("无效的选择，请输入1 - 9的整数: ");
                    scanner.nextLine(); // 清除无效输入
                }
            }
            switch (choice) {
                case 1:
                    findAllBooks();
                    break;
                case 2:
                    borrowBook(user);
                    break;
                case 3:
                    returnBook(user);
                    break;
                case 4:
                    queryBorrowedBooks(user);
                    break;
                case 5:
                    System.out.println("退出登录成功！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    // 管理员菜单
    public void adminMenu() {
        while (true) {
            System.out.println("--- 管理员菜单 ---");
            System.out.println("1. 新增书籍");
            System.out.println("2. 查找所有书籍");
            System.out.println("3. 替用户归还书籍");
            System.out.println("4. 查询所有用户的在借书籍");
            System.out.println("5. 帮用户注册");
            System.out.println("6. 查看用户借阅历史");
            System.out.println("7. 添加已借出的书籍");
            System.out.println("8. 查看用户数量");
            System.out.println("9. 删除书籍");
            System.out.println("10. 退出登录");
            System.out.print("请选择操作: ");
            int choice;
            while (true) { // 新增循环确保输入整数
                try {
                    choice = scanner.nextInt();
                    scanner.nextLine(); // 消耗换行符
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("无效的选择，请输入1 - 9的整数: ");
                    scanner.nextLine(); // 清除无效输入
                }
            }
            switch (choice) {
                case 1:
                    addBook();
                    break;
                case 2:
                    findAllBooks();
                    break;
                case 3:
                    adminReturnBook();
                    break;
                case 4:
                    adminQueryAllBorrowedBooks();
                    break;
                case 5:
                    adminRegisterUser();
                    break;
                case 6:
                    adminViewBorrowHistory();
                    break;
                case 7:
                    addBorrowedBook();
                    break;
                case 8:
                    adminViewUserCount();
                    break;
                case 9:
                    adminDeleteBook();
                    break;
                case 10:
                    System.out.println("管理员退出登录成功！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }
}