from django import forms
from django.contrib import admin
from django.db import models

from ..models.static_settings import StaticSettings
from .mixins import SingletonAdminMixin


class StaticSettingsAdmin(SingletonAdminMixin, admin.ModelAdmin):
    formfield_overrides = {
        models.PositiveIntegerField: {'widget': forms.NumberInput(attrs={'style': 'width: 300px;'})},
    }

    # 自定义保存逻辑
    def save_model(self, request, obj, form, change):
        if not change and StaticSettings.objects.exists():
            # 防止通过其他方式创建新实例
            return
        super().save_model(request, obj, form, change)

    # 字段分组布局
    fieldsets = (
        ('', {
            'fields': (),
            'description':
            '''
                <div class="alert alert-warning">
                    <strong>特别说明：</strong>
                    <ul>
                        <li>静态过期时间值为999时表示永不过期，高频保护不受限；</li>
                        <li>当缓存和静态同时启用时注意时间协调.<br>优先级：缓存>高频保护>静态文件；</li>
                        <li>在DEBUG=TRUE或者后台“网站设置”打开调试状态本页所有设置全部失效；</li>
                    </ul>
                    <p>移除操作可用GET触发</p>
                    <pre class="bg-secondary-subtle border border-1 p-3 rounded"><code><strong>url：</strong>host/api/remove_static_file?code=安全码</code></pre>
                </div>
            '''
        }),
        ('基本设置', {
            'fields': ('static_key', 'static_dir'),
        }),
        ('过期时间设置（单位：秒）', {
            'fields': ('high_safe', 'static_index', 'static_node',
                       'static_list', 'static_tag', 'static_item'),
        }),
    )

    # 自定义列表显示（仅在无实例时显示）
    list_display = ('singleton_notice', )

    def singleton_notice(self, obj):
        return "点击此处配置全局静态设置（唯一配置项）"

    singleton_notice.short_description = "系统提示"

    # # 模板控制
    # change_form_template = 'admin/static_settings_change_form.html'

    # # 字段自动填充建议
    # class Media:
    #     css = {'all': ('css/admin_static_settings.css', )}


admin.site.register(StaticSettings, StaticSettingsAdmin)
