# admin/mixins.py
import threading

from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse

from ..services.django_sys import uWSGI_Reload


class SingletonAdminMixin:
    """单例模式管理Mixin"""

    def changelist_view(self, request, extra_context=None):
        obj = self.model.objects.first()
        if not obj:
            # 自动创建实例并重定向到修改页面
            obj = self.model.objects.create()
            change_url = reverse(
                "admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta.model_name),
                args=(obj.id,),
            )
            return HttpResponseRedirect(change_url)
        return HttpResponseRedirect(
            reverse(
                "admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta.model_name),
                args=(obj.id,),
            )
        )

    def has_add_permission(self, request):
        return not self.model.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False
        # 禁用添加功能

    def get_actions(self, request):
        actions = super().get_actions(request)
        if "delete_selected" in actions:
            del actions["delete_selected"]
        return actions

    def save_model(self, request, obj, form, change):

        super().save_model(request, obj, form, change)
        # # 写入静态文件
        # static_config_path = settings.BASE_DIR / 'config/caches.json'
        # try:
        #     with open(static_config_path, 'w', encoding='utf-8') as f:
        #         json.dump(obj.caches_setting, f, indent=2)
        # except Exception as e:
        #     print(f"缓存配置写入失败: {str(e)}")

        messages.add_message(
            request,
            messages.SUCCESS,
            "配置为重要配置，保存后项目会后台自动重启，在重启完成后生效。",
        )
        thread = threading.Thread(target=uWSGI_Reload)
        thread.start()
