# admin/mixins.py
from apps.content.models.category import Category
from apps.core.models.base import BaseModel
from apps.core.models.security_code import SecurityCode
from apps.core.utils.get_true_host import get_true_host
from django.contrib import admin, messages
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _


class SingletonAdminMixin:

    def get_queryset(self, request):
        return (
            super()
            .get_queryset(request)
            .select_related("category")
            .only(
                "id",
                "title",
                "category__id",
                "category__slug",
                "status",
                "create_time",
                "update_time",
            )
        )

    prepopulated_fields = {"slug": ("title",)}
    # 列表页配置
    list_display = (
        "id",
        "title_truncated",
        "category",
        "status_badge",
        "create_time",
        "update_time",
        "extended_functionality",
    )
    list_display_links = ("title_truncated",)
    # 只读字段
    readonly_fields = ("create_time", "update_time", "hits", "editor")
    preserve_filters = True
    # 关闭顶部搜索结果中的完整计数显示
    show_full_result_count = False
    # 分页配置
    list_per_page = 20

    # 自定义字段显示
    @admin.display(description=_("标题"), ordering="title")
    def title_truncated(self, obj):
        return obj.title[:35] + "..." if len(obj.title) > 33 else obj.title

    @admin.display(description=_("状态"))
    def status_badge(self, obj):
        from django.utils.html import format_html

        colors = {
            0: "#666",  # 已入库
            1: "#999",  # 草稿
            2: "#ffc107",  # 已提交
            3: "#17a2b8",  # 审核中
            4: "#28a745",  # 已通过
            5: "#dc3545",  # 已驳回
            6: "#6c757d",  # 已归档
            99: "#007bff",  # 已发布
        }
        return format_html(
            '<span style="padding:2px 8px; border-radius:12px; background:{}; color:white" class="nowrap">{}</span>',
            colors[obj.status],
            obj.get_status_display(),
        )

    @admin.display(description=_("扩展功能"))
    def extended_functionality(self, obj):
        code_config = SecurityCode.get_solo()
        code = getattr(code_config, "code", "")
        html = format_html(
            '<nav aria-label="breadcrumb" class="nowrap"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="{}" target="_blank">浏览</a></li><li class="breadcrumb-item"><a href="#" class="remove_static_a" data-url="{}" data-code="{}" data-object-id="{}">移除静态</a></li></ol></nav>',
            obj.get_absolute_url(),  # 对应第一个 {}
            obj.get_absolute_url(),  # 对应第二个 {}
            code,  # 对应第三个 {}
            obj.id,  # 对应第四个 {}
        )
        return html

    extended_functionality.allow_tags = True  # 允许HTML渲染

    # 自动填充逻辑
    def save_model(self, request, obj, form, change):
        if not obj.editor_id:
            obj.editor = request.user
        obj.save()
        super().save_model(request, obj, form, change)
        from apps.core.models import UrlPush

        url_push_config = UrlPush.get_solo()
        model_name = obj.__class__  # 获取模型名称
        mes = ""
        if model_name in url_push_config.get_active_models():
            base_url = get_true_host(request)
            push_status = UrlPush.push_url([f"{base_url}{obj.get_absolute_url()}"])
            mes += url_push_config.check_baidu_push_status(push_status)
            messages.success(request, mes)

    # 定义所有状态对应的动作
    actions = [
        "make_published",
        "make_stored",
        "make_draft",
        "make_submitted",
        "make_in_review",
        "make_approved",
        "make_rejected",
        "archive_selected",
    ]

    # 已发布 (原 make_published)
    @admin.action(description=_("发布选中条目"))
    def make_published(self, request, queryset):
        # updated = queryset.update(status=BaseModel.StatusChoices.REVIEW)
        # self.message_user(request, f"成功发布 {updated} 个条目")
        for obj in queryset:
            obj.status = BaseModel.StatusChoices.REVIEW
            obj.save()  # 这会触发 pre_save 和 post_save 信号
        self.message_user(request, f"成功发布 {queryset.count()} 个条目")

    # 已入库 (STORED)
    @admin.action(description=_("设为已入库"))
    def make_stored(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.STORED)
        self.message_user(request, f"成功将 {updated} 个条目设为已入库状态")

    # 草稿 (DRAFT)
    @admin.action(description=_("设为草稿"))
    def make_draft(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.DRAFT)
        self.message_user(request, f"成功将 {updated} 个条目设为草稿状态")

    # 已提交 (SUBMITTED)
    @admin.action(description=_("提交选中条目"))
    def make_submitted(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.SUBMITTED)
        self.message_user(request, f"成功提交 {updated} 个条目")

    # 审核中 (IN_REVIEW)
    @admin.action(description=_("设为审核中"))
    def make_in_review(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.IN_REVIEW)
        self.message_user(request, f"{updated} 个条目已进入审核流程")

    # 已通过 (APPROVED)
    @admin.action(description=_("审核通过选中条目"))
    def make_approved(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.APPROVED)
        self.message_user(request, f"成功通过 {updated} 个条目的审核")

    # 已驳回 (REJECTED)
    @admin.action(description=_("驳回选中条目"))
    def make_rejected(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.REJECTED)
        self.message_user(request, f"已驳回 {updated} 个条目")

    # 已归档 (原 archive_selected)
    @admin.action(description=_("归档选中条目"))
    def archive_selected(self, request, queryset):
        updated = queryset.update(status=BaseModel.StatusChoices.ARCHIVED)
        self.message_user(request, f"已归档 {updated} 个条目")

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # 捕获 URL 中的 category_id 参数
        category_id = request.GET.get("category_id")
        if category_id:
            # 将参数注入表单字段初始值
            form.base_fields["category"].initial = Category.objects.get(id=category_id)
        return form
