/*
 * @Author: Student author@example.com
 * @Date: 2025-01-03 01:29:21
 * @LastEditors: Student author@example.com
 * @LastEditTime: 2025-01-03 09:49:24
 * @FilePath: \LibraryManageSystem\src\UI.cpp
 * @Description: Coding with UTF-8
 *
 * Copyright (c) 2025 by Student, All Rights Reserved.
 */
#include "../include/UI.h"
#include <iostream>
#include <iomanip>
#include <limits>
#include <cstdlib>
#include <fstream>

/**
 * @brief UI类构造函数
 * @param sys 图书管理系统对象引用
 */
UI::UI(LibrarySystem &sys) : system(sys) {}

/**
 * @brief 清空控制台屏幕
 */
void UI::clearScreen() const
{
#ifdef _WIN32
    std::system("cls");
#else
    std::system("clear");
#endif
}

/**
 * @brief 绘制分隔线
 * @param c 分隔线字符
 */
void UI::drawLine(char c) const
{
    std::cout << std::string(60, c) << std::endl;
}

/**
 * @brief 绘制标题
 * @param title 标题文本
 */
void UI::drawTitle(const std::string &title) const
{
    clearScreen();
    drawLine('=');
    std::cout << std::setw(30 + title.length() / 2) << title << std::endl;
    drawLine('=');
}

/**
 * @brief 等待用户按回车键继续
 */
void UI::waitForEnter() const
{
    std::cout << "\n按回车键继续...";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.get();
}

/**
 * @brief 获取用户输入的选项
 * @param min 最小选项值
 * @param max 最大选项值
 * @return 用户选择的选项值
 */
int UI::getChoice(int min, int max) const
{
    int choice;
    while (true)
    {
        std::cout << "\n请输入选项 (" << min << "-" << max << "): ";
        if (std::cin >> choice && choice >= min && choice <= max)
        {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            return choice;
        }
        std::cout << "输入无效，请重试。" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

/**
 * @brief 获取用户输入的字符串
 * @param prompt 提示信息
 * @return 用户输入的字符串
 */
std::string UI::getInput(const std::string &prompt) const
{
    std::string input;
    std::cout << prompt;
    std::getline(std::cin, input);
    return input;
}

/**
 * @brief 显示主菜单
 */
void UI::displayMainMenu() const
{
    drawTitle("图书管理系统");
    std::cout << "\n1. 登录系统"
              << "\n2. 注册账号"
              << "\n3. 退出程序"
              << std::endl;
    drawLine('-');
}

/**
 * @brief 显示登录界面
 */
void UI::displayLoginScreen()
{
    drawTitle("用户登录");
}

/**
 * @brief 显示注册界面
 */
void UI::displayRegisterScreen()
{
    drawTitle("用户注册");
}

/**
 * @brief 处理主菜单逻辑
 */
void UI::handleMainMenu()
{
    while (true)
    {
        displayMainMenu();
        int choice = getChoice(1, 3);

        switch (choice)
        {
        case 1:
            handleLogin();
            break;
        case 2:
            handleRegister();
            break;
        case 3:
            std::cout << "\n感谢使用图书管理系统，再见！" << std::endl;
            system.memberManager.saveToFile();
            return;
        }
    }
}

/**
 * @brief 处理用户登录
 */
void UI::handleLogin()
{
    displayLoginScreen();
    std::string id = getInput("账号: ");
    std::string password = getInput("密码: ");

    if (system.login(id, password))
    {
        std::cout << "\n登录成功！" << std::endl;
        std::cout << "用户类型: " << (system.isAdmin() ? "管理员" : "普通用户") << std::endl;
        std::cout << "按回车继续..." << std::endl;
        waitForEnter();

        if (system.isAdmin())
        {
            std::cout << "进入管理员菜单..." << std::endl;
            handleAdminMenu();
        }
        else
        {
            std::cout << "进入用户菜单..." << std::endl;
            handleUserMenu();
        }
        std::cout << "菜单处理完成，返回主菜单..." << std::endl;
        return;
    }
    else
    {
        std::cout << "\n账号或密码错误！" << std::endl;
        waitForEnter();
        return;
    }
}

/**
 * @brief 处理用户注册
 */
void UI::handleRegister()
{
    displayRegisterScreen();

    std::string id = getInput("请输入用户名: ");
    if (id.empty())
    {
        std::cout << "\n用户名不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    if (system.memberManager.findMember(id))
    {
        std::cout << "\n该用户名已被注册！" << std::endl;
        waitForEnter();
        return;
    }

    std::string name = getInput("请输入姓名: ");
    if (name.empty())
    {
        std::cout << "\n姓名不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    std::string phone = getInput("请输入手机号 (11位): ");
    if (phone.length() != 11)
    {
        std::cout << "\n请输入正确的手机号！" << std::endl;
        waitForEnter();
        return;
    }

    if (system.memberManager.findMemberByPhone(phone))
    {
        std::cout << "\n该手机号已被注册！" << std::endl;
        waitForEnter();
        return;
    }

    std::string password = getInput("请输入密码: ");
    if (password.empty())
    {
        std::cout << "\n密码不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    std::string confirmPassword = getInput("请确认密码: ");
    if (password != confirmPassword)
    {
        std::cout << "\n两次输入的密码不一致！" << std::endl;
        waitForEnter();
        return;
    }

    Member *newMember = new Member(id, name, phone, password, MemberType::NORMAL);
    if (system.memberManager.addMember(newMember))
    {
        std::cout << "\n注册成功！" << std::endl;
        std::cout << "您的账号信息如下：" << std::endl;
        std::cout << "用户名: " << id << std::endl;
        std::cout << "姓名: " << name << std::endl;
        std::cout << "手机: " << phone << std::endl;
        std::cout << "\n请记住您的账号和密码。" << std::endl;
    }
    else
    {
        std::cout << "\n注册失败，请稍后重试。" << std::endl;
        delete newMember;
    }
    waitForEnter();
}

/**
 * @brief 启动UI系统
 */
void UI::start()
{
    handleMainMenu();
}

/**
 * @brief 显示管理员菜单
 */
void UI::displayAdminMenu() const
{
    drawTitle("管理员菜单");
    std::cout << "\n1. 图书管理"
              << "\n2. 用户管理"
              << "\n3. 临期书籍查看"
              << "\n4. 退出系统"
              << std::endl;
    drawLine('-');
}

/**
 * @brief 处理管理员菜单逻辑
 */
void UI::handleAdminMenu()
{
    while (true)
    {
        displayAdminMenu();
        int choice = getChoice(1, 4);

        switch (choice)
        {
        case 1:
            handleBookManagement();
            break;
        case 2:
            handleUserManagement();
            break;
        case 3:
            viewOverdueBooks();
            break;
        case 4:
            system.logout();
            return;
        }
    }
}

/**
 * @brief 显示图书管理菜单
 */
void UI::displayBookManagementMenu() const
{
    drawTitle("图书管理");
    std::cout << "\n1. 添加图书"
              << "\n2. 修改图书"
              << "\n3. 下架图书"
              << "\n4. 返回上级"
              << std::endl;
    drawLine('-');
}

/**
 * @brief 处理图书管理菜单逻辑
 */
void UI::handleBookManagement()
{
    while (true)
    {
        displayBookManagementMenu();
        int choice = getChoice(1, 4);

        switch (choice)
        {
        case 1:
            addBook();
            break;
        case 2:
            modifyBook();
            break;
        case 3:
            removeBook();
            break;
        case 4:
            return;
        }
    }
}

/**
 * @brief 添加新图书
 */
void UI::addBook()
{
    drawTitle("添加新书");

    std::string id = getInput("图书编号: ");
    if (system.findBook(id))
    {
        std::cout << "\n该编号已存在！" << std::endl;
        waitForEnter();
        return;
    }

    std::string title = getInput("书名: ");
    if (title.empty())
    {
        std::cout << "\n书名不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    std::string author = getInput("作者: ");
    if (author.empty())
    {
        std::cout << "\n作者不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    std::string library = getInput("馆藏位置: ");
    if (library.empty())
    {
        std::cout << "\n馆藏位置不能为空！" << std::endl;
        waitForEnter();
        return;
    }

    // 选择图书类别
    std::cout << "\n图书类别：" << std::endl;
    std::cout << "1. 文学\n2. 科学\n3. 技术\n4. 历史"
              << "\n5. 哲学\n6. 艺术\n7. 经济\n8. 其他" << std::endl;
    int categoryChoice = getChoice(1, 8);
    BookCategory category = static_cast<BookCategory>(categoryChoice);

    std::string description = getInput("图书简介(可选): ");

    int stock;
    while (true)
    {
        std::cout << "库存数量: ";
        if (std::cin >> stock && stock > 0)
        {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            break;
        }
        std::cout << "请输入有效的库存数量！" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    Book *newBook = new Book(id, title, author, library, category, description, stock);
    if (system.bookManager.addBook(newBook))
    {
        std::cout << "\n添加成功！" << std::endl;
        system.bookManager.saveToFile(); // 立即保存到文件
    }
    else
    {
        std::cout << "\n添加失败。" << std::endl;
        delete newBook;
    }
    waitForEnter();
}

/**
 * @brief 修改图书信息
 */
void UI::modifyBook()
{
    drawTitle("修改图书");

    std::string id = getInput("请输入要修改的图书编号: ");
    Book *book = system.findBook(id);
    if (!book)
    {
        std::cout << "\n未找到该图书。" << std::endl;
        waitForEnter();
        return;
    }

    std::cout << "\n当前信息：" << std::endl;
    std::cout << "书名: " << book->getTitle() << std::endl;
    std::cout << "作者: " << book->getAuthor() << std::endl;
    std::cout << "馆藏: " << book->getLibrary() << std::endl;
    std::cout << "库存: " << book->getCurrentStock() << "/" << book->getTotalStock() << std::endl;

    std::cout << "\n请输入新信息(直接回车保持不变)：" << std::endl;
    std::string title = getInput("新书名: ");
    std::string author = getInput("新作者: ");
    std::string library = getInput("新馆藏位置: ");
    std::string stockStr = getInput("新库存数量: ");

    if (!title.empty())
        book->updateInfo(title, book->getAuthor(), book->getLibrary(), book->getDescription());
    if (!author.empty())
        book->updateInfo(book->getTitle(), author, book->getLibrary(), book->getDescription());
    if (!library.empty())
        book->updateInfo(book->getTitle(), book->getAuthor(), library, book->getDescription());
    if (!stockStr.empty())
        book->updateStock(std::stoi(stockStr));

    system.bookManager.saveToFile(); // 立即保存到文件
    std::cout << "\n修改成功！" << std::endl;
    waitForEnter();
}

/**
 * @brief 下架图书
 */
void UI::removeBook()
{
    drawTitle("下架图书");
    std::string bookId = getInput("请输入要下架的图书ID: ");
    Book *book = system.findBook(bookId);

    if (!book)
    {
        std::cout << "\n未找到该图书。" << std::endl;
        waitForEnter();
        return;
    }

    // 显示图书信息并确认
    std::cout << "\n图书信息：" << std::endl;
    std::cout << "ID: " << book->getBookId() << std::endl;
    std::cout << "书名: " << book->getTitle() << std::endl;
    std::cout << "作者: " << book->getAuthor() << std::endl;
    std::cout << "馆藏地: " << book->getLibrary() << std::endl;
    std::cout << "库存: " << book->getCurrentStock() << "/" << book->getTotalStock() << std::endl;

    std::string confirm = getInput("\n确认要下架该图书吗？(y/n): ");
    if (confirm == "y" || confirm == "Y")
    {
        // 读取所有行并重写文件，跳过要删除的图书
        std::ifstream inFile("../data/books.csv");
        std::ofstream tempFile("../data/books_temp.csv");

        if (!inFile || !tempFile)
        {
            std::cout << "\n文件操作失败。" << std::endl;
            waitForEnter();
            return;
        }

        std::string line;
        bool found = false;
        while (std::getline(inFile, line))
        {
            // 检查行是否以图书ID开头
            if (line.find(bookId + ",") == 0)
            {
                found = true;
                continue; // 跳过这一行
            }
            tempFile << line << "\n";
        }

        inFile.close();
        tempFile.close();

        if (!found)
        {
            std::cout << "\n在文件中未找到该图书。" << std::endl;
            std::remove("../data/books_temp.csv");
            waitForEnter();
            return;
        }

        // 替换原文件
        if (std::remove("../data/books.csv") != 0 ||
            std::rename("../data/books_temp.csv", "../data/books.csv") != 0)
        {
            std::cout << "\n文件更新失败。" << std::endl;
            waitForEnter();
            return;
        }

        // 重新加载图书数据
        if (system.bookManager.loadFromFile())
        {
            std::cout << "\n图书下架成功！" << std::endl;
        }
        else
        {
            std::cout << "\n图书下架成功，但重新加载数据失败。" << std::endl;
        }
    }
    waitForEnter();
}

/**
 * @brief 查看所有用户信息
 */
void UI::viewAllUsers() const
{
    drawTitle("用户列表");

    std::cout << std::setw(10) << "ID"
              << std::setw(20) << "姓名"
              << std::setw(15) << "手机号"
              << std::setw(10) << "类型"
              << std::setw(10) << "等级"
              << std::setw(10) << "信用分" << std::endl;
    drawLine('-');

    const auto &members = system.memberManager.getMembers();
    for (int i = 1; i <= members.length(); i++)
    {
        Member *member = reinterpret_cast<Member *>(members.getPointer(i)->data);
        std::cout << std::setw(10) << member->getId()
                  << std::setw(20) << member->getName()
                  << std::setw(15) << member->getPhone()
                  << std::setw(10) << (member->getType() == MemberType::ADMIN ? "管理员" : "普通用户")
                  << std::setw(10) << static_cast<int>(member->getLevel())
                  << std::setw(10) << member->getCreditScore() << std::endl;
    }
    waitForEnter();
}

/**
 * @brief 查看临期图书
 */
void UI::viewOverdueBooks() const
{
    drawTitle("临期书籍查看");

    std::cout << std::setw(10) << "用户ID"
              << std::setw(30) << "书名"
              << std::setw(15) << "借阅日期"
              << std::setw(15) << "应还日期"
              << std::setw(10) << "超期天数" << std::endl;
    drawLine('-');

    const auto &members = system.memberManager.getMembers();
    for (int i = 1; i <= members.length(); i++)
    {
        Member *member = reinterpret_cast<Member *>(members.getPointer(i)->data);
        const auto &records = member->getBorrowRecords();

        for (const auto &record : records)
        {
            if (!record.returnDate) // 未归还的图书
            {
                time_t now = std::time(nullptr);
                int daysLeft = (record.dueDate - now) / (24 * 3600);
                if (daysLeft <= 7) // 显示7天内到期的图书
                {
                    Book *book = system.findBook(record.bookId);
                    if (book)
                    {
                        std::cout << std::setw(10) << member->getId()
                                  << std::setw(30) << book->getTitle()
                                  << std::setw(15) << std::ctime(&record.borrowDate)
                                  << std::setw(15) << std::ctime(&record.dueDate)
                                  << std::setw(10) << (daysLeft < 0 ? -daysLeft : 0) << std::endl;
                    }
                }
            }
        }
    }
    waitForEnter();
}

/**
 * @brief 显示用户菜单
 */
void UI::displayUserMenu() const
{
    drawTitle("用户菜单");
    std::cout << "\n1. 搜索图书"
              << "\n2. 借阅图书"
              << "\n3. 归还图书"
              << "\n4. 借阅历史"
              << "\n5. 图书排行"
              << "\n6. 图书推荐"
              << "\n7. 退出系统"
              << std::endl;
    drawLine('-');
}

/**
 * @brief 处理用户菜单逻辑
 */
void UI::handleUserMenu()
{
    while (true)
    {
        displayUserMenu();
        int choice = getChoice(1, 7);

        switch (choice)
        {
        case 1:
            searchBooks();
            break;
        case 2:
            borrowBook();
            break;
        case 3:
            returnBook();
            break;
        case 4:
            viewBorrowHistory();
            break;
        case 5:
            handleBookRanking();
            break;
        case 6:
            showRecommendedBooks();
            break;
        case 7:
            system.logout();
            return;
        }
    }
}

/**
 * @brief 搜索图书
 */
void UI::searchBooks() const
{
    drawTitle("搜索图书");
    std::string keyword = getInput("请输入搜索关键词(书名/作者): ");
    LinkList results = system.bookManager.searchBooks(keyword);
    displaySearchResults(results);
}

/**
 * @brief 显示搜索结果
 * @param books 搜索结果图书链表
 */
void UI::displaySearchResults(const LinkList &books) const
{
    if (books.length() == 0)
    {
        std::cout << "\n未找到相关图书。" << std::endl;
    }
    else
    {
        std::cout << "\n搜索结果：" << std::endl;
        std::cout << std::setw(5) << "序号"
                  << std::setw(10) << "ID"
                  << std::setw(30) << "书名"
                  << std::setw(20) << "作者"
                  << std::setw(15) << "馆藏位置"
                  << std::setw(10) << "库存" << std::endl;
        drawLine('-');

        for (int i = 1; i <= books.length(); i++)
        {
            Book *book = reinterpret_cast<Book *>(books.getPointer(i)->data);
            std::cout << std::setw(5) << i
                      << std::setw(10) << book->getBookId()
                      << std::setw(30) << book->getTitle()
                      << std::setw(20) << book->getAuthor()
                      << std::setw(15) << book->getLibrary()
                      << std::setw(10) << book->getCurrentStock() << std::endl;
        }
    }
    waitForEnter();
}

/**
 * @brief 借阅图书
 */
void UI::borrowBook()
{
    displayAvailableBooks();
    std::string choice = getInput("请输入要借阅的图书ID: ");

    try
    {
        std::string bookId = choice;
        std::cout << " 输入的图书ID = " << bookId << std::endl;
        const auto &books = system.bookManager.getBooks();
        bool found = false;

        for (int i = 1; i <= books.length(); i++)
        {
            Book *book = reinterpret_cast<Book *>(books.getPointer(i)->data);
            std::cout << " 当前比较的图书ID = " << book->getBookId() << std::endl;
            if (book->getBookId() == bookId)
            {
                found = true;
                try
                {
                    if (system.borrowBook(bookId))
                    {
                        std::cout << "\n借阅成功！" << std::endl;
                        time_t dueDate = system.currentUser->getDueDate(bookId);
                        std::cout << "应还日期: " << std::ctime(&dueDate);
                    }
                    else
                    {
                        std::cout << "\n借阅失败。" << std::endl;
                    }
                }
                catch (const std::exception &e)
                {
                    std::cout << " 借阅时发生异常: " << e.what() << std::endl;
                    std::cout << "\n借阅失败。" << std::endl;
                }
                break;
            }
        }

        if (!found)
        {
            std::cout << "\n未找到对应的图书。" << std::endl;
        }
    }
    catch (...)
    {
        std::cout << " 捕获到异常" << std::endl;
        std::cout << "\n无效的图书ID。" << std::endl;
    }

    waitForEnter();
}

/**
 * @brief 归还图书
 */
void UI::returnBook()
{
    drawTitle("归还图书");
    displayBorrowedBooks();
    std::string choice = getInput("\n请输入要归还的图书ID: ");

    try
    {
        std::string bookId = choice;
        std::cout << " 输入的图书ID = " << bookId << std::endl;

        // 直接检查用户的借阅记录
        const auto &records = system.currentUser->getBorrowRecords();
        bool found = false;

        for (const auto &record : records)
        {
            std::cout << " 检查借阅记录 - BookId: " << record.bookId
                      << ", ReturnDate: " << record.returnDate << std::endl;

            if (record.bookId == bookId && record.returnDate == 0)
            {
                found = true;
                if (system.returnBook(bookId))
                {
                    std::cout << "\n归还成功！" << std::endl;
                }
                else
                {
                    std::cout << "\n归还失败。" << std::endl;
                }
                break;
            }
        }

        if (!found)
        {
            std::cout << "\n您没有借阅此书或已归还。" << std::endl;
        }
    }
    catch (...)
    {
        std::cout << "\n无效的图书ID。" << std::endl;
    }

    waitForEnter();
}

/**
 * @brief 显示可借阅的图书
 */
void UI::displayAvailableBooks() const
{
    std::cout << std::setw(5) << "序号"
              << std::setw(10) << "ID"
              << std::setw(30) << "书名"
              << std::setw(20) << "作者"
              << std::setw(15) << "馆藏位置"
              << std::setw(10) << "库存" << std::endl;
    drawLine('-');

    const auto &books = system.bookManager.getBooks();
    int index = 1;
    for (int i = 1; i <= books.length(); i++)
    {
        Book *book = reinterpret_cast<Book *>(books.getPointer(i)->data);
        if (book->isAvailable())
        {
            std::cout << std::setw(5) << index++
                      << std::setw(10) << book->getBookId()
                      << std::setw(30) << book->getTitle()
                      << std::setw(20) << book->getAuthor()
                      << std::setw(15) << book->getLibrary()
                      << std::setw(10) << book->getCurrentStock() << std::endl;
        }
    }
}

/**
 * @brief 显示已借阅的图书
 */
void UI::displayBorrowedBooks() const
{
    const auto &records = system.currentUser->getBorrowRecords();
    if (records.empty())
    {
        std::cout << "\n当前没有借阅的图书。" << std::endl;
        return;
    }

    std::cout << std::setw(5) << "序号"
              << std::setw(30) << "书名"
              << std::setw(15) << "借阅日期"
              << std::setw(15) << "应还日期"
              << std::setw(15) << "剩余天数" << std::endl;
    drawLine('-');

    int index = 1;
    for (const auto &record : records)
    {
        if (record.returnDate != 0)
            continue;

        Book *book = system.findBook(record.bookId);
        if (book)
        {
            time_t now = std::time(nullptr);
            int daysLeft = (record.dueDate - now) / (24 * 3600);
            std::cout << std::setw(5) << index++
                      << std::setw(30) << book->getTitle()
                      << std::setw(15) << std::ctime(&record.borrowDate)
                      << std::setw(15) << std::ctime(&record.dueDate)
                      << std::setw(15) << daysLeft << std::endl;
        }
    }
}

/**
 * @brief 查看借阅历史
 */
void UI::viewBorrowHistory() const
{
    drawTitle("借阅历史");

    const auto &records = system.currentUser->getBorrowRecords();
    if (records.empty())
    {
        std::cout << "\n暂无借阅记录。" << std::endl;
        waitForEnter();
        return;
    }

    std::cout << std::setw(5) << "序号"
              << std::setw(30) << "书名"
              << std::setw(15) << "借阅日期"
              << std::setw(15) << "应还日期"
              << std::setw(15) << "状态" << std::endl;
    drawLine('-');

    int index = 1;
    for (const auto &record : records)
    {
        Book *book = system.findBook(record.bookId);
        if (book)
        {
            time_t now = std::time(nullptr);
            int daysLeft = (record.dueDate - now) / (24 * 3600);
            std::string status;
            if (daysLeft < 0)
                status = "已超期" + std::to_string(-daysLeft) + "天";
            else
                status = "剩余" + std::to_string(daysLeft) + "天";

            std::cout << std::setw(5) << index++
                      << std::setw(30) << book->getTitle()
                      << std::setw(15) << std::ctime(&record.borrowDate)
                      << std::setw(15) << std::ctime(&record.dueDate)
                      << std::setw(15) << status << std::endl;
        }
    }
    waitForEnter();
}

// 图书排行功能
void UI::displayBookRankingMenu() const
{
    drawTitle("图书排行榜");
    std::cout << "\n1. 评分排行"
              << "\n2. 借阅次数排行"
              << "\n3. 返回上级"
              << std::endl;
    drawLine('-');
}

void UI::handleBookRanking()
{
    while (true)
    {
        displayBookRankingMenu();
        int choice = getChoice(1, 3);

        switch (choice)
        {
        case 1:
            showTopRatedBooks();
            break;
        case 2:
            showMostBorrowedBooks();
            break;
        case 3:
            return;
        }
    }
}

void UI::showTopRatedBooks() const
{
    drawTitle("评分排行榜");

    LinkList topBooks = system.getTopRatedBooks(10); // 获取前10名
    if (topBooks.length() == 0)
    {
        std::cout << "\n暂无评分数据。" << std::endl;
        waitForEnter();
        return;
    }

    std::cout << std::setw(5) << "排名"
              << std::setw(30) << "书名"
              << std::setw(20) << "作者"
              << std::setw(15) << "评分"
              << std::setw(10) << "评分人数" << std::endl;
    drawLine('-');

    for (int i = 1; i <= topBooks.length(); i++)
    {
        Book *book = system.findBook(std::to_string(topBooks.getPointer(i)->data));
        if (book)
        {
            std::cout << std::setw(5) << i
                      << std::setw(30) << book->getTitle()
                      << std::setw(20) << book->getAuthor()
                      << std::setw(15) << std::fixed << std::setprecision(1)
                      << book->getAverageRating()
                      << std::setw(10) << book->getRatingCount() << std::endl;
        }
    }
    waitForEnter();
}

void UI::showMostBorrowedBooks() const
{
    drawTitle("借阅次数排行榜");

    LinkList topBooks = system.getMostBorrowedBooks(10); // 获取前10名
    if (topBooks.length() == 0)
    {
        std::cout << "\n暂无借阅数据。" << std::endl;
        waitForEnter();
        return;
    }

    std::cout << std::setw(5) << "排名"
              << std::setw(30) << "书名"
              << std::setw(20) << "作者"
              << std::setw(15) << "借阅次数"
              << std::setw(10) << "当前库存" << std::endl;
    drawLine('-');

    for (int i = 1; i <= topBooks.length(); i++)
    {
        Book *book = system.findBook(std::to_string(topBooks.getPointer(i)->data));
        if (book)
        {
            std::cout << std::setw(5) << i
                      << std::setw(30) << book->getTitle()
                      << std::setw(20) << book->getAuthor()
                      << std::setw(15) << book->getBorrowCount()
                      << std::setw(10) << book->getCurrentStock() << "/"
                      << book->getTotalStock() << std::endl;
        }
    }
    waitForEnter();
}

// 图书推荐功能
void UI::showRecommendedBooks() const
{
    drawTitle("个性化图书推荐");

    // 如果用户没有借阅历史，显示热门图书
    if (system.currentUser->getBorrowRecords().empty())
    {
        std::cout << "\n暂无借阅历史，为您推荐热门图书：" << std::endl;
        showMostBorrowedBooks();
        return;
    }

    // 获取用户最喜欢的图书类别
    BookCategory favoriteCategory = static_cast<BookCategory>(1); // 默认为文学类
    double maxWeight = 0;
    for (int i = 1; i <= 8; i++)
    {
        double weight = system.currentUser->getCategoryWeight(static_cast<BookCategory>(i));
        if (weight > maxWeight)
        {
            maxWeight = weight;
            favoriteCategory = static_cast<BookCategory>(i);
        }
    }

    std::cout << "\n根据您的阅读偏好，为您推荐以下图书：" << std::endl;
    drawLine('-');

    std::cout << std::setw(5) << "序号"
              << std::setw(30) << "书名"
              << std::setw(20) << "作者"
              << std::setw(15) << "类别"
              << std::setw(10) << "评分" << std::endl;
    drawLine('-');

    // 遍历所有图书，找出符合用户偏好的图书
    const auto &books = system.bookManager.getBooks();
    int count = 0;
    for (int i = 1; i <= books.length() && count < 10; i++)
    {
        Book *book = reinterpret_cast<Book *>(books.getPointer(i)->data);
        if (book->getCategory() == favoriteCategory && !system.currentUser->hasBorrowed(book->getBookId()))
        {
            count++;
            std::cout << std::setw(5) << count
                      << std::setw(30) << book->getTitle()
                      << std::setw(20) << book->getAuthor()
                      << std::setw(15) << getCategoryName(book->getCategory())
                      << std::setw(10) << std::fixed << std::setprecision(1)
                      << book->getAverageRating() << std::endl;
        }
    }

    if (count == 0)
    {
        std::cout << "\n暂无符合您阅读偏好的推荐图书。" << std::endl;
    }
    waitForEnter();
}

std::string UI::getCategoryName(BookCategory category) const
{
    switch (category)
    {
    case BookCategory::LITERATURE:
        return "文学";
    case BookCategory::SCIENCE:
        return "科学";
    case BookCategory::TECHNOLOGY:
        return "技术";
    case BookCategory::HISTORY:
        return "历史";
    case BookCategory::PHILOSOPHY:
        return "哲学";
    case BookCategory::ART:
        return "艺术";
    case BookCategory::ECONOMICS:
        return "经济";
    default:
        return "其他";
    }
}

void UI::displayUserManagementMenu() const
{
    drawTitle("用户管理");
    std::cout << "\n1. 查询账户信息"
              << "\n2. 修改用户信息"
              << "\n3. 删除账户"
              << "\n4. 返回上级菜单"
              << std::endl;
    drawLine('-');
}

void UI::handleUserManagement()
{
    while (true)
    {
        displayUserManagementMenu();
        int choice = getChoice(1, 4);

        switch (choice)
        {
        case 1:
            queryUserInfo();
            break;
        case 2:
            modifyUserInfo();
            break;
        case 3:
            deleteUser();
            break;
        case 4:
            return;
        }
    }
}

void UI::queryUserInfo()
{
    drawTitle("查询账户信息");
    std::string userId = getInput("请输入要查询的用户ID: ");
    Member *member = system.memberManager.findMember(userId);

    if (member)
    {
        std::cout << "\n用户信息：" << std::endl;
        std::cout << "ID: " << member->getId() << std::endl;
        std::cout << "姓名: " << member->getName() << std::endl;
        std::cout << "手机号: " << member->getPhone() << std::endl;
        std::cout << "用户类型: " << (member->getType() == MemberType::ADMIN ? "管理员" : "普通用户") << std::endl;
        std::cout << "会员等级: " << static_cast<int>(member->getLevel()) << std::endl;
        std::cout << "信用分数: " << member->getCreditScore() << std::endl;

        // 显示借阅信息
        const auto &records = member->getBorrowRecords();
        if (!records.empty())
        {
            std::cout << "\n借阅记录：" << std::endl;
            std::cout << std::setw(30) << "书名"
                      << std::setw(15) << "借阅日期"
                      << std::setw(15) << "应还日期"
                      << std::setw(15) << "状态" << std::endl;
            drawLine('-');

            for (const auto &record : records)
            {
                Book *book = system.findBook(record.bookId);
                if (book)
                {
                    std::cout << std::setw(30) << book->getTitle()
                              << std::setw(15) << std::ctime(&record.borrowDate)
                              << std::setw(15) << std::ctime(&record.dueDate)
                              << std::setw(15) << (record.returnDate ? "已归还" : "借阅中") << std::endl;
                }
            }
        }
        else
        {
            std::cout << "\n暂无借阅记录。" << std::endl;
        }
    }
    else
    {
        std::cout << "\n未找到该用户。" << std::endl;
    }
    waitForEnter();
}

void UI::modifyUserInfo()
{
    drawTitle("修改用户信息");
    std::string userId = getInput("请输入要修改的用户ID: ");
    Member *member = system.memberManager.findMember(userId);

    if (member)
    {
        if (member->getType() == MemberType::ADMIN)
        {
            std::cout << "\n不能修改管理员信息。" << std::endl;
            waitForEnter();
            return;
        }

        std::cout << "\n当前用户信息：" << std::endl;
        std::cout << "姓名: " << member->getName() << std::endl;
        std::cout << "手机号: " << member->getPhone() << std::endl;

        std::string newName = getInput("\n请输入新用户名（直接回车保持不变）: ");
        std::string newPhone = getInput("请输入新手机号（直接回车保持不变）: ");
        std::string newPassword = getInput("请输入新密码（直接回车保持不变）: ");

        if (system.updateUserInfo(userId,
                                  newName.empty() ? member->getName() : newName,
                                  newPhone.empty() ? member->getPhone() : newPhone,
                                  newPassword))
        {
            std::cout << "\n用户信息修改成功！" << std::endl;
            system.memberManager.saveToFile();
        }
        else
        {
            std::cout << "\n用户信息修改失败。" << std::endl;
        }
    }
    else
    {
        std::cout << "\n未找到该用户。" << std::endl;
    }
    waitForEnter();
}

void UI::deleteUser()
{
    drawTitle("删除账户");
    std::string userId = getInput("请输入要删除的用户ID: ");
    Member *member = system.memberManager.findMember(userId);

    if (member)
    {
        if (member->getType() == MemberType::ADMIN)
        {
            std::cout << "\n不能删除管理员账户。" << std::endl;
            waitForEnter();
            return;
        }

        std::cout << "\n确认要删除以下用户吗？" << std::endl;
        std::cout << "ID: " << member->getId() << std::endl;
        std::cout << "姓名: " << member->getName() << std::endl;
        std::cout << "手机号: " << member->getPhone() << std::endl;

        std::string confirm = getInput("\n确认删除？(y/n): ");
        if (confirm == "y" || confirm == "Y")
        {
            if (system.removeMember(userId))
            {
                std::cout << "\n用户删除成功！" << std::endl;
                system.memberManager.saveToFile();
            }
            else
            {
                std::cout << "\n用户删除失败。" << std::endl;
            }
        }
    }
    else
    {
        std::cout << "\n未找到该用户。" << std::endl;
    }
    waitForEnter();
}