<!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">
            <h2>搜索书籍</h2>
            <div class="form-container">
                <input type="text" id="searchInput" placeholder="搜索书名或作者">
                <button onclick="searchBooks()">查询</button>
            </div>
            <ul id="searchResults"></ul>
        </div>
        <div class="section" id="historySection" style="display:none;">
            <h2>借阅历史</h2>
            <ul class="book-list" id="borrowHistory"></ul>
        </div>
        <div class="section" id="favoritesSection" style="display:none;">
            <h2>我的收藏</h2>
            <ul class="book-list" id="favoritesList"></ul>
        </div>
    </div>
    <script>
        function logout() {
            alert('已退出登录');
            localStorage.removeItem('userInfo'); // 清除用户信息
            window.location.href = 'login.html'; // 重定向到登录页面
        }

        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>修改代码，让渲染处理的表单和数据都居中显示