// overdue.js

document.addEventListener('DOMContentLoaded', function() {
    // 归还图书功能
    const returnButtons = document.querySelectorAll('.return-btn');
    const returnModal = document.getElementById('returnModal');
    const returnBookTitle = document.getElementById('returnBookTitle');
    const overdueRemark = document.getElementById('overdueRemark');
    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;
            overdueRemark.value = '';

            // 使用 Bootstrap 的 jQuery 方法显示模态框
            $('#returnModal').modal('show');
        });
    });

    confirmReturnButton.addEventListener('click', function() {
        if (!currentBorrowId) return;

        const remark = overdueRemark.value.trim();

        // 发送归还请求
        fetch(`/borrow/return/${currentBorrowId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                remark: remark
            })
        })
        .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 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);
        });
    });

    // 显示提示消息
    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}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        `;

        document.body.appendChild(alertDiv);

        // 3秒后自动消失
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
});
