修改代码，让搜索书籍点击查询出来的样式变好看点，高级点      <!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>用户：<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 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 () {
    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/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/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'
            });

            // 显示所有信息，包括记录 ID 和状态
            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); // 检查用户 ID
    console.log('Record ID:', borrowRecordId); // 检查记录 ID
    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 }) // 发送正确的记录 ID
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            alert(data.message); // 通知用户还书状态
            loadBorrowHistory(); // 刷新借阅历史
        })
        .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('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>         body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4; /* 背景颜色 */
}


.topbar {
    background-color: #343a40;
    color: white;
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: padding 0.3s;
}

.topbar button {
    background-color: #dc3545;
    border: none;
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.3s;
}

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

.sidebar {
    width: 200px;
    background-color: #343a40;
    color: white;
    padding: 20px;
    position: fixed;
    top: 50px;
    height: calc(100% - 50px);
    overflow: auto;
}

.sidebar h1 {
    text-align: center;
    font-size: 26px;
    margin-bottom: 22px;
}

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

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

.main-content {
    margin-left: 200px;
    padding: 20px;
    flex-grow: 1;
    background-color: #f4f4f4;
    margin-top: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.section {
    width: 100%;
    max-width: 600px;
    margin-bottom: 20px;
    text-align: center;
}

.form-container {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 100%;
    margin: 0 auto;
}

.form-container input {
    width: 96%;
    padding: 15px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.form-container button {
    padding: 10px 20px;
    font-size: 16px;
    width: auto;
    background-color: #28a745;
    transition: background-color 0.3s, transform 0.3s;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.book-list {
    list-style-type: none;
    padding: 0;
    width: 100%; /* Full width for the book list */
}

.book-list li {
    background-color: white; /* Set background color for each item */
    padding: 15px; /* Add some padding */
    margin: 10px 0; /* Add margin for spacing */
    border-radius: 5px; /* Round the corners */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* Add shadow effect */
    display: flex; /* Use flex for better alignment */
    justify-content: space-between; /* Space out content */
    align-items: center; /* Center align items vertically */
}

.book-list li:last-child {
    border-bottom: none;
}

.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); /* 缩放效果 */
}