from django.contrib import admin
from django.contrib.admin import action
from api_v1.models import (
    UploadedFile,
    DataSync,
    MDYPlateOrderStaging,
    MDYPlateOrderStagingTiiaUploadFailure,
    MDYPlateOrderStagingQiniuImageUploadAudit,
    MDYPlateOrderStagingQiniuImageUploadState,
    PrintingExternalSyncFailure,
    ApiAuditLog,
)
from .tasks import backup_database


@admin.register(UploadedFile)
class UploadedFileAdmin(admin.ModelAdmin):
    list_display = ['id', 'original_filename', 'owner', 'file_size', 'content_type', 'created_at', 'is_deleted']
    list_filter = ['is_deleted', 'created_at', 'content_type']
    search_fields = ['original_filename', 'owner__username']
    readonly_fields = ['created_at', 'file_size', 'content_type']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    actions = ['backup_database']
    
    def get_queryset(self, request):
        # 在管理界面显示所有文件，包括已删除的
        return super().get_queryset(request).select_related('owner')

    @action(description='备份数据库')
    def backup_database(self, request, queryset):
        backup_database.delay()


@admin.register(DataSync)
class DataSyncAdmin(admin.ModelAdmin):
    list_display = ['id', 'table_name', 'page_index', 'page_size', 'total_count', 'synced_rows', 'last_ctime', 'last_rowid', 'note']
    list_filter = ['table_name', 'created_at']
    search_fields = ['table_name', 'last_rowid', 'note']
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']


@admin.register(MDYPlateOrderStaging)
class MDYPlateOrderStagingAdmin(admin.ModelAdmin):
    list_display = ['id', 'mdy_rowid', 'ctime', 'utime', 'created_at', 'updated_at']
    list_filter = ['created_at']
    search_fields = ['mdy_rowid']
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']


@admin.register(MDYPlateOrderStagingTiiaUploadFailure)
class MDYPlateOrderStagingTiiaUploadFailureAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'run_date',
        'mdy_rowid',
        'staging_id',
        'attempts',
        'last_attempt_at',
        'created_at',
    ]
    list_filter = ['run_date', 'created_at']
    search_fields = ['mdy_rowid', 'error']
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']


@admin.register(MDYPlateOrderStagingQiniuImageUploadAudit)
class MDYPlateOrderStagingQiniuImageUploadAuditAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'mdy_rowid',
        'staging_id',
        'attachment_index',
        'original_host',
        'status',
        'attempts',
        'uploaded_at',
        'last_attempt_at',
        'created_at',
    ]
    list_filter = ['status', 'original_host', 'created_at', 'uploaded_at']
    search_fields = ['mdy_rowid', 'original_url', 'qiniu_url', 'error']
    readonly_fields = [
        'staging',
        'mdy_rowid',
        'source',
        'attachment_index',
        'source_field',
        'original_url',
        'original_host',
        'qiniu_key',
        'qiniu_url',
        'status',
        'attempts',
        'error',
        'file_size',
        'content_type',
        'raw_attachment',
        'started_at',
        'uploaded_at',
        'last_attempt_at',
        'created_at',
        'updated_at',
    ]
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    def has_add_permission(self, request):
        return False


@admin.register(MDYPlateOrderStagingQiniuImageUploadState)
class MDYPlateOrderStagingQiniuImageUploadStateAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'name',
        'last_staging_id',
        'staging_finished',
        'scanned_staging_rows',
        'discovered_image_items',
        'created_audit_rows',
        'existing_audit_rows',
        'last_heartbeat_at',
        'updated_at',
    ]
    readonly_fields = [
        'name',
        'last_staging_id',
        'staging_finished',
        'scanned_staging_rows',
        'discovered_image_items',
        'created_audit_rows',
        'existing_audit_rows',
        'last_heartbeat_at',
        'created_at',
        'updated_at',
    ]
    ordering = ['name']

    def has_add_permission(self, request):
        return False


@admin.register(PrintingExternalSyncFailure)
class PrintingExternalSyncFailureAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'run_date',
        'external_record_id',
        'external_order_id',
        'product_name',
        'attempts',
        'last_attempt_at',
        'created_at',
    ]
    list_filter = ['run_date', 'created_at']
    search_fields = ['external_record_id', 'external_order_id', 'product_name', 'error']
    readonly_fields = [
        'run_date',
        'external_record_id',
        'external_order_id',
        'product_name',
        'error',
        'raw',
        'attempts',
        'last_attempt_at',
        'created_at',
        'updated_at',
    ]
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    def has_add_permission(self, request):
        return False


@admin.register(ApiAuditLog)
class ApiAuditLogAdmin(admin.ModelAdmin):
    """API审计日志管理"""
    list_display = ['id', 'method', 'url', 'username', 'user_id', 'response_status', 'created_at']
    list_filter = ['method', 'response_status', 'created_at']
    search_fields = ['url', 'username']
    readonly_fields = ['url', 'method', 'request_data', 'query_params', 'user_id', 'username', 'response_status', 'created_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    
    # 禁止添加和修改，只允许查看和删除
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False
