import random
import string

from django.contrib import admin
from django.shortcuts import redirect
from django.urls import path

from ..models.security_code import SecurityCode


def get_random_string(length=8):
    characters = string.ascii_letters + string.digits  # 包含大小写字母和数字
    return ''.join(random.choice(characters) for _ in range(length))


@admin.register(SecurityCode)
class SecurityCodeAdmin(admin.ModelAdmin):
    change_list_template = 'admin/core/security_code/security_code_change_list.html'

    def has_add_permission(self, request):
        return False  # 禁止添加新实例

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

    def changelist_view(self, request, extra_context=None):
        # 生成默认安全码（如果不存在）
        SecurityCode.get_code()
        return super().changelist_view(request, extra_context)

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('refresh/', self.refresh_code),
        ]
        return custom_urls + urls

    def refresh_code(self, request):
        obj = SecurityCode.objects.get(pk=1)
        obj.code = get_random_string(8)  # 可以修改生成位数
        obj.save()
        return redirect('admin:core_securitycode_changelist')
