// borrow_management.js
document.addEventListener('DOMContentLoaded', function() {
    // 归还图书功能
    const returnButtons = document.querySelectorAll('.return-btn');
    const returnModal = document.getElementById('returnModal');
    const returnBookTitle = document.getElementById('returnBookTitle');
    const confirmReturnButton = document.getElementById('confirmReturn');
    let currentBorrowId = null;
    returnButtons.forEach(button => {
        button.addEventListener('click', function() {
            const borrowId = this.getAttribute('data-id');
            const bookTitle = this.getAttribute('data-title');
            currentBorrowId = borrowId;
            returnBookTitle.textContent = bookTitle;
            // 使用 Bootstrap 的 jQuery 方法显示模态框
            $('#returnModal').modal('show');
        });
    });
    confirmReturnButton.addEventListener('click', function() {
        if (!currentBorrowId) return;
        // 发送归还请求
        fetch(`/borrow/return/${currentBorrowId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            // 隐藏模态框
            $('#returnModal').modal('hide');
            if (data.success) {
                // 显示成功消息
                showAlert('success', data.message);
                // 重新加载页面以更新借阅状态
                setTimeout(() => window.location.reload(), 1500);
            } else {
                // 显示错误消息
                showAlert('danger', data.message);
            }
        })
        .catch(error => {
            $('#returnModal').modal('hide');
            showAlert('danger', '操作失败,请稍后重试');
            console.error('Error:', error);
        });
    });
    // 续借图书功能
    const renewButtons = document.querySelectorAll('.renew-btn');
    const renewModal = document.getElementById('renewModal');
    const renewBookTitle = document.getElementById('renewBookTitle');
    const confirmRenewButton = document.getElementById('confirmRenew');
    renewButtons.forEach(button => {
        button.addEventListener('click', function() {
            const borrowId = this.getAttribute('data-id');
            const bookTitle = this.getAttribute('data-title');
            currentBorrowId = borrowId;
            renewBookTitle.textContent = bookTitle;
            // 使用 Bootstrap 的 jQuery 方法显示模态框
            $('#renewModal').modal('show');
        });
    });
    confirmRenewButton.addEventListener('click', function() {
        if (!currentBorrowId) return;
        // 发送续借请求
        fetch(`/borrow/renew/${currentBorrowId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            // 隐藏模态框
            $('#renewModal').modal('hide');
            if (data.success) {
                // 显示成功消息
                showAlert('success', data.message);
                // 重新加载页面以更新借阅状态
                setTimeout(() => window.location.reload(), 1500);
            } else {
                // 显示错误消息
                showAlert('danger', data.message);
            }
        })
        .catch(error => {
            $('#renewModal').modal('hide');
            showAlert('danger', '操作失败,请稍后重试');
            console.error('Error:', error);
        });
    });
    // 逾期通知功能
    const notifyButtons = document.querySelectorAll('.notify-btn');
    const notifyModal = document.getElementById('notifyModal');
    const notifyBookTitle = document.getElementById('notifyBookTitle');
    const confirmNotifyButton = document.getElementById('confirmNotify');
    notifyButtons.forEach(button => {
        button.addEventListener('click', function() {
            const borrowId = this.getAttribute('data-id');
            const bookTitle = this.getAttribute('data-title');
            currentBorrowId = borrowId;
            notifyBookTitle.textContent = bookTitle;
            // 使用 Bootstrap 的 jQuery 方法显示模态框
            $('#notifyModal').modal('show');
        });
    });
    confirmNotifyButton.addEventListener('click', function() {
        if (!currentBorrowId) return;
        // 发送通知请求
        fetch(`/borrow/overdue/notify/${currentBorrowId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            // 隐藏模态框
            $('#notifyModal').modal('hide');
            if (data.success) {
                // 显示成功消息
                showAlert('success', data.message);
                // 禁用已点击的通知按钮
                document.querySelector(`.notify-btn[data-id="${currentBorrowId}"]`).disabled = true;
            } else {
                // 显示错误消息
                showAlert('danger', data.message);
            }
        })
        .catch(error => {
            $('#notifyModal').modal('hide');
            showAlert('danger', '操作失败,请稍后重试');
            console.error('Error:', error);
        });
    });
    // 图书搜索功能
    const bookSearchInput = document.getElementById('bookSearch');
    const searchBookBtn = document.getElementById('searchBookBtn');
    const bookSelect = document.getElementById('bookSelect');
    function searchBooks() {
        const searchTerm = bookSearchInput.value.trim();
        if (searchTerm.length < 2) {
            showAlert('warning', '请输入至少2个字符进行搜索');
            return;
        }
        // 清空当前选项
        bookSelect.innerHTML = '';
        // 发送搜索请求
        fetch(`/book/api/search?q=${encodeURIComponent(searchTerm)}`)
            .then(response => response.json())
            .then(data => {
                bookSelect.innerHTML = '';
                if (data.success && data.books.length > 0) {
                    // 添加找到的图书
                    data.books.forEach(book => {
                        const option = document.createElement('option');
                        option.value = book.id;
                        option.textContent = `${book.title} - ${book.author} (库存: ${book.stock})`;
                        // 如果库存为0,禁用该选项
                        if (book.stock <= 0) {
                            option.disabled = true;
                            option.textContent += ' [无库存]';
                        }
                        bookSelect.appendChild(option);
                    });
                } else {
                    // 未找到图书
                    const option = document.createElement('option');
                    option.value = '';
                    option.textContent = '未找到相关图书';
                    bookSelect.appendChild(option);
                }
            })
            .catch(error => {
                console.error('搜索图书时出错:', error);
                bookSelect.innerHTML = '';
            });
    }
    // 绑定搜索按钮点击事件
    searchBookBtn.addEventListener('click', searchBooks);
    // 绑定回车键搜索
    bookSearchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            searchBooks();
        }
    });
    // 显示提示消息
    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show fixed-top mx-auto mt-3`;
        alertDiv.style.maxWidth = '500px';
        alertDiv.style.zIndex = '9999';
        alertDiv.innerHTML = `
            ${message}
            
        `;
        document.body.appendChild(alertDiv);
        // 3秒后自动消失
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
});