# admin.py
from django import forms
from django.contrib import admin
from django.utils.safestring import mark_safe

from ..models.admin_settings import AdminSettings
from .mixins import SingletonAdminMixin


class AdminSettingsForm(forms.ModelForm):
    stat_models = forms.MultipleChoiceField(
        label="核心模型", widget=forms.CheckboxSelectMultiple, required=False)

    user_app_models = forms.MultipleChoiceField(
        label="自定义模型", widget=forms.CheckboxSelectMultiple, required=False)
    core_update_models = forms.MultipleChoiceField(
        label="核心模型", widget=forms.CheckboxSelectMultiple, required=False)

    user_update_models = forms.MultipleChoiceField(
        label="自定义模型", widget=forms.CheckboxSelectMultiple, required=False)

    class Meta:
        model = AdminSettings
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 动态设置选项
        self.fields[
            'stat_models'].choices = AdminSettings.get_content_models_choices(
            )
        self.fields[
            'user_app_models'].choices = AdminSettings.get_user_space_choices(
            )

        # 初始化已选值
        if self.instance.stat_models:
            self.initial['stat_models'] = self.instance.stat_models
        if self.instance.user_app_models:
            self.initial['user_app_models'] = self.instance.user_app_models
        # 新增选项配置
        self.fields[
            'core_update_models'].choices = AdminSettings.get_core_update_choices(
            )
        self.fields[
            'user_update_models'].choices = AdminSettings.get_user_update_choices(
            )

        # 初始化新字段
        if self.instance.core_update_models:
            self.initial[
                'core_update_models'] = self.instance.core_update_models
        if self.instance.user_update_models:
            self.initial[
                'user_update_models'] = self.instance.user_update_models

    def save(self, commit=True):
        instance = super().save(commit=False)
        if hasattr(instance, 'admin_base_path') and instance.admin_base_path:
            if not instance.admin_base_path.endswith('/'):
                instance.admin_base_path += '/'
        # 转换表单数据到JSON存储格式
        instance.stat_models = self.cleaned_data['stat_models']
        instance.user_app_models = self.cleaned_data['user_app_models']
        instance.core_update_models = self.cleaned_data['core_update_models']
        instance.user_update_models = self.cleaned_data['user_update_models']
        if commit:
            instance.save()
        return instance


@admin.register(AdminSettings)
class AdminSettingsAdmin(SingletonAdminMixin, admin.ModelAdmin):
    form = AdminSettingsForm
    fieldsets = (('', {
        'description':
        mark_safe('''<div class="alert alert-warning">
                      <p style="color: red; font-weight: bold;font-size:130%">重要提示：</p>
                      <p>后台配置为底层操作，保存后系统会自动重启。配置将会在重启后生效，后台管理路径会失效</p>
                </div>'''),
        'fields': ()
    }), ('基础配置', {
        'fields': ('admin_base_path', 'admin_site_name')
    }), ('后台首页全局统计', {
        'description':
        mark_safe('''<div class="alert alert-info">
                      <p>此设置为控制后台首页系统信息--全局数据内的显示模型。这里将会显示数据的总数</p>
                </div>'''),
        'fields': (
            'stat_models',
            'user_app_models',
        )
    }), ('后台内容更新统计', {
        'description':
        mark_safe('''<div class="alert alert-info">
                      <p>此设置为控制后台首页内容发布统计显示的模型。这里将会显示几天内的模型变化数</p>
                      <p>用户空间（/users_space/apps/下）自建模型，需要继承BseModel(from apps.core.models.base import BaseModel),或者在建立模型时确认字段有"update_time"和“status”，且有“status=99”的选项</p>
                </div>'''),
        'fields': (
            'update_tracking_days',
            'core_update_models',
            'user_update_models',
        )
    }))
