from django import forms
from django.conf import settings
from django.contrib import admin
from gm_types.doris import STRATEGY_TYPE
from json_editor import JSONEditorWidget

from rank.forms.interpose import InterposeForm, InterposeObjectForm, InterposeObjectFormSet
from rank.models import Strategy, Interpose, InterposeObject
from rank.tasks import export_email_task


class JsonForm(forms.ModelForm):
    class Meta:
        model = Strategy
        fields = '__all__'
        widgets = {
            'json': JSONEditorWidget(schema={}),
        }

    def _check_strategy(self, cleaned_data):
        if cleaned_data['name'] == STRATEGY_TYPE.DOCTOR_ORDER:
            self._check_doctor(cleaned_data)

    def _check_doctor(self, cleaned_data):
        sum = 0
        for v in cleaned_data['json'].values():
            sum += v
        if sum != 1:
            raise forms.ValidationError(
                "权重之和必须等于1"
            )

    def clean(self):
        cleaned_data = super(JsonForm, self).clean()
        self._check_strategy(cleaned_data)



class StrategyAdmin(admin.ModelAdmin):
    form = JsonForm

    actions = ['push_search_cache', 'export_email']

    def export_email(self, request, queryset):
        export_email_task(to_user_email=settings.RANK_EMAIL)

    def push_search_cache(self, request, queryset):
        print('run generate_word_action')
        for item in queryset:
            item.push_search_cache()

    def has_delete_permission(self,request, obj=None):
        return False

    push_search_cache.short_description='推送策略'


class InterposeObjectInline(admin.TabularInline):
    model = InterposeObject
    form = InterposeObjectForm
    formset = InterposeObjectFormSet


class InterposeAdmin(admin.ModelAdmin):
    form = InterposeForm
    inlines = [InterposeObjectInline]

    def get_formsets_with_inlines(self, request, obj=None):
        for inline in self.get_inline_instances(request, obj):
            if isinstance(inline, InterposeObjectInline) and obj is None:
                continue
            yield inline.get_formset(request, obj), inline

    def save_formset(self, request, form, formset, change):
        super(InterposeAdmin, self).save_formset(request, form, formset, change)
        if form.instance and form.instance.pk:
            form.instance.update_obj_ids()


admin.site.register(Strategy, StrategyAdmin)
admin.site.register(Interpose, InterposeAdmin)
