借阅记录中的书籍在用户成功还书后可以在“我的收藏”中继续借阅<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户页面</title>
    <link href="./css/user.css" rel="stylesheet" type="text/css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(to right, #e2e3e5, #ffffff);
            margin: 0;
            color: #333;
        }

        .topbar {
            background-color: #343a40;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        .topbar button {
            background-color: #dc3545;
            border: none;
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
            font-weight: bold;
        }

        .topbar button:hover {
            background-color: #c82333;
            transform: scale(1.05);
        }

        .sidebar {
            width: 240px;
            background-color: #343a40;
            color: white;
            padding: 20px;
            position: fixed;
            top: 75px;
            height: calc(100% - 75px);
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2);
        }

        .sidebar h1 {
            text-align: center;
            font-size: 24px;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .sidebar button {
            font-size: 16px;
            width: 100%;
            padding: 12px;
            margin: 8px 0;
            border: none;
            border-radius: 8px;
            background-color: #495057;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .sidebar button:hover {
            background-color: #5a6268;
        }

        .main-content {
            margin-left: 240px;
            padding: 25px;
            flex-grow: 1;
            background-color: #f8f9fa;
            margin-top: 75px;
            flex-direction: column;
            align-items: center;
        }

        .section {
            width: 100%;
            max-width: 800px;
            margin-bottom: 30px;
            text-align: center;
            /* background-color: white;  */
            border-radius: 10px;
            /* 圆角 */
            /* box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);  */
            padding: 20px;
        }

        .form-container {
            padding: 20px;
            margin: 0 auto;
        }

        .form-container input {
            width: calc(100% - 30px);
            padding: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin: 10px 0;
            transition: border-color 0.3s;
        }

        .form-container input:focus {
            border-color: #007bff;
            outline: none;
        }

        .query-button {
            padding: 12px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
        }

        .query-button:hover {
            background-color: #0056b3;
            transform: scale(1.05);
        }

        .search-results-container {
            padding: 20px;
            border-radius: 10px;
            width: 100%;
            margin-top: 20px;
        }

        .search-result-item {
            background-color: white;
            padding: 15px;
            margin: 10px 0;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .search-result-item div {
            flex: 1;
            margin-right: 20px;
        }

        .book-actions button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .book-actions button:hover {
            background-color: #0056b3;
        }

        .book-list {
            list-style-type: none;
            padding: 0;
            width: 100%;
        }

        .book-list li {
            background-color: white;
            padding: 15px;
            margin: 10px 0;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .book-list button {
            background-color: #007bff;
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
        }

        .book-list button:hover {
            background-color: #0056b3;
            transform: scale(1.05);
        }
    </style>
</head>

<body>
    <div class="topbar">
        <div>用户：<span id="username-display">未登录</span></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 class="query-button" onclick="searchBooks()">查询</button>
            </div>
            <div id="searchResults" class="search-results-container"></div>
        </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 () {
            updateUsernameDisplay();
        });

        function logout() {
            alert('已退出登录');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('username');
            updateUsernameDisplay();
            window.location.href = 'login.html';
        }

        function updateUsernameDisplay() {
            const username = localStorage.getItem('username');
            const usernameDisplay = document.getElementById('username-display');
            if (username) {
                usernameDisplay.textContent = username;
            } else {
                usernameDisplay.textContent = '未登录';
                console.log('在 localStorage 中未找到用户名');
            }
        }

        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('div');
                    listItem.className = 'search-result-item';
                    listItem.innerHTML = `
                        <div>
                            <strong>书名:</strong> ${book.title}<br>
                            <strong>作者:</strong> ${book.author}<br>
                            <strong>出版年份:</strong> ${book.year_published}
                        </div>
                        <div class="book-actions">
                            <button onclick="borrowBook(${book.id})">借阅</button>
                            <button onclick="addToFavorites(${book.id})">添加到收藏</button>
                        </div>
                    `;
                    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/favorites/${userId}`)
        .then(response => response.json())
        .then(favorites => {
            const isFavorited = favorites.some(fav => fav.book_id === bookId);
            if (isFavorited) {
                alert('您已经将此书收藏，不能重复借阅！');
                return; // 不允许再次借阅
            }

            // 检查书籍是否已经被借出
            return fetch(`http://localhost:3000/user/borrow-history/${userId}`);
        })
        .then(response => response.json())
        .then(borrowedRecords => {
            const isAlreadyBorrowed = borrowedRecords.some(record => record.book_id === bookId && !record.is_returned);
            if (isAlreadyBorrowed) {
                alert('您已借阅此书，必须先还书才能借阅！');
                return; // 不允许借阅
            }

            // 如果没有借过，允许借阅
            return fetch('http://localhost:3000/user/borrow-book', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId, bookId: bookId })
            });
        })
        .then(response => {
            if (response && response.ok) {
                return response.text();
            } else {
                throw new Error('网络响应不正常');
            }
        })
        .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} - 状态: ${record.status}`;

                    const returnButton = document.createElement('button');
                    returnButton.textContent = '还书';
                    returnButton.onclick = function () {
                        console.log('Attempting to return book with Record ID:', record.id);
                        returnBook(record.id, returnButton);
                    };

                    if (record.status === '已还书') {
                        returnButton.disabled = true;
                        returnButton.textContent = '已还书';
                    }

                    listItem.appendChild(returnButton);
                    borrowHistory.appendChild(listItem);
                });
            }
        }

        function returnBook(borrowRecordId, returnButton) {
    const userId = getUserId();
    console.log('User ID:', userId);
    console.log('Record ID:', borrowRecordId);
    if (!userId || !borrowRecordId) {
        alert('无效的用户 ID 或借阅记录 ID');
        return;
    }

    console.log("Returning book with Record ID:", borrowRecordId, "for User ID:", userId);

    returnButton.disabled = true;
    returnButton.textContent = '处理中...';

    fetch('http://localhost:3000/user/return-book', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userId: userId, recordId: borrowRecordId })
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            alert(data.message);

            // 在成功还书后，重新加载借阅历史和收藏
            loadBorrowHistory();
            loadFavorites();  // 刷新收藏，以便用户能再次借阅
        })
        .catch(error => {
            console.error('Error:', error);
            alert('还书时发生错误，请稍后再试');
            returnButton.disabled = false;
            returnButton.textContent = '还书';
        });
}

        // 添加到收藏
        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('网络响应不正常');
                    }
                    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-history/${userId}`)
        .then(response => response.json())
        .then(borrowedRecords => {
            // 检查该书籍是否已经被借阅
            const isAlreadyBorrowed = borrowedRecords.some(record => record.book_id === bookId && !record.is_returned);
            if (isAlreadyBorrowed) {
                alert('您已借阅此书，必须先还书才能借阅！');
                return; // 不允许借阅
            }

            // 在借阅前检查用户的收藏
            fetch(`http://localhost:3000/user/favorites/${userId}`)
                .then(response => response.json())
                .then(favorites => {
                    const isFavorited = favorites.some(fav => fav.book_id === bookId);
                    if (!isFavorited) {
                        alert('这本书您已借阅过了');
                        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('网络响应不正常');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.error) {
                            alert(data.error);
                        } else {
                            alert(data.message);
                            loadFavorites();
                            loadBorrowHistory();
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('借阅书籍时发生错误，请稍后再试');
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取收藏记录时发生错误，请稍后再试');
                });
        })
        .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>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', 
    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) {
            const user = results[0]; 
            if (user.role === 'admin') {
                currentAdmin = user;
            }
            res.json({ id: user.id, username: user.username, role: user.role }); 
        } else {
            res.status(400).json({ error: '无效的登录' });
        }
    });
});
// 从借阅记录中删除借阅记录（还书功能）
app.post('/user/return-book', (req, res) => {
    const { userId, recordId } = req.body;

    // 确保用户和记录 ID 是有效的
    if (!userId || !recordId || isNaN(recordId)) {
        return res.status(400).json({ error: '无效的用户ID或记录ID' });
    }

    // 执行还书更新
    const query = 'UPDATE borrow_records SET is_returned = TRUE, return_date = NOW(), status = "已还书" WHERE id = ? AND user_id = ?';
    db.query(query, [recordId, userId], (err, results) => {
        if (err) {
            console.error('Error returning book:', err);
            return res.status(500).json({ error: '未能还书' });
        }

        if (results.affectedRows > 0) {
            res.json({ message: '书籍已成功还回！' });
        } else {
            res.status(404).json({ error: '未找到该借阅记录' });
        }
    });
});
// 获取当前管理员信息
app.get('/admin/current', (req, res) => {
    if (currentAdmin) {
        res.json({ username: currentAdmin.username }); 
    } else {
        res.status(401).json({ error: '没有管理员登录' }); 
    }
});
// 注册路由
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: '服务器错误' });
        } else if (results.length > 0) {
            res.status(400).json({ error: '用户名已存在' });
        } 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: '注册用户失败' });
                } else {
                    res.status(201).send('用户注册成功');
                }
            });
        }
    });
});
// 管理员操作路由
// 添加图书
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) {
            return res.status(500).json({ error: '检查现有图书失败' });
        }

        if (results.length > 0) {
            return res.status(400).json({ error: '书名已经存在' }); 
        }

        const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
        db.query(query, [title, author, year_published], (err, results) => {
            if (err) {
                console.error('添加图书错误:', err);
                return res.status(500).json({ error: '添加图书失败' });
            }
            res.status(200).send('成功添加图书');
        });
    });
});
// 删除图书按ID
app.post('/admin/delete-book', (req, res) => {
    const { id } = req.body;

    if (!id || isNaN(id)) {
        res.status(400).json({ error: '无效的图书ID格式' });
        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: '删除图书失败。错误的细节: ' + err.message });
        } else {
            if (results.affectedRows > 0) {
                res.send('书成功删除');
            } else {
                res.status(404).send('没有找到有这个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('服务器错误');
        } 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('服务器错误');
        } 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) {
            return res.status(500).json({ error: '编辑图书失败。错误的细节: ' + err.message });
        }
        if (results.affectedRows > 0) {
            res.status(200).send('图书编辑成功');
        } else {
            res.status(404).send('没有发现有这个标题的书可以编辑');
        }
    });
});
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('编辑书错误:', err);
            return res.status(500).json({ error: '编辑图书失败。错误的细节: ' + err.message });
        }
        if (results.affectedRows > 0) {
            res.status(200).send('图书编辑成功');
        } else {
            res.status(404).send('没有发现有这个标题的书可以编辑');
        }
    });
});

app.get('/admin/get-books', (req, res) => {
    const query = 'SELECT * FROM books';
    db.query(query, (err, results) => {
        if (err) {
            res.status(500).json({ error: '找不到书' });
        } else {
            res.json(results);
        }
    });
});

// 获取所有用户
app.get('/admin/get-users', (req, res) => {
    const query = 'SELECT * FROM users';
    db.query(query, (err, results) => {
        if (err) {
            res.status(500).json({ error: '获取用户失败' });
        } 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('借书错误:', err);
            res.status(500).json({ error: '借书失败' });
        } else {
            res.status(200).send('成功借书');
        }
    });
});

// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
    const { userId } = req.params;
    const query = `
        SELECT br.id, b.title, b.author, br.borrow_date, br.status 
        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('服务器错误');
        } else {
            console.log('取得的借阅记录:', results);
            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('服务器错误');
        } else {
            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('获取用户数据进行密码验证时出错:', err);
            return res.status(500).json({ error: '验证密码失败' });
        }
        if (!user || user.length === 0 || user[0].password !== oldPassword) {
            // 旧密码不正确
            return res.status(400).json({ error: '旧密码无效' });
        }
 
        // 更新用户信息
        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: '编辑用户失败' });
            }
            console.log('用户信息编辑成功，编辑的用户ID：', id);
            res.status(200).send('用户编辑成功');
        });
    });
});

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

    if (!title || typeof title !== 'string') {
        return res.status(400).json({ error: '无效的书名格式' });
    }

    const query = 'DELETE FROM books WHERE title = ?';
    db.query(query, [title], (err, results) => {
        if (err) {
            return res.status(500).json({ error: '删除图书失败。错误的细节: ' + err.message });
        } else {
            if (results.affectedRows > 0) {
                res.send('书删除成功');
            } else {
                res.status(404).send('没有找到那个书名的书');
            }
        }
    });
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
    const { id } = req.body;
    db.beginTransaction((err => {
        if (err) {
            console.error('启动事务出错:', err);
            res.status(500).send('启动事务时服务器错误');
            return;
        }
        const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
        db.query(deleteBorrowRecordsQuery, [id], (err => {
            if (err) {
                db.rollback(() => {
                    res.status(500).send('删除相关借阅记录时服务器错误，事务回滚');
                });
                return;
            }
            const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
            db.query(deleteFavoritesQuery, [id], (err => {
                if (err) {
                    db.rollback(() => {
                        res.status(500).send('删除相关收藏夹时出现服务器错误，事务回滚');
                    });
                    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('服务器错误，事务回滚');
                        });
                    } else {
                        db.commit((err => {
                            if (err) {
                                res.status(500).send('提交事务时服务器错误');
                                return;
                            }
                            console.log('用户删除成功，删除的用户ID：', id);
                            res.send('用户删除成功');
                        }));
                    }
                });
            }));
        }));
    }));
});
//获取单个用户
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('获取用户错误:', err);
            res.status(500).json({ error: '获取用户失败' });
        } else if (results.length === 0) {
            res.status(404).json({ error: '未找到用户' });
        } 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) {
            res.status(500).json({ error: '编辑借阅记录失败' });
        } else {
            res.status(200).send('成功编辑借用记录');
        }
    });
});

// 删除借阅记录
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('删除借阅记录错误:', 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;
    if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
        res.status(400).json({ error: '无效的借用记录ID格式或值' });
        return;
    }
    const query = `
        SELECT * 
        FROM borrow_records 
        WHERE id =?
    `;
    db.query(query, [id], (err, results) => {
        if (err) {
            res.status(500).json({ error: '未能取得借阅记录。错误的细节: ' + err.message });
        } else if (results.length === 0) {
            res.status(404).json({ error: '未找到借阅记录' });
        } 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: '服务器错误' });
        } else if (results.length > 0) {
            // 已收藏，提示用户
            res.status(400).json({ error: '这本书已被列入收藏夹' });
        } 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: '添加收藏夹失败' });
                } else {
                    res.status(200).json({ message: '成功将图书添加到收藏夹' });
                }
            });
        }
    });
});

// 删除收藏书籍路由
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: '删除收藏夹时服务器错误' });
        } else if (results.affectedRows === 0) {
            // 如果受影响的行数为0，表示没有找到对应的收藏记录，即可能已经不存在该收藏了
            res.status(400).json({ error: '这本书不在你的最爱之列' });
        } else {
            res.status(200).json({ message: '成功从收藏夹中删除图书' });
        }
    });
});

// 从收藏中借阅书籍
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('在借阅前删除收藏夹错误:', err);
            res.status(500).json({ error: '未能从最喜欢的人那里借书' });
            return;
        }
        if (deleteResults.affectedRows === 0) {
            res.status(400).json({ error: '这本书不在你的最爱之列' });
            return;
        }

        const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
        db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
            if (err) {
                res.status(500).json({ error: '未能借书' });
            } else {
                res.status(200).json({ message: '从收藏夹借的书成功了' });
            }
        });
    });
});
 
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`在端口上运行的服务器 ${PORT}`);
});