from django import forms
from django.contrib import admin

from ..models import UrlPush
from .mixins import SingletonAdminMixin


class UrlPushForm(forms.ModelForm):
    content_models = forms.MultipleChoiceField(
        label="统计模型", widget=forms.CheckboxSelectMultiple, required=False)

    user_app_models = forms.MultipleChoiceField(
        label="用户应用模型", widget=forms.CheckboxSelectMultiple, required=False)

    class Meta:
        model = UrlPush
        fields = '__all__'

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

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

        # 初始化已选值
        if self.instance.content_models:
            self.initial['content_models'] = self.instance.content_models
        if self.instance.user_app_models:
            self.initial['user_app_models'] = self.instance.user_app_models

    def save(self, commit=True):
        instance = super().save(commit=False)
        # 转换表单数据到JSON存储格式
        instance.content_models = self.cleaned_data['content_models']
        instance.user_app_models = self.cleaned_data['user_app_models']
        if commit:
            instance.save()
        return instance


from django.utils.safestring import mark_safe


@admin.register(UrlPush)
class UrlPushAdmin(SingletonAdminMixin, admin.ModelAdmin):
    form = UrlPushForm
    fieldsets = (
        ('使用场景', {
            'fields': ('article_status', )
        }),
        ('内容保存时', {
            'fields': ('content_models', 'user_app_models')
        }),
        ('百度推送', {
            'description':
            mark_safe('''<div class="alert alert-warning">
                      <p>推送URL中的host优先使用网站基础设置中的网站URL进行匹配，对于老版本中没有强制设置网站URL的，将以系统自动获取host进行完整URL的处理。</p>
                      </div>'''),
            'fields': ('baidu_is_active', 'baidu_api')
        }),
    )
