{% extends 'base.html' %}

{% block title %}图书花园 - 批量导入{% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/book-import.css') }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script&family=Playfair+Display&display=swap" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="import-container">
    <div class="page-header animate__animated animate__fadeIn">
        <h1 class="fancy-title">图书花园 <span class="subtitle">批量导入</span></h1>
        <a href="{{ url_for('book.book_list') }}" class="btn btn-return">
            <i class="fas fa-arrow-left"></i> 返回图书列表
        </a>
    </div>

    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card animate__animated animate__fadeInUp">
                <div class="card-header">
                    <h4><i class="fas fa-magic sparkle"></i> 添加您的图书收藏</h4>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group file-upload-wrapper">
                            <label for="file" class="elegant-label">选择您的Excel文件</label>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="file" name="file" accept=".xlsx, .xls" required>
                                <label class="custom-file-label" for="file">点击这里选择文件...</label>
                            </div>
                            <small class="form-text text-muted">支持的文件格式: .xlsx, .xls</small>
                        </div>

                        <button type="submit" class="btn btn-primary btn-lg btn-block import-btn">
                            <i class="fas fa-upload"></i> 开始导入
                        </button>
                    </form>

                    <div class="divider">
                        <span class="divider-content"><i class="fas fa-book-open"></i></span>
                    </div>

                    <div class="import-instructions animate__animated animate__fadeIn">
                        <h5 class="instruction-title"><i class="fas fa-leaf"></i> 导入指南</h5>
                        <div class="instruction-content">
                            <p>Excel文件须包含以下字段 (标题行必须与下列完全一致):</p>
                            <ul class="elegant-list">
                                <li class="required-field"><span class="field-name">title</span> - 图书标题 <span class="required-badge">必填</span></li>
                                <li class="required-field"><span class="field-name">author</span> - 作者名称 <span class="required-badge">必填</span></li>
                                <li><span class="field-name">publisher</span> - 出版社</li>
                                <li><span class="field-name">category_id</span> - 分类ID</li>
                                <li><span class="field-name">tags</span> - 标签 (多个标签用逗号分隔)</li>
                                <li><span class="field-name">isbn</span> - ISBN编号</li>
                                <li><span class="field-name">publish_year</span> - 出版年份</li>
                                <li><span class="field-name">description</span> - 图书简介</li>
                                <li><span class="field-name">cover_url</span> - 封面图片URL</li>
                                <li><span class="field-name">stock</span> - 库存数量</li>
                                <li><span class="field-name">price</span> - 价格</li>
                            </ul>
                        </div>

                        <div class="template-download animate__animated animate__pulse animate__infinite animate__slower">
                            <p>不确定如何开始? 下载我们精心准备的模板:</p>
                            <button type="button" id="downloadTemplateBtn" class="btn download-btn">
                                <i class="fas fa-download"></i> 下载Excel模板
                            </button>
                            <!-- 用于显示下载成功或失败的消息 -->
                            <div id="downloadMessage" style="margin-top: 10px; display: none;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="floating-elements">
        <div class="snowflake snowflake-1"></div>
        <div class="snowflake snowflake-2"></div>
        <div class="snowflake snowflake-3"></div>
        <div class="snowflake snowflake-4"></div>
        <div class="flower flower-1"></div>
        <div class="flower flower-2"></div>
    </div>

    <!-- 基本模板隐藏在页面里，以便在无法请求服务器时使用 -->
    <div style="display:none;">
        <a id="directDownloadLink" href="#" download="book_import_template.xlsx"></a>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/book-import.js') }}"></script>
<script>
    // 添加下载模板的JavaScript代码
    document.addEventListener('DOMContentLoaded', function() {
        const downloadBtn = document.getElementById('downloadTemplateBtn');
        const messageDiv = document.getElementById('downloadMessage');
        const directLink = document.getElementById('directDownloadLink');

        if (downloadBtn) {
            downloadBtn.addEventListener('click', function(e) {
                e.preventDefault();

                // 显示下载中状态
                const originalText = downloadBtn.innerHTML;
                downloadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 准备下载中...';
                downloadBtn.disabled = true;

                // 方法1: 使用fetch API请求文件并手动触发下载
                fetch('{{ url_for("book.download_template") }}', {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('下载请求失败，状态码: ' + response.status);
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建临时URL
                    const url = window.URL.createObjectURL(blob);

                    // 设置下载链接
                    directLink.href = url;
                    directLink.download = 'book_import_template.xlsx';

                    // 触发点击
                    directLink.click();

                    // 释放URL对象
                    window.URL.revokeObjectURL(url);

                    // 显示成功消息
                    messageDiv.innerHTML = '<div class="alert alert-success">模板下载成功！</div>';
                    messageDiv.style.display = 'block';

                    // 3秒后隐藏消息
                    setTimeout(() => {
                        messageDiv.style.display = 'none';
                    }, 3000);
                })
                .catch(error => {
                    console.error('下载失败:', error);

                    // 显示错误消息
                    messageDiv.innerHTML = '<div class="alert alert-danger">下载失败，请稍后重试。</div>';
                    messageDiv.style.display = 'block';

                    // 方法2: 如果fetch失败，尝试使用window.open在新标签页下载
                    window.open('{{ url_for("book.download_template") }}', '_blank');
                })
                .finally(() => {
                    // 恢复按钮状态
                    downloadBtn.innerHTML = originalText;
                    downloadBtn.disabled = false;
                });

                // 方法3: 超时后，如果以上方法都失败，提供直接链接让用户手动点击
                setTimeout(function() {
                    if (messageDiv.innerHTML.includes('下载失败') || messageDiv.style.display === 'none') {
                        messageDiv.innerHTML = '<div class="alert alert-warning">下载似乎没有开始。<a href="{{ url_for("book.download_template") }}" target="_blank" download class="alert-link">点击这里</a>手动下载。</div>';
                        messageDiv.style.display = 'block';
                    }
                }, 5000);
            });
        }
    });
</script>
{% endblock %}
