from django import forms
from django.contrib import admin
from django.db import models
from django.utils.safestring import mark_safe
from django_json_widget.widgets import JSONEditorWidget

from ..models import SearchConfig
from .mixins import SingletonAdminMixin


class SearchConfigForm(forms.ModelForm):

    content_models = forms.MultipleChoiceField(
        label="内容模型", widget=forms.CheckboxSelectMultiple, required=False)
    content_fields = forms.MultipleChoiceField(
        label="可选字段", widget=forms.CheckboxSelectMultiple, required=False)

    class Meta:
        model = SearchConfig
        fields = '__all__'

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

        # 动态设置选项
        self.fields[
            'content_models'].choices = SearchConfig.get_content_models_choices(
            )
        self.fields[
            'content_fields'].choices = SearchConfig.get_available_fields()

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

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


@admin.register(SearchConfig)
class SearchConfigAdmin(SingletonAdminMixin, admin.ModelAdmin):
    form = SearchConfigForm
    formfield_overrides = {
        models.JSONField: {
            'widget':
            JSONEditorWidget(
                mode='code',  # 直接显示代码编辑模式
                options={
                    'modes': ['code'],  # 禁用模式切换
                    'theme': 'github',  # 更简洁的亮色主题
                    'lineNumbers': False,
                    'indentation': 2,
                    'autoFormat': True  # 自动格式化
                },
                height='400px',  # 适当降低高度
            )
        }
    }
    fieldsets = (
        ('', {
            'description':
            mark_safe('''
                <div class="alert alert-warning">
                    <strong>注意：</strong>强大的功能需要更多的性能开销，资源开源与模型的选择成正比，请合理的选择自己需要的模型。
                </div>
            '''),
            'fields': ()
        }),
        ("内容模型", {
            'fields': (
                'content_models',
                'content_fields',
            ),
        }),
        ("自定义模型", {
            'fields': ('user_space_search', ),
        }),
        ("辅助", {
            'fields': ('update_switch', 'search_engine'),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # 获取可用模型选项
        choices = SearchConfig.get_user_space_choices()
        # 构建help_text内容
        help_text = '''格式示例:<br>
        {<br>
        &nbsp;&nbsp;"app.model1": {<br>
        &nbsp;&nbsp;&nbsp;&nbsp;"search_fields": ["field1","field2"],<br>
        &nbsp;&nbsp;&nbsp;&nbsp;"display_fields": ["field1","field3"]<br>
        &nbsp;&nbsp;},<br>
        &nbsp;&nbsp;"app.model2": {<br>
        &nbsp;&nbsp;&nbsp;&nbsp;"search_fields": ["field3"],<br>
        &nbsp;&nbsp;&nbsp;&nbsp;"display_fields": ["field3","field4"]<br>
        &nbsp;&nbsp;}<br>
        }<br><br>
        可用模型:<br>'''

        # 添加模型选项到help_text
        for app_model, verbose_name in choices:
            help_text += f'&nbsp;&nbsp;{app_model}: {verbose_name}<br>'
        # 更新字段的help_text
        form.base_fields['user_space_search'].help_text = mark_safe(help_text)
        return form
