from apps.content.models.article import Article
from apps.content.models.content_manager import ContentManager
from apps.content.models.download import Download
from apps.content.models.image_gallery import ImageGallery
from apps.content.models.wiki import Wiki
from apps.core.models.security_code import SecurityCode
from django.contrib import admin
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import path


class ContentManagerAdmin(admin.ModelAdmin):
    """
    统一内容管理Admin类
    通过重写changelist_view和get_urls实现多模型切换
    """
    # 使用自定义模板（可选）
    change_list_template = 'admin/content/simplified_list.html'

    # 基本配置
    list_per_page = 50
    show_full_result_count = False  # 提升性能

    # 模型映射
    model_mapping = {
        'article': {
            'model': Article,
            'name': '文章',
            'search_fields': ['title', 'py_title', 'content']
        },
        'download': {
            'model': Download,
            'name': '下载',
            'search_fields': ['title', 'py_title']
        },
        'imagegallery': {
            'model': ImageGallery,
            'name': '图库',
            'search_fields': ['title', 'py_title']
        },
        'wiki': {
            'model': Wiki,
            'name': 'Wiki',
            'search_fields': ['title', 'py_title', 'content']
        }
    }

    def has_add_permission(self, request):
        """禁用添加功能"""
        return False

    def has_change_permission(self, request, obj=None):
        """禁用修改功能（因为这是虚拟模型）"""
        return False

    def has_delete_permission(self, request, obj=None):
        """禁用删除功能"""
        return False

    def get_urls(self):
        """
        重写URL配置，添加自定义视图[2,5,6](@ref)
        """
        urls = super().get_urls()

        # 添加自定义URL
        custom_urls = [
            path('simplified-content/',
                 self.admin_site.admin_view(self.simplified_content_view),
                 name='content_simplified_list'),
        ]
        return custom_urls + urls

    def simplified_content_view(self, request):
        """
        统一内容列表视图[1,2](@ref)
        支持模型切换、搜索和筛选
        """
        # 获取参数
        model_type = request.GET.get('model', 'article')
        search_term = request.GET.get('q', '')
        status_filter = request.GET.get('status')
        page_number = request.GET.get('page', 1)  # 获取页码参数，默认为1

        # 获取对应的模型配置
        model_config = self.model_mapping.get(model_type,
                                              self.model_mapping['article'])
        model_class = model_config['model']

        # 构建查询集，只选择必要的字段提升性能
        queryset = model_class.objects.all().only('id', 'title', 'status',
                                                  'create_time', 'update_time',
                                                  'hits', 'is_top')

        # 应用搜索[7](@ref)
        if search_term:
            search_conditions = Q()
            for field in model_config.get('search_fields', ['title']):
                search_conditions |= Q(**{f"{field}__icontains": search_term})
            queryset = queryset.filter(search_conditions)

        # 应用状态筛选
        if status_filter:
            queryset = queryset.filter(status=status_filter)
        # 创建分页器对象：每页显示20条数据[1](@ref)

        paginator = Paginator(queryset, self.list_per_page)

        try:
            page_obj = paginator.get_page(page_number)  # 自动处理无效页码[1](@ref)
        except (PageNotAnInteger, EmptyPage):
            page_obj = paginator.get_page(1)  # 出现异常时显示第一页

        # 准备上下文
        code_config = SecurityCode.get_solo()
        context = {
            **self.admin_site.each_context(request),
            'title': f'简化内容列表 - {model_config["name"]}',
            'page_obj': page_obj,  # 使用page_obj代替objects
            'objects': page_obj.object_list,  # 当前页的数据
            'model_mapping': self.model_mapping,
            'selected_model': model_type,
            'model_display_name': model_config['name'], 
            'code': getattr(code_config, 'code', ''),
            'search_term': search_term,
            'status_filter': status_filter,
            'status_choices': model_class.StatusChoices.choices,
            'opts': self.model._meta,
        }

        return render(request, self.change_list_template, context)

    def changelist_view(self, request, extra_context=None):
        """
        重写默认的changelist_view，跳转到我们的自定义视图[2](@ref)
        """
        return HttpResponseRedirect('simplified-content/')


# 注册虚拟模型
admin.site.register(ContentManager, ContentManagerAdmin)
