<!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/admin.css" rel="stylesheet" type="text/css">
</head>
<style>
    li {
        list-style-type: none;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: center;
    }

    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }

    .book-list-container {
        margin-top: 20px;
    }

    .book-list-container h2 {
        margin-bottom: 20px;
    }

    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }

    .book-list-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }

    .book-list-header input[type="checkbox"] {
        margin-right: 10px;
    }

    .book-list-container ul {
        list-style-type: none;
        padding: 0;
    }

    .book-list-container li {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }

    .book-item {
        display: flex;
        align-items: center;
        flex-grow: 1;
    }

    .book-actions {
        display: flex;
        align-items: center;
        margin-left: 10px;
    }

    .book-actions button {
        margin-left: 18px;
    }

    .user-list-container ul {
        list-style-type: none;
        padding: 0;
        width: 100%;
    }

    .user-list-container li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding: 10px;
        margin-bottom: 10px;
    }
    .search-results-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px; /* 卡片之间的间隔 */
    margin-top: 20px;
}

.book-card {
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    width: 350px; 
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); 
    transition: transform 0.2s; 
}

.book-card:hover {
    transform: scale(1.05); 
}

.book-card h3 {
    margin-top: 0;
}

.book-card p {
    margin: 5px 0; 
}
</style>

<body>
    <div class="topbar">
        <div id="adminName">管理员：</div>
        <button onclick="logout()">退出</button>
    </div>
    <div class="sidebar">
        <h1>管理员菜单</h1>
        <button onclick="showForm('add')">增加图书</button>
        <button onclick="showForm('delete')">删除图书</button>
        <button onclick="showForm('edit')">修改图书</button>
        <button onclick="showForm('search')">查询图书</button>
        <button onclick="showForm('userManagement')">用户管理</button>
        <button onclick="showForm('dataManagement')">图书管理</button>
        <button onclick="showForm('borrowRecords')">借阅记录</button>
    </div>
    <div class="main-content">
        <div class="welcome-message" id="welcomeMessage">
            <h1 style="text-align: center;">欢迎进入管理系统</h1>
        </div>
        <div class="form-container centered-content" id="formContainer" style="display:none;">

        </div>

    </div>
    <script>
        function logout() {
            alert('已退出登录');
            window.location.href = 'login.html';
        }
        function showForm(type, id = null) {

            const formContainer = document.getElementById('formContainer');
            const welcomeMessage = document.getElementById('welcomeMessage');
            formContainer.innerHTML = '';
            formContainer.style.display = 'block';
            welcomeMessage.style.display = 'none';
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>增加图书</h1>
                        <input type="text" placeholder="书名">
                        <input type="text" placeholder="作者">
                        <input type="number" placeholder="出版年份">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
                    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>删除图书</h1>
                        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
                    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>借阅记录</h1>
                        <div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
                        <h1 style="text-align: center";>修改图书</h1>
                        <input type="text" placeholder="旧书名" id="oldTitle">
                        <input type="text" placeholder="新书名" id="newTitle">
                        <input type="text" placeholder="新作者" id="newAuthor">
                        <input type="number" placeholder="新出版年份" id="newYearPublished">
                        <div style="text-align: center;">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="editBook()">修改</button>
                    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
                        <div style="text-align: center;">
                        <h1 style="text-align: center";>查询图书</h1>
                        <input type="text" placeholder="搜索关键词" id="searchKeyword">
                        <button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
                    `;
                    break;
                case 'userManagement':
                    loadUsers().then(users => {
                        const userItems = users.map(user => `
            <li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                <div class="book-actions">
                    <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                    <button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </li>`).join("");

                        formContainer.innerHTML = `
            <h1 style="text-align: center;">用户管理</h1>
            <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
                <ul style="list-style-type: none; padding: 0;">
                    ${userItems}
                </ul>
            </div>
        `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                    <h2 style="text-align: center";>借阅记录</h2>
                        <!-- 这里可以添加借阅记录的相关表单或内容 -->
                    `;
                    break;
                case 'editUser':
                    fetch(`http://localhost:3000/admin/get-user/${id}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch user data');
                            }
                            return response.json();
                        })
                        .then(user => {
                            const formContainer = document.getElementById('formContainer');
                            formContainer.innerHTML = `
                <input type="hidden" value="${id}" name="id">
                <input type="text" placeholder="用户名" value="${user.username}" name="username">
                <input type="password" placeholder="密码" name="password">
                <select name="role">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                </select>
                <button onclick="editUser(${id})">保存</button>
            `;
                        })
                        .catch(error => {
                            console.error('获取用户数据出错:', error);
                            alert('获取用户数据失败: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗？此操作不可撤销！`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
                    welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
            }
        }

        function deleteBookByTitle() {
            const bookTitle = document.getElementById('bookTitle').value; // 获取书名

            if (!bookTitle) {
                alert('请输入书名以进行删除');
                return;
            }

            fetch('http://localhost:3000/admin/delete-book-by-title', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ title: bookTitle }) // 传递书名
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错：' + error.message);
                });
        }
        function addBook() {
            const formContainer = document.getElementById('formContainer');
            const title = formContainer.querySelector('input[placeholder="书名"]').value;
            const author = formContainer.querySelector('input[placeholder="作者"]').value;
            const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value;

            fetch('http://localhost:3000/admin/get-books') // 获取所有书籍的数组
                .then(response => {
                    if (!response.ok) {
                        throw new Error('无法加载书籍');
                    }
                    return response.json();
                })
                .then(books => {
                    const bookExists = books.some(book => book.title === title);
                    if (bookExists) {
                        alert('书名已经存在，无法添加。');
                        return;
                    }

                    // 发送增加图书的请求
                    return fetch('http://localhost:3000/admin/add-book', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'user-type': 'admin'
                        },
                        body: JSON.stringify({ title, author, year_published })
                    });
                })
                .then(response => {
                    // 前端处理整个响应
                    if (!response.ok) {
                        return response.json().then(err => {
                            alert(err.error || '添加图书时出错'); // 不再抛出异常
                        });
                    }

                    return response.text();
                })
                .then(data => {
                    alert('图书添加成功：' + data);
                    formContainer.innerHTML = '';
                    formContainer.style.display = 'none';
                    showForm('dataManagement');
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                });
        }

        function searchBooks() {
            const searchKeyword = document.getElementById('searchKeyword').value;

            fetch('http://localhost:3000/user/search-books', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: searchKeyword })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    displaySearchResults(data);
                })
                .catch(error => {
                    console.error('Error searching books:', error);
                    alert('搜索图书时出错：' + error.message);
                });
        }

        function displaySearchResults(books) {
    const formContainer = document.getElementById('formContainer');
    formContainer.innerHTML = `
        <div>
            <button onclick="showForm('search')">返回继续搜索</button>
        </div>
        <h2>搜索结果</h2>
        <div class="search-results-container">
    `;

    if (books.length === 0) {
        formContainer.innerHTML += '<p>未找到图书。</p>';
    } else {
        books.forEach(book => {
            formContainer.innerHTML += `
                <div class="book-card">
                    <h3>${book.title}</h3>
                    <p><strong>作者:</strong> ${book.author}</p>
                    <p><strong>出版年份:</strong> ${book.year_published}</p>
                </div>
            `;
        });
    }
    formContainer.innerHTML += `</div>`; // 闭合容器
}

        function loadBooks() {
            console.log('Starting to load books...');
            return fetch('http://localhost:3000/admin/get-books')
                .then(response => {
                    console.log('Received response from get-books:', response);
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log('Loaded books data:', books);
                    displayBooks(books);
                    return Promise.resolve();
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错：' + error.message);
                    return Promise.reject(error);
                });
        }

        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <div class="book-list-header">
                <input type="checkbox" id="selectAllBooks"> 全选
                <button onclick="deleteSelectedBooks()">删除选中</button>
            </div>
            <ul id="bookList">
    `;
            books.forEach(book => {
                formContainer.innerHTML += `
            <li style="display: flex; align-items: center;">
                <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;">
                    <input type="checkbox" class="bookCheckbox" value="${book.id}">
                    <strong>书名:</strong> ${book.title} &nbsp;&nbsp;
                    <strong>作者:</strong> ${book.author} &nbsp;&nbsp;
                    <strong>出版年份:</strong> ${book.year_published}
                </div>
                <div class="book-actions">
                    <button onclick="editBookForm('${book.id}')">编辑</button>
                    <button onclick="deleteBookConfirm('${book.id}')">删除</button>
                </div>
            </li>
        `;
            });
            formContainer.innerHTML += `
            </ul>
        </div>
    `;

            const selectAllCheckbox = document.getElementById('selectAllBooks');
            selectAllCheckbox.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.bookCheckbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
            bookCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }

        function deleteSelectedBooks() {
            const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
            const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);

            if (bookIds.length === 0) {
                alert('没有选中任何书籍。');
                return;
            }

            if (confirm('确定要删除选中的书籍吗？此操作不可撤销！')) {
                bookIds.forEach(id => {
                    deleteBook(id);
                });
            }
        }


        function loadUsers() {
    return fetch('http://localhost:3000/admin/get-users')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(users => {
            displayUsers(users);
            return users;
        })
        .catch(error => {
            console.error('Error loading users:', error);
            alert('加载用户时出错：' + error.message);
            throw error;
        });
}

function displayUsers(users) {
    const formContainer = document.getElementById('formContainer');
    formContainer.innerHTML = `
        <h2 style="text-align: center;">用户管理</h2>
        <div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
            <ul style="list-style-type: none; padding: 0;">
                ${users.map(user => `
                    <li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
                        <div class="book-actions">
                            <button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
                            <button onclick="deleteUser('${user.username}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button> <!-- 使用用户名 -->
                        </div>
                    </li>
                `).join('')}
            </ul>
        </div>
    `;
}

        function loadBorrowRecords() {
        fetch('http://localhost:3000/admin/borrow-records')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(records => {
                displayBorrowRecords(records);
            })
            .catch(error => {
                alert('加载借阅记录时出错：' + error.message);
            });
    }

    function displayBorrowRecords(records) {
        const borrowRecordsList = document.getElementById('borrowRecordsList');
        borrowRecordsList.innerHTML = '';
 
        if (records.length === 0) {
            borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
        } else {
            const table = document.createElement('table');
            table.innerHTML = `
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>作者</th>
                <th>借阅日期</th>
                <th>还书日期</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        `;
            records.forEach(record => {
                const borrowDate = new Date(record.borrow_date);
                const returnDate = record.return_date ? new Date(record.return_date) : null;
                const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
                const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN', options).replace(/\//g, '-');
                const formattedReturnDate = returnDate ? returnDate.toLocaleDateString('zh-CN', options).replace(/\//g, '-') : '未还';
 
                const row = document.createElement('tr');
                row.innerHTML = `
                <td>${record.username}</td>
                <td>${record.title}</td>
                <td>${record.author}</td>
                <td>${formattedBorrowDate}</td>
                <td>${formattedReturnDate}</td>
                <td>${record.status}</td>
                <td style="text-align: center;">
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
                table.appendChild(row);
            });
            borrowRecordsList.appendChild(table);
        }
    }


    function deleteUser(username) {
    if (confirm(`确定要删除用户 ${username} 吗？此操作不可撤销！`)) {
        fetch(`http://localhost:3000/admin/delete-user`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username }) // 这里传递用户名
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常: ' + response.statusText);
            }
            return response.text();
        })
        .then(data => {
            alert(data);
            loadUsers(); // 重新加载用户列表
        })
        .catch(error => {
            console.error('Error deleting user:', error);
            alert('删除用户时出现错误：' + error.message);
        });
    }
}
        function editUserForm(id) {
            fetch(`http://localhost:3000/admin/get-user/${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败，状态码：' + response.status);
                    }
                    return response.json();
                })
                .then(user => {
                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                <form id="editUserForm">
                    <input type="hidden" value="${id}" name="id">
                    <input type="text" placeholder="用户名" value="${user.username}" name="username">
                    <input type="password" placeholder="旧密码" name="oldPassword" required>
                    <input type="password" placeholder="新密码" name="newPassword">
                    <select name="role">
                        <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                        <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                    </select>
                    <button type="button" onclick="editUser(${id})">保存</button>
                    <button type="button" onclick="cancelEditUser()">取消</button>
                </form>
            `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错：', error);
                    alert('获取用户信息失败，请稍后重试：' + error.message);
                });
        }

        function cancelEditUser() {
            showForm('userManagement');
        }

        function editUser(id) {
    const form = document.querySelector(`#editUserForm`);
    if (!form || !(form instanceof HTMLFormElement)) {
        return;
    }
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());

    // 简单验证必填字段
    if (!data.username || !data.oldPassword || !data.newPassword || !data.role) {
        alert('请填写所有必填字段');
        return;
    }

    fetch(`http://localhost:3000/admin/edit-user`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('编辑用户失败');
        }
        return response.text();
    })
    .then(data => {
        alert(data);
        // 重新加载用户列表
        loadUsers();
    })
    .catch(error => {
        console.error('Error editing user:', error);
        alert('编辑用户信息时出错，请稍后重试：' + error.message);
    });
}

        function editBookForm(bookId) {
            fetch(`http://localhost:3000/admin/get-books`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('未能获取所有图书数据');
                    }
                    return response.json();
                })
                .then(allBooks => {
                    const targetBook = allBooks.find(book => book.id === Number(bookId));
                    if (!targetBook) {
                        alert('未找到对应图书信息，请确认图书ID是否正确');
                        return;
                    }

                    const formContainer = document.getElementById('formContainer');
                    formContainer.innerHTML = `
                        <h2>修改图书</h2>
                        <input type="hidden" value="${bookId}" id="bookId">
                        <input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
                        <input type="text" placeholder="新书名" id="newTitle" value="${targetBook.title}">
                        <input type="text" placeholder="新作者" id="newAuthor" value="${targetBook.author}">
                        <input type="number" placeholder="新出版年份" id="newYearPublished" value="${targetBook.year_published}">
                        <button onclick="editBook()">保存</button>
                        <button onclick="cancelEditBook()">取消</button>
                    `;
                })
                .catch(error => {
                    alert('获取图书信息失败，请稍后重试：' + error.message);
                });
        }

        function cancelEditBook() {
            const bookId = document.getElementById('bookId').value;
            if (bookId) {
                showForm('dataManagement'); // 返回图书管理列表
            }
        }

        function deleteBookConfirm(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }
            if (confirm(`确定要删除图书ID为${bookId}的图书吗？此操作不可撤销！`)) {
                deleteBook(bookId);
            }
        }

        function deleteBook(bookId) {
            if (!bookId) {
                alert('无效的图书ID');
                return;
            }

            fetch('http://localhost:3000/admin/delete-book', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ id: bookId })  // 使用书籍 ID
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    alert('删除图书时出错：' + error.message);
                });
        }

        function editBook() {
            const newTitle = document.getElementById('newTitle').value.trim();
            const newAuthor = document.getElementById('newAuthor').value.trim();
            const newYearPublished = document.getElementById('newYearPublished').value.trim();

            if (!newTitle || !newAuthor || !newYearPublished) {
                alert('请填写所有修改信息');
                return;
            }

            const oldTitle = document.getElementById('oldTitle').value;
            fetch('http://localhost:3000/admin/edit-book', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin'
                },
                body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement'); // 返回数据管理界面
                })
                .catch(error => {
                    alert('修改图书时出错：' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            if (!recordId) {
                alert('无效的借阅记录ID');
                return;
            }
            if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗？此操作不可撤销！`)) {
                deleteBorrowRecord(recordId);
            }
        }
        function deleteBorrowRecord(recordId) {
            fetch('http://localhost:3000/admin/delete-borrow-record', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: recordId })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.text();
                })
                .then(data => {
                    alert('借阅记录删除成功');
                    loadBorrowRecords();
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错：' + error.message);
                });
        }
        document.addEventListener('DOMContentLoaded', () => {
            fetchCurrentAdmin();
        });

        // 获取当前管理员信息
        function fetchCurrentAdmin() {
            fetch('http://localhost:3000/admin/current')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log(data);

                    document.getElementById('adminName').textContent = `管理员：${data.username}`;
                })
                .catch(error => {
                    console.error('获取管理员名错误:', error);
                    document.getElementById('adminName').textContent = '管理员：未知'; // 出错时处理
                });
        }
    </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, br.return_date, br.is_returned, br.status 
        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 { username } = req.body; // 使用用户名

    // 开启事务
    db.beginTransaction(err => {
        if (err) {
            console.error('启动事务出错:', err);
            res.status(500).send('启动事务时服务器错误');
            return;
        }

        // 删除借阅记录
        const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id = (SELECT id FROM users WHERE username = ?)';
        db.query(deleteBorrowRecordsQuery, [username], (err => {
            if (err) {
                db.rollback(() => {
                    res.status(500).send('删除相关借阅记录时服务器错误，事务回滚');
                });
                return;
            }
            
            const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id = (SELECT id FROM users WHERE username = ?)';
            db.query(deleteFavoritesQuery, [username], (err => {
                if (err) {
                    db.rollback(() => {
                        res.status(500).send('删除相关收藏时出现服务器错误，事务回滚');
                    });
                    return;
                }
                
                const userIdQuery = 'SELECT id FROM users WHERE username = ?';
                db.query(userIdQuery, [username], (err, results) => {
                    if (err || results.length === 0) {
                        db.rollback(() => {
                            res.status(500).send('未能找到用户，事务回滚');
                        });
                        return;
                    }
                    
                    const userId = results[0].id;
                    
                    const deleteUserQuery = 'DELETE FROM users WHERE id = ?';
                    db.query(deleteUserQuery, [userId], (err, results) => {
                        if (err) {
                            db.rollback(() => {
                                console.error('删除用户出错，要删除的用户:', username);
                                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('用户删除成功，用户:', username);
                                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}`);
});获取到的还是确定要删除用户 17 吗？此操作不可撤销！，查看代码，看是哪里出问题