<!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>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        display: flex;
        background-color: #f4f4f4;
    }

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

    .topbar button {
        background-color: #dc3545;
        border: none;
        color: white;
        padding: 8px 12px;
        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: 220px;
        background-color: #343a40;
        color: white;
        padding: 20px;
        position: fixed;
        top: 50px;
        height: calc(100% - 50px);
        overflow: auto;
    }

    .sidebar h1 {
        font-size: 24px;
        margin-bottom: 20px;
    }

    .sidebar button {
        width: 100%;
        padding: 12px;
        margin: 6px 0;
        border: none;
        border-radius: 4px;
        background-color: #495057;
        color: white;
        cursor: pointer;
        transition: background-color 0.3s;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

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

    .main-content {
        margin-left: 240px;
        padding: 20px;
        flex-grow: 1;
        background-color: #f4f4f4;
        margin-top: 50px;
    }

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

    .form-container h2 {
        text-align: center;
        margin-bottom: 20px;
        color: #343a40;
    }

    .form-container input,
    .form-container select,
    .form-container button {
        width: 100%;
        padding: 12px 15px;
        margin: 10px 0;
        border: 1px solid #ccc;
        border-radius: 4px;
        font-size: 16px;
        box-sizing: border-box;
    }

    .form-container button {
        background-color: #28a745;
        color: white;
        transition: background-color 0.3s;
    }

    .form-container button:hover {
        background-color: #218838;
    }

    .form-container button.delete {
        background-color: #dc3545;
    }

    .form-container button.delete:hover {
        background-color: #c82333;
    }

    .form-container button.search {
        background-color: #ffc107;
    }

    .form-container button.search:hover {
        background-color: #e0a800;
    }

    .book-list-container {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    li {
        list-style-type: none;
    }

    .book-list-container ul {
        list-style-type: none;
        /* 去掉小黑点 */
        padding: 0;
        margin: 0;
        width: 100%;
    }

    .book-list-container li {
        padding: 15px;
    background-color: #f8f9fa;
    border-radius: 5px;
    margin: 10px 0;
    text-align: left;  /* 左对齐文本 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    transition: background-color 0.3s;
    width: 100%;  /* 确保列表项的宽度 */
    display: flex; /* 使用flexbox以便在同一行内排列内容 */
    justify-content: space-between; /* 分散对齐，确保按钮在右边 */
    align-items: center; /* 垂直居中对齐 */
    }

    .book-list-container li:hover {
        background-color: #e2e6ea;
    }

    .table-container {
        max-width: 800px;
        margin: 20px auto;
        overflow-x: auto;
    }

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

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

    th {
        background-color: #f2f2f2;
    }

    /* 新增用户管理部分的样式 */
    .user-list-container ul {
        list-style-type: none;
        /* 去掉小黑点 */
        padding: 0;
        margin: 0;
        width: 100%;
    }

    .user-list-container li {
        padding: 15px;
    background-color: #f8f9fa;
    border-radius: 5px;
    margin: 10px 0;
    text-align: left;  /* 左对齐文本 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    transition: background-color 0.3s;
    width: 100%;  /* 确保列表项的宽度 */
    display: flex; /* 使用flexbox以便在同一行内排列内容 */
    justify-content: space-between; /* 分散对齐，确保按钮在右边 */
    align-items: center; /* 垂直居中对齐 */
    }

    .user-list-container li:hover {
        background-color: #dee2e6;
    }

    body {
        color: #495057;
        /* 加强文本可读性 */
    }
</style>

<body>
    <div class="topbar">
        <div>管理员：张三</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="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');
            formContainer.innerHTML = ''; // 清空之前的内容
            formContainer.style.display = 'block';

            // 根据type动态创建表单
            switch (type) {
                case 'add':
                    formContainer.innerHTML = `
        <h2>增加图书</h2>
        <input type="text" placeholder="书名" required>
        <input type="text" placeholder="作者" required>
        <input type="number" placeholder="出版年份" required>
        <button onclick="addBook()">添加</button>
    `;
                    break;
                case 'delete':
                    formContainer.innerHTML = `
        <h2>删除图书</h2>
        <input type="text" id="bookTitle" placeholder="输入书名" style="width: 100%;" required />
        <button onclick="deleteBookByTitle()">删除</button>
    `;
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
                    loadBorrowRecords();
                    break;
                case 'edit':
                    formContainer.innerHTML = `
        <h2>修改图书</h2>
        <input type="text" placeholder="旧书名" id="oldTitle" required disabled>
        <input type="text" placeholder="新书名" id="newTitle" required>
        <input type="text" placeholder="新作者" id="newAuthor" required>
        <input type="number" placeholder="新出版年份" id="newYearPublished" required>
        <button onclick="editBook()">修改</button>
    `;
                    break;
                case 'search':
                    formContainer.innerHTML = `
        <h2>查询图书</h2>
        <input type="text" placeholder="搜索关键词" id="searchKeyword" required>
        <button onclick="searchBooks()">查询</button>
    `;
                    break;
                case 'userManagement':
                    loadUsers().then(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.forEach(user => {
                            formContainer.innerHTML += `
    <li style="margin: 10px 0;">
        ${user.username}
        <button onclick="editUserForm('${user.id}')">编辑</button>
        <button onclick="deleteUser('${user.id}')">删除</button>
    </li>
    `;
                        });
                        formContainer.innerHTML += `
                    </ul>
                </div>
            `;
                    });
                    break;
                case 'dataManagement':
                    formContainer.innerHTML = `
                        <h2>数据管理</h2>
                        <!-- 这里可以添加数据管理的相关表单或内容 -->
                    `;
                    loadBooks();  // 正确的位置
                    break;
                case 'borrowRecords':
                    formContainer.innerHTML = `
                        <h2>借阅记录</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 fetching user data:', error);
                            alert('Failed to fetch user data: ' + error.message);
                        });
                    break;
                case 'deleteUser':
                    if (confirm(`确定要删除用户ID为${id}的用户吗？此操作不可撤销！`)) {
                        deleteUser(id);
                    }
                    break;
                default:
                    formContainer.style.display = 'none';
            }
        }

        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('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book deleted:', data);
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    console.error('Error deleting book:', 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/add-book', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'user-type': 'admin' // 假设已经在某处设置了用户类型
                },
                body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book added:', data);
                    alert('图书添加成功：' + data); // 显示成功消息
                    // 可选：清空表单
                    formContainer.innerHTML = '';
                    formContainer.style.display = 'none';
                    // 可选：更新图书列表（如果有的话）
                })
                .catch(error => {
                    console.error('Error adding book:', error);
                    alert('添加图书时出错：' + error.message);
                });
        }

        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('Network response was not ok');
                    }
                    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>
    `;

            if (books.length === 0) {
                formContainer.innerHTML += '<p>未找到图书。</p>';
            } else {
                const resultsList = document.createElement('ul');
                books.forEach(book => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
                    resultsList.appendChild(listItem);
                });
                formContainer.appendChild(resultsList);
            }
        }

        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('Network response was not ok');
                    }
                    return response.json();
                })
                .then(books => {
                    console.log('Loaded books data:', books);
                    displayBooks(books);
                    return Promise.resolve();  // 显式返回一个已解决的Promise，确保外层能正确链式调用
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                    alert('加载图书时出错：' + error.message);
                    return Promise.reject(error);  // 出现错误时返回一个被拒绝的Promise，传播错误
                });
        }

        function displayBooks(books) {
            const formContainer = document.getElementById('formContainer');
            formContainer.innerHTML = `
        <h2 style="text-align: center;">图书管理</h2>
        <div class="book-list-container">
            <ul>
    `;
            books.forEach(book => {
                formContainer.innerHTML += `
       <li>
        ${book.title} by ${book.author} (${book.year_published})
        <button onclick="editBookForm('${book.id}')">编辑</button>
        <button onclick="deleteBookConfirm('${book.id}')">删除</button>
    </li>
        `;
            });
            formContainer.innerHTML += `
            </ul>
        </div>
    `;
            return Promise.resolve();
        }

        function loadUsers() {
            return fetch('http://localhost:3000/admin/get-users')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(users => {
                    displayUsers(users);
                    return users; // 将处理后的用户数据返回，使得外层能接收到这个 Promise 结果
                })
                .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.forEach(user => {
                formContainer.innerHTML += `
            <li style="margin: 10px 0;">
                ${user.username}
                <button onclick="editUserForm('${user.id}')">编辑</button>
                <button onclick="deleteUserConfirm('${user.id}')">删除</button>
            </li>
        `;
            });
            formContainer.innerHTML += `
            </ul>
        </div>
    `;
        }

        function loadBorrowRecords() {
            fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(records => {
                    console.log('Loaded borrow records:', records); // 检查返回的 records
                    displayBorrowRecords(records);
                })
                .catch(error => {
                    console.error('Error loading borrow records:', error);
                    alert('加载借阅记录时出错：' + error.message);
                });
        }

        function displayBorrowRecords(records) {
            console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构

            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>
            </tr>
        `;
                records.forEach(record => {
                    console.log('Record:', record); // 输出每一条记录
                    const row = document.createElement('tr');
                    row.innerHTML = `
                <td>${record.username}</td>
                <td>${record.title}</td>
                <td>${record.author}</td>
                <td>${record.borrow_date}</td>
                <td>
                    <button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
                </td>
            `;
                    table.appendChild(row);
                });
                borrowRecordsList.appendChild(table);
            }
        }


        function deleteUser(id) {
            fetch(`http://localhost:3000/admin/delete-user`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + 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="password">
                    <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>
                </form>
            `;
                })
                .catch(error => {
                    console.error('编辑用户信息获取出错：', error);
                    alert('获取用户信息失败，请稍后重试：' + error.message);
                });
        }

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

            // Simple validation for required fields
            if (!data.username || !data.password || !data.role) {
                alert('请填写所有必填字段');
                return;
            }

            fetch(`http://localhost:3000/admin/edit-user`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
                .then(response => 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('Failed to fetch all books data');
                    }
                    return response.json();
                })
                .then(allBooks => {
                    // 在获取到的所有图书数据中查找对应id的图书
                    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="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
                <input type="text" placeholder="新书名" id="newTitle">
                <input type="text" placeholder="新作者" id="newAuthor">
                <input type="number" placeholder="新出版年份" id="newYearPublished">
                <button onclick="editBook()">保存</button>
            `;
                })
                .catch(error => {
                    console.error('Error fetching book data:', error);
                    alert('获取图书信息失败，请稍后重试：' + error.message);
                });
        }

        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('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book deleted:', data);
                    alert('图书删除成功');
                    loadBooks();  // 重新加载图书列表
                })
                .catch(error => {
                    console.error('Error deleting book:', 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; // 注意，没有trim()，因为oldTitle是禁用输入，不应更改

            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('Network response was not ok: ' + response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Book edited:', data);
                    alert('图书修改成功');
                    showForm('dataManagement'); // 返回数据管理界面
                })
                .catch(error => {
                    console.error('Error editing book:', error);
                    alert('修改图书时出错：' + error.message);
                });
        }
        function deleteBorrowRecordConfirm(recordId) {
            console.log('Attempting to delete record with ID:', 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 }) // 发送要删除记录的 ID
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('Borrow record deleted:', data);
                    alert('借阅记录删除成功');
                    loadBorrowRecords(); // 重新加载借阅记录列表
                })
                .catch(error => {
                    console.error('Error deleting borrow record:', error);
                    alert('删除借阅记录时出错：' + error.message);
                });
        }
    </script>
</body>

</html>修改代码，让按钮变的渲染的数据在同一条数据上