在“我的收藏”部分当借阅记录存在某本书时阻止用户继续借阅该书，<!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/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'
                    });

                    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();
                })
                .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/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('获取借阅记录时发生错误，请稍后再试');
        });
}

        // 从收藏中删除书籍
        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>