{% extends "admin/change_form.html" %}
{% load static i18n %}

{% block body_main %}
<div style="margin-bottom: 20px;">
    <h2>当前使用主题</h2>
    {% if current_theme %}
    <div style="display: flex; gap: 20px; align-items: center; padding: 15px; border: 2px solid #4CAF50; border-radius: 5px;">
        <img src="{% static current_theme.preview %}" alt="{{ current_theme.name }}" style="max-width: 200px;">
        <div>
            <h3>{{ current_theme.name }} ({{ current_theme.dirname }})</h3>
            <p>作者：{{ current_theme.author }}</p>
            <p>版本：{{ current_theme.version }}</p>
            <p>说明：{{ current_theme.description }}</p>
            <!-- 使用json_script安全传递数据 -->
            {{ current_theme.settings|json_script:"themeSettingsData" }}
            {{ current_settings|json_script:"currentSettingsData" }}
            
            <!-- 主题设置按钮 -->
            {% if current_theme.settings %}
            <button type="button" class="btn btn-warning btn-sm mb-3" data-bs-toggle="modal" 
                    data-bs-target="#themeSettingsModal"
                    data-theme-dirname="{{ current_theme.dirname }}">
                主题设置
            </button>
            {% endif %}
            {% if current_theme.main %}
            <!-- 查看详情按钮 -->
            <button type="button" class="btn btn-info btn-sm mb-3" data-bs-toggle="modal" 
                    data-bs-target="#themeDetailModal" 
                    onclick="showThemeDetail('{{ current_theme.name|escapejs }}', `{{ current_theme.main|escapejs }}`)">
                查看详情
            </button>
            {% endif %}
            
        </div>
    </div>
    {% else %}
    <p>未检测到有效主题配置！</p>
    {% endif %}
</div>

<div>
    <h2>可用主题列表</h2>
    <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;">
        {% for theme in themes %}
        <div style="padding: 15px; border: 2px solid {% if theme.dirname == original.themename %}#4CAF50{% else %}#ddd{% endif %}; border-radius: 5px;">
            <img src="{% static theme.preview %}" alt="{{ theme.name }}" style="max-width: 100%; height: auto;" class="shadow">
            <div style="margin-top: 10px;">
                <h3 class="card-title">{{ theme.name }}</h3>
                <p>目录名：{{ theme.dirname }}</p>
                <p>作者：{{ theme.author }}</p>
                <p>版本：{{ theme.version }}</p>
                <p>说明：{{ theme.description }}</p> 
                <!-- 查看详情按钮 -->
                {% if theme.main %}
                <button type="button" class="btn btn-info btn-sm mb-3" data-bs-toggle="modal" data-bs-target="#themeDetailModal" 
                        onclick="showThemeDetail('{{ theme.name|escapejs }}', `{{ theme.main|escapejs }}`)">
                    查看详情
                </button>
                {% endif %}
                
                <form method="post">
                    {% csrf_token %}
                    <input type="hidden" name="selected_theme" value="{{ theme.dirname }}">
                    <button type="submit" name="_select-theme" class="button" style="background-color: {% if theme.dirname == original.themename %}#4CAF50{% else %}#2196F3{% endif %}; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">
                        {% if theme.dirname == original.themename %}当前使用中{% else %}切换至此主题{% endif %}
                    </button>
                </form>
            </div>
        </div>
        {% empty %}
        <div style="padding: 20px; background-color: #ffe6e6; border: 1px solid #ff8080;">
            <p>未找到任何有效主题！请按以下结构创建主题：</p>
            <pre>
templates/themes/
└── 主题目录名/
    ├── __int__.py      # DjacoreCMS 应用包必用
    ├── theme.jpg      # 主题预览图
    ├── static      # 静态文件
    ├── templates     # 模板文件
    ├── templatetags      # 主题预览图
    ├── themeconfig.json  # 主题元信息文件
    └── themesettings.json  # 个性设置文件
            </pre>
        </div>
        {% endfor %}
    </div>
</div>
{{ block.super }}
<!-- Bootstrap 模态框 -->
<div class="modal fade" id="themeDetailModal" tabindex="-1" aria-labelledby="themeDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="themeDetailModalLabel">主题详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="themeDetailContent">
                <!-- 这里将动态加载主题详情内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
// 显示主题详情的函数
function showThemeDetail(themeName, themeContent) {
    // 设置模态框标题
    document.getElementById('themeDetailModalLabel').textContent = themeName + ' - 详情';
    
    // 设置模态框内容
    document.getElementById('themeDetailContent').innerHTML = themeContent;
}
</script>
<!-- 主题设置模态框 -->
<div class="modal fade" id="themeSettingsModal" tabindex="-1" aria-labelledby="themeSettingsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="themeSettingsModalLabel">主题个性化设置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="themeSettingsForm">
                {% csrf_token %}
                <input type="hidden" name="theme_name" id="themeNameInput">
                
                <div class="modal-body" id="themeSettingsContent">
                    <!-- 动态加载主题设置表单 -->
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="submit" name="_save-theme-settings" class="btn btn-primary">保存设置</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// 当主题设置模态框完全显示后
document.getElementById('themeSettingsModal').addEventListener('shown.bs.modal', function (event) {
    // 获取触发模态框的按钮
    var button = event.relatedTarget;
    // 从按钮的data-*属性中获取主题目录名
    var themeName = button.getAttribute('data-theme-dirname');
    
    // 从json_script创建的元素中获取数据
    var themeSettings = JSON.parse(document.getElementById('themeSettingsData').textContent);
    var currentSettings = JSON.parse(document.getElementById('currentSettingsData').textContent);
    
    console.log('themeName, themeSettings, currentSettings', themeName, themeSettings, currentSettings);
    // 调用函数渲染表单
    loadThemeSettings(themeName, themeSettings, currentSettings);
});
// 加载主题设置表单
function loadThemeSettings(themeName, settings, currentValues) {
    document.getElementById('themeNameInput').value = themeName;
    const settingsContent = document.getElementById('themeSettingsContent');
    let html = '';
    
    settings.forEach(setting => {
        const currentValue = currentValues[setting.name] !== undefined ? 
                            currentValues[setting.name] : setting.default;
        const requiredAttr = setting.required ? 'required' : '';
        const requiredIndicator = setting.required ? '<span class="text-danger">*</span>' : '';
        
        html += `<div class="mb-3">`;
        html += `<label class="form-label">${setting.label} ${requiredIndicator}</label>`;
        
        switch(setting.type) {
            case 'color':
                html += `<input type="color" class="form-control form-control-color" 
                       name="setting_${setting.name}" value="${currentValue}" ${requiredAttr}>`;
                break;
                
            case 'select':
                html += `<select class="form-select" name="setting_${setting.name}" ${requiredAttr}>`;
                setting.options.forEach(option => {
                    const selected = option.value === currentValue ? 'selected' : '';
                    html += `<option value="${option.value}" ${selected}>${option.label}</option>`;
                });
                html += `</select>`;
                break;
                
            case 'checkbox':
                const checked = currentValue ? 'checked' : '';
                html += `<div class="form-check">`;
                html += `<input class="form-check-input" type="checkbox" 
                       name="setting_${setting.name}" value="true" ${checked} ${requiredAttr}>`;
                html += `<label class="form-check-label">${setting.description}</label>`;
                html += `</div>`;
                break;
                
            case 'boolean':
                const boolChecked = currentValue ? 'checked' : '';
                html += `<div class="form-check form-switch">`;
                html += `<input class="form-check-input" type="checkbox" role="switch"
                       name="setting_${setting.name}" value="true" ${boolChecked} ${requiredAttr}>`;
                html += `<label class="form-check-label">${setting.description}</label>`;
                html += `</div>`;
                break;
                
            case 'number':
                html += `<input type="number" class="form-control" 
                       name="setting_${setting.name}" value="${currentValue}" 
                       min="${setting.min || ''}" max="${setting.max || ''}" 
                       step="${setting.step || '1'}" ${requiredAttr}>`;
                break;
                
            case 'range':
                html += `<input type="range" class="form-range" 
                       name="setting_${setting.name}" value="${currentValue}" 
                       min="${setting.min || ''}" max="${setting.max || ''}" 
                       step="${setting.step || '1'}" ${requiredAttr}
                       oninput="this.nextElementSibling.value = this.value">
                       <output>${currentValue}</output>`;
                break;
                
            case 'image':
                html += `<input type="file" class="form-control" 
                       name="setting_${setting.name}" accept="image/*" ${requiredAttr}
                       onchange="previewImage(this)">`;
                html += `<input type="hidden" name="setting_${setting.name}_url" value="${currentValue}">`;
                if (currentValue) {
                    html += `<div class="mt-2">
                            <img src="${currentValue}" style="max-height: 100px;" class="img-thumbnail">
                            <button type="button" class="btn btn-sm btn-danger ms-2" onclick="removeImage(this)">移除</button>
                           </div>`;
                }
                break;
                
            case 'email':
                html += `<input type="email" class="form-control" 
                       name="setting_${setting.name}" value="${currentValue}" 
                       maxlength="${setting.max_length || ''}" ${requiredAttr}>`;
                break;
                
            case 'url':
                html += `<input type="url" class="form-control" 
                       name="setting_${setting.name}" value="${currentValue}" 
                       maxlength="${setting.max_length || ''}" ${requiredAttr}>`;
                break;
                
            case 'date':
                html += `<input type="date" class="form-control" 
                       name="setting_${setting.name}" value="${currentValue}" ${requiredAttr}>`;
                break;
                
            case 'radio':
                setting.options.forEach(option => {
                    const checked = option.value === currentValue ? 'checked' : '';
                    html += `<div class="form-check">
                            <input class="form-check-input" type="radio" 
                                   name="setting_${setting.name}" value="${option.value}" 
                                   ${checked} ${requiredAttr}>
                            <label class="form-check-label">${option.label}</label>
                           </div>`;
                });
                break;
                
            case 'multiple':
                html += `<div class="border p-3 rounded">`;
                setting.options.forEach(option => {
                    const isChecked = Array.isArray(currentValue) ? 
                                    currentValue.includes(option.value) : 
                                    (option.value === currentValue);
                    const checked = isChecked ? 'checked' : '';
                    html += `<div class="form-check">
                            <input class="form-check-input" type="checkbox" 
                                   name="setting_${setting.name}[]" value="${option.value}" 
                                   ${checked}>
                            <label class="form-check-label">${option.label}</label>
                           </div>`;
                });
                html += `</div>`;
                break;
                
            case 'text':
            default:
                html += `<input type="text" class="form-control" 
                       name="setting_${setting.name}" value="${currentValue}" 
                       maxlength="${setting.max_length || ''}" ${requiredAttr}>`;
        }
        
        if (setting.description) {
            html += `<div class="form-text">${setting.description}</div>`;
        }
        
        html += `</div>`;
    });
    
    settingsContent.innerHTML = html;
}

// 图片预览函数
function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = input.parentElement.querySelector('.img-thumbnail');
            if (preview) {
                preview.src = e.target.result;
            } else {
                const html = `<div class="mt-2">
                    <img src="${e.target.result}" style="max-height: 100px;" class="img-thumbnail">
                    <button type="button" class="btn btn-sm btn-danger ms-2" onclick="removeImage(this)">移除</button>
                </div>`;
                input.insertAdjacentHTML('afterend', html);
            }
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// 移除图片函数
function removeImage(button) {
    const container = button.parentElement;
    const fileInput = container.previousElementSibling;
    const hiddenInput = fileInput.previousElementSibling;
    
    fileInput.value = '';
    hiddenInput.value = '';
    container.remove();
}

// 显示主题详情的函数
function showThemeDetail(themeName, themeContent) {
    document.getElementById('themeDetailModalLabel').textContent = themeName + ' - 详情';
    document.getElementById('themeDetailContent').innerHTML = themeContent;
}
</script>
{% endblock %}
