const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// MySQL数据库连接配置
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456', // 替换为你的MySQL密码
    database: 'librarysystem'
});
let currentAdmin = null;
db.connect(err => {
    if (err) {
        throw err;
    }
    console.log('MySQL connected...');
});

// 登录路由
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
    db.query(query, [username, password], (err, results) => {
        if (err) {
            res.status(500).json({ error: 'Server error' });
        } else if (results.length > 0) {
            currentAdmin = results[0]; // 保存当前登录的管理员
            res.json(currentAdmin);
        } else {
            res.status(400).json({ error: 'Invalid login' });
        }
    });
});
// 获取当前管理员信息
app.get('/admin/current', (req, res) => {
    if (currentAdmin) {
        res.json({ username: currentAdmin.username }); // 返回当前管理员的用户名
    } else {
        res.status(401).json({ error: 'No admin logged in' }); // 如果没有管理员登录，则返回错误
    }
});
// 注册路由
app.post('/register', (req, res) => {
    const { username, password } = req.body;
    // 检查用户名是否已存在
    const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
    db.query(checkUserQuery, [username], (err, results) => {
        if (err) {
            res.status(500).json({ error: 'Server error' });
        } else if (results.length > 0) {
            // 用户名已存在
            res.status(400).json({ error: 'Username already exists' });
        } else {
            // 用户名不存在，可以注册
            const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
            db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
                if (err) {
                    res.status(500).json({ error: 'Failed to register user' });
                } else {
                    res.status(201).send('User registered successfully');
                }
            });
        }
    });
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
    const { title, author, year_published } = req.body;

    // 在添加之前，先检查书名是否已存在
    const checkBookQuery = 'SELECT * FROM books WHERE title = ?';
    db.query(checkBookQuery, [title], (err, results) => {
        if (err) {
            console.error('Error checking existing book:', err);
            return res.status(500).json({ error: 'Failed to check existing book' });
        }

        if (results.length > 0) {
            return res.status(400).json({ error: 'Book title already exists' }); // 如果书名已存在，则返回错误
        }

        // 如果书名不存在，则继续插入新书
        const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
        db.query(query, [title, author, year_published], (err, results) => {
            if (err) {
                console.error('Error adding book:', err);
                return res.status(500).json({ error: 'Failed to add book' });
            }
            res.status(200).send('Book added successfully');
        });
    });
});
// 删除图书按ID
app.post('/admin/delete-book', (req, res) => {
    const { id } = req.body;

    // 确保 ID 是有效的数字
    if (!id || isNaN(id)) {
        res.status(400).json({ error: 'Invalid book ID format' });
        return;
    }

    const query = 'DELETE FROM books WHERE id = ?';
    db.query(query, [id], (err, results) => {
        if (err) {
            console.error('Error deleting book:', err);
            res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
        } else {
            // 检查是否有行被删除
            if (results.affectedRows > 0) {
                res.send('Book deleted');
            } else {
                res.status(404).send('No book found with this ID');
            }
        }
    });
});

// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
    const { keyword } = req.body;
    const query = `
        SELECT * FROM books 
        WHERE id = ? OR title LIKE ? OR author LIKE ?
    `;
    db.query(query, [keyword, `%${keyword}%`, `%${keyword}%`], (err, results) => {
        if (err) {
            res.status(500).send('Server error');
        } else {
            res.json(results);
        }
    });
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
    const { userId } = req.params;
    const query = `
        SELECT b.id, b.title, b.author 
        FROM favorites f 
        JOIN books b ON f.book_id = b.id 
        WHERE f.user_id = ?
    `;
    db.query(query, [userId], (err, results) => {
        if (err) {
            res.status(500).send('Server error');
        } else {
            res.json(results);
        }
    });
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
    const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;

    // 验证每个字段
    if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
        return res.status(400).json({ error: '所有字段都需要填写' });
    }

    const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
    db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
        if (err) {
            console.error('Error editing book:', err);
            return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
        }
        // 检查是否有行被更新
        if (results.affectedRows > 0) {
            res.status(200).send('Book edited successfully');
        } else {
            res.status(404).send('No book found with that title for editing');
        }
    });
});
app.post('/admin/edit-book', (req, res) => {
    const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;

    // 验证每个字段
    if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
        return res.status(400).json({ error: '所有字段都需要填写' });
    }

    const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
    db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
        if (err) {
            console.error('Error editing book:', err);
            return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
        }
        // 检查是否有行被更新
        if (results.affectedRows > 0) {
            res.status(200).send('Book edited successfully');
        } else {
            res.status(404).send('No book found with that title for editing');
        }
    });
});

app.get('/admin/get-books', (req, res) => {
    const query = 'SELECT * FROM books';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error getting books:', err);
            res.status(500).json({ error: 'Failed to get books' });
        } else {
            res.json(results);
        }
    });
});

// 获取所有用户
app.get('/admin/get-users', (req, res) => {
    const query = 'SELECT * FROM users';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error getting users:', err);
            res.status(500).json({ error: 'Failed to get users' });
        } else {
            res.json(results);
        }
    });
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
    const { userId, bookId } = req.body;
    const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
    db.query(query, [userId, bookId], (err, results) => {
        if (err) {
            console.error('Error borrowing book:', err);
            res.status(500).json({ error: 'Failed to borrow book' });
        } else {
            res.status(200).send('Book borrowed successfully');
        }
    });
});

// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
    const { userId } = req.params;
    const query = `
        SELECT b.title, b.author, br.borrow_date 
        FROM borrow_records br 
        JOIN books b ON br.book_id = b.id 
        WHERE br.user_id = ?
        ORDER BY br.borrow_date DESC
    `;
    db.query(query, [userId], (err, results) => {
        if (err) {
            res.status(500).send('Server error');
        } else {
            res.json(results);
        }
    });
});

// 获取所有借阅记录（管理员用）
// 获取所有借阅记录（管理员用）
app.get('/admin/borrow-records', (req, res) => {
    const query = `
        SELECT br.id, u.username, b.title, b.author, br.borrow_date 
        FROM borrow_records br 
        JOIN users u ON br.user_id = u.id 
        JOIN books b ON br.book_id = b.id 
        ORDER BY br.borrow_date DESC
    `;
    db.query(query, (err, results) => {
        if (err) {
            res.status(500).send('Server error');
        } else {
            // Ensure that the ID is included in results
            res.json(results);
        }
    });
});

// 编辑用户
app.post('/admin/edit-user', (req, res) => {
    const { id, username, oldPassword, newPassword, role } = req.body;
 
    // 验证旧密码
    const query = 'SELECT * FROM users WHERE id = ?';
    db.query(query, [id], (err, user) => {
        if (err) {
            console.error('Error fetching user data for password verification:', err);
            return res.status(500).json({ error: 'Failed to verify password' });
        }
        if (!user || user.length === 0 || user[0].password !== oldPassword) {
            // 旧密码不正确
            return res.status(400).json({ error: 'Invalid old password' });
        }
 
        // 更新用户信息
        const updateQuery = 'UPDATE users SET username = ?, password = ?, role = ? WHERE id = ?';
        db.query(updateQuery, [username, newPassword, role, id], (err, results) => {
            if (err) {
                console.error('编辑用户信息出错，编辑的用户ID：', id);
                console.error('错误信息：', err.message);
                console.error('错误堆栈：', err.stack);
                return res.status(500).json({ error: 'Failed to edit user' });
            }
            console.log('用户信息编辑成功，编辑的用户ID：', id);
            res.status(200).send('User edited successfully');
        });
    });
});

// 删除图书
app.post('/admin/delete-book-by-title', (req, res) => {
    const { title } = req.body; // 获取书名

    // 确保书名是有效的字符串
    if (!title || typeof title !== 'string') {
        return res.status(400).json({ error: 'Invalid book title format' });
    }

    // SQL 查询使用书名删除图书
    const query = 'DELETE FROM books WHERE title = ?';
    db.query(query, [title], (err, results) => {
        if (err) {
            console.error('Error deleting book:', err);
            return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
        } else {
            if (results.affectedRows > 0) {
                res.send('Book deleted');
            } else {
                res.status(404).send('No book found with that title');
            }
        }
    });
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
    const { id } = req.body;
    db.beginTransaction((err => {
        if (err) {
            console.error('Error starting transaction:', err);
            res.status(500).send('Server error starting transaction');
            return;
        }
        // 先删除 borrow_records 表中与该用户相关的记录
        const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
        db.query(deleteBorrowRecordsQuery, [id], (err => {
            if (err) {
                db.rollback(() => {
                    console.error('Error deleting related borrow records, rolling back transaction:', err);
                    res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
                });
                return;
            }
            // 再删除 favorites 表中与该用户相关的记录
            const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
            db.query(deleteFavoritesQuery, [id], (err => {
                if (err) {
                    db.rollback(() => {
                        console.error('Error deleting related favorites, rolling back transaction:', err);
                        res.status(500).send('Server error when deleting related favorites, transaction rolled back');
                    });
                    return;
                }
                // 最后执行删除用户操作
                const query = 'DELETE FROM users WHERE id =?';
                db.query(query, [id], (err, results) => {
                    if (err) {
                        db.rollback(() => {
                            console.error('删除用户出错，要删除的用户ID：', id);
                            console.error('错误信息：', err.message);
                            console.error('错误堆栈：', err.stack);
                            res.status(500).send('Server error, transaction rolled back');
                        });
                    } else {
                        db.commit((err => {
                            if (err) {
                                console.error('Error committing transaction:', err);
                                res.status(500).send('Server error committing transaction');
                                return;
                            }
                            console.log('用户删除成功，删除的用户ID：', id);
                            res.send('User deleted');
                        }));
                    }
                });
            }));
        }));
    }));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
    const { id } = req.params;
    const query = 'SELECT * FROM users WHERE id = ?';
    db.query(query, [id], (err, results) => {
        if (err) {
            console.error('Error getting user:', err);
            res.status(500).json({ error: 'Failed to get user' });
        } else if (results.length === 0) {
            res.status(404).json({ error: 'User not found' });
        } else {
            res.json(results[0]);
        }
    });
});
// 编辑借阅记录（注意：通常借阅记录不需要编辑，但这里为了完整性提供示例）
app.post('/admin/edit-borrow-record', (req, res) => {
    const { id, user_id, book_id, borrow_date } = req.body;
    const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
    db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
        if (err) {
            console.error('Error editing borrow record:', err);
            res.status(500).json({ error: 'Failed to edit borrow record' });
        } else {
            res.status(200).send('Borrow record edited successfully');
        }
    });
});

// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
    const { id } = req.body;

    if (!id || isNaN(id)) {
        return res.status(400).send('无效的借阅记录ID格式');
    }

    const query = 'DELETE FROM borrow_records WHERE id = ?';
    db.query(query, [id], (err, results) => {
        if (err) {
            console.error('Error deleting borrow record:', err);
            return res.status(500).send('服务器错误');
        }
        if (results.affectedRows > 0) {
            res.send('借阅记录删除成功');
        } else {
            res.status(404).send('没有找到该借阅记录');
        }
    });
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
    const { id } = req.params;
    // 验证id是否为有效的数字且大于0
    if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
        res.status(400).json({ error: 'Invalid borrow record ID format or value' });
        return;
    }
    const query = `
        SELECT * 
        FROM borrow_records 
        WHERE id =?
    `;
    db.query(query, [id], (err, results) => {
        if (err) {
            console.error('Error getting borrow record:', err);
            res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
        } else if (results.length === 0) {
            res.status(404).json({ error: 'Borrow record not found' });
        } else {
            res.json(results[0]);
        }
    });
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
    const { userId, bookId } = req.body;
    // 先检查该用户是否已经收藏了这本书
    const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
    db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
        if (err) {
            res.status(500).json({ error: 'Server error' });
        } else if (results.length > 0) {
            // 已收藏，提示用户
            res.status(400).json({ error: 'This book has already been added to favorites' });
        } else {
            // 可以添加收藏，插入记录到 favorites 表
            const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
            db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
                if (err) {
                    res.status(500).json({ error: 'Failed to add to favorites' });
                } else {
                    // 返回成功的 JSON 响应
                    res.status(200).json({ message: 'Book added to favorites successfully' });
                }
            });
        }
    });
});

// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
    const { userId, bookId } = req.body;
    const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
    db.query(deleteQuery, [userId, bookId], (err, results) => {
        if (err) {
            res.status(500).json({ error: 'Server error when deleting favorite' });
        } else if (results.affectedRows === 0) {
            // 如果受影响的行数为0，表示没有找到对应的收藏记录，即可能已经不存在该收藏了
            res.status(400).json({ error: 'This book is not in your favorites' });
        } else {
            res.status(200).json({ message: 'Book removed from favorites successfully' });
        }
    });
});

// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
    const { userId, bookId } = req.body;
    // 先从收藏中删除这本书
    const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
    db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
        if (err) {
            console.error('Error deleting favorite before borrowing:', err);
            res.status(500).json({ error: 'Failed to borrow book from favorites' });
            return;
        }
        if (deleteResults.affectedRows === 0) {
            res.status(400).json({ error: 'This book is not in your favorites' });
            return;
        }

        // 然后借阅这本书
        const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
        db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
            if (err) {
                console.error('Error borrowing book:', err);
                res.status(500).json({ error: 'Failed to borrow book' });
            } else {
                // 返回成功的 JSON 响应
                res.status(200).json({ message: 'Book borrowed from favorites successfully' });
            }
        });
    });
});
 

// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});               <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" width="device-width, initial-scale=1.0">
    <title>用户页面</title>
    <link href="./css/user.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div class="topbar">
        <div>用户：未登录</div>
        <button onclick="logout()">退出</button>
    </div>
    <div class="sidebar">
        <h1>用户菜单</h1>
        <button onclick="showSection('search')">搜索书籍</button>
        <button onclick="showSection('history')">借阅历史</button>
        <button onclick="showSection('favorites')">我的收藏</button>
    </div>
    <div class="main-content">
        <div class="section" id="searchSection">
            <div class="form-container">
                <h1>搜索书籍</h1>
                <input type="text" id="searchInput" placeholder="搜索书名或作者">
                <button onclick="searchBooks()">查询</button>
            </div>
            <ul id="searchResults"></ul>
        </div>
        <div class="section" id="historySection" style="display:none;">
            <h1>借阅历史</h1>
            <ul class="book-list" id="borrowHistory"></ul>
        </div>
        <div class="section" id="favoritesSection" style="display:none;">
            <h1>我的收藏</h1>
            <ul class="book-list" id="favoritesList"></ul>
        </div>
    </div>

    <script>
        // 页面加载时显示用户名
        document.addEventListener("DOMContentLoaded", function () {
            const username = localStorage.getItem('username');
            if (username) {
                document.querySelector('.topbar div').textContent = `用户：${username}`;
            } else {
                document.querySelector('.topbar div').textContent = '用户：未登录';
            }
        });

        function logout() {
            alert('已退出登录');
            localStorage.removeItem('userInfo'); // 清除用户信息
            localStorage.removeItem('username'); // 清除存储的用户名
            window.location.href = 'login.html'; // 重定向到登录页面
        }

        // 用户登录
        function handleLogin() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            fetch('http://localhost:3000/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password }),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Login failed');
                }
                return response.json();
            })
            .then(data => {
                localStorage.setItem('userInfo', JSON.stringify(data)); // 保存用户信息
                localStorage.setItem('username', data.username); // 保存用户名
                window.location.href = 'user.html'; // 重定向到用户页面
            })
            .catch(error => {
                console.error('Error:', error);
                alert('登录失败，请检查您的用户名和密码');
            });
        }

        function showSection(section) {
            const sections = document.querySelectorAll('.section');
            sections.forEach(s => s.style.display = 'none');
            document.getElementById(section + 'Section').style.display = 'block';

            if (section === 'favorites') {
                loadFavorites(); // 加载收藏书籍
            } else if (section === 'history') {
                loadBorrowHistory(); // 加载借阅历史
            }
        }

        function searchBooks() {
            const keyword = document.getElementById('searchInput').value;
            if (keyword.trim() === '') {
                alert('请输入搜索关键词');
                return;
            }

            fetch('http://localhost:3000/user/search-books', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: keyword })
            })
                .then(response => response.json())
                .then(data => {
                    // 处理搜索结果，更新页面
                    console.log(data);
                    displaySearchResults(data);
                })
                .catch(error => console.error('Error:', error));
        }

        function displaySearchResults(books) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = '';
            if (books.length === 0) {
                searchResults.innerHTML = '<p>没有找到相关书籍</p>';
            } else {
                books.forEach(book => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `书名: ${book.title} - 作者: ${book.author} - 出版年份: ${book.year_published}`;

                    // 创建借阅按钮
                    const borrowButton = document.createElement('button');
                    borrowButton.textContent = '借阅';
                    borrowButton.onclick = function () {
                        borrowBook(book.id);
                    };

                    // 创建添加到收藏按钮
                    const favoriteButton = document.createElement('button');
                    favoriteButton.textContent = '添加到收藏';
                    favoriteButton.onclick = function () {
                        addToFavorites(book.id);
                    };

                    // 将按钮添加到列表项
                    listItem.appendChild(borrowButton);
                    listItem.appendChild(favoriteButton);
                    searchResults.appendChild(listItem);
                });
            }
        }

        function getUserId() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            return userInfo ? userInfo.id : null;
        }

        // 借阅书籍
        function borrowBook(bookId) {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            fetch('http://localhost:3000/user/borrow-book', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId, bookId: bookId })
            })
                .then(response => response.text())
                .then(data => {
                    alert('您已成功借阅');
                    loadBorrowHistory();
                })
                .catch(error => console.error('Error:', error));
        }

        // 加载借阅历史
        function loadBorrowHistory() {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            fetch(`http://localhost:3000/user/borrow-history/${userId}`)
                .then(response => response.json())
                .then(data => {
                    displayBorrowHistory(data);
                })
                .catch(error => console.error('Error:', error));
        }

        // 显示借阅历史
        function displayBorrowHistory(borrowRecords) {
            const borrowHistory = document.getElementById('borrowHistory');
            borrowHistory.innerHTML = '';
            if (borrowRecords.length === 0) {
                borrowHistory.innerHTML = '<p>没有借阅记录</p>';
            } else {
                borrowRecords.forEach(record => {
                    const listItem = document.createElement('li');
                    const borrowDate = new Date(record.borrow_date);
                    const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    });
                    listItem.textContent = `书名: ${record.title} - 作者: ${record.author} - 借阅日期: ${formattedDate}`;
                    borrowHistory.appendChild(listItem);
                });
            }
        }

        // 添加到收藏
        function addToFavorites(bookId) {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }
            fetch('http://localhost:3000/user/add-favorite', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId, bookId: bookId })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        alert(data.message);
                        loadFavorites();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('添加收藏时发生错误，请稍后再试');
                });
        }

        // 加载收藏书籍
        function loadFavorites() {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            fetch(`http://localhost:3000/user/favorites/${userId}`)
                .then(response => response.json())
                .then(data => {
                    displayFavorites(data);
                })
                .catch(error => console.error('Error:', error));
        }

        // 显示收藏书籍
        function displayFavorites(favoriteBooks) {
            const favoritesList = document.getElementById('favoritesList');
            favoritesList.innerHTML = '';
            if (favoriteBooks.length === 0) {
                favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
            } else {
                favoriteBooks.forEach(book => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `书名: ${book.title} - 作者: ${book.author}`;

                    const borrowButton = document.createElement('button');
                    borrowButton.textContent = '借阅';
                    borrowButton.onclick = function () {
                        borrowFromFavorites(book.id);
                    };

                    const deleteButton = document.createElement('button');
                    deleteButton.textContent = '删除收藏';
                    deleteButton.onclick = function () {
                        removeFromFavorites(book.id);
                    };

                    listItem.appendChild(borrowButton);
                    listItem.appendChild(deleteButton);
                    favoritesList.appendChild(listItem);
                });
            }
        }

        // 从收藏中借阅书籍
        function borrowFromFavorites(bookId) {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            fetch('http://localhost:3000/user/borrow-from-favorite', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId, bookId: bookId })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        alert(data.message);
                        loadFavorites();
                        loadBorrowHistory();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('借阅书籍时发生错误，请稍后再试');
                });
        }

        // 从收藏中删除书籍
        function removeFromFavorites(bookId) {
            const userId = getUserId();
            if (!userId) {
                alert('用户信息已失效，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            fetch('http://localhost:3000/user/delete-favorite', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId, bookId: bookId })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        alert('您已成功从收藏中删除这本书');
                        loadFavorites();
                    }
                })
                .catch(error => console.error('Error:', error));
        }
    </script>
</body>

</html>查看代码，看是怎么回事，用户左上角显示未登录