import random
import string

from django.contrib import admin
from django.http import JsonResponse
from django.urls import path
from django.utils.html import format_html
from django.utils.safestring import mark_safe

from ..models.url_style import UrlStyle
from .mixins import SingletonAdminMixin


@admin.register(UrlStyle)
class UrlStyleAdmin(SingletonAdminMixin, admin.ModelAdmin):
    fieldsets = (
        (
            "选择配置方案",
            {
                "description": mark_safe(
                    """<div class="alert alert-info">
                      <p style="font-weight: bold;font-size:130%">重要提示：</p>
                      <p>这里的URL配置是指的栏目和文章的URL，其他模型的配置暂时使用模型路径。</p>
                      </div>"""
                ),
                "fields": ("url_front", "url_mid", "url_suffix"),
            },
        ),
        (
            "随机字符配置",
            {
                "classes": ("random-config",),
                "fields": ("random_length",),
            },
        ),
        (
            "自定义路径配置",
            {
                "classes": ("custom-config",),
                "fields": (
                    "custom_slug",
                    "custom_article",
                ),
            },
        ),
        ("URL 预览", {"fields": ("url_preview",)}),
        (
            "指定模型路由slug配置",
            {
                "description": mark_safe(
                    """<div class="alert alert-info">
                      <p>指定模型路由是完善上面栏目、文章外的其他模型，为空则默认。</p>
                      </div>"""
                ),
                "fields": ("tag_identifier",),
            },
        ),
    )

    readonly_fields = ("url_preview",)

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path("preview-url/", self.preview_url, name="preview_url"),
        ]
        return custom_urls + urls

    def preview_url(self, request):
        data = request.GET.dict()
        front = data.get("url_front", "model")
        mid = data.get("url_mid", "id")
        suffix = data.get("url_suffix", ".html")
        random_length = data.get("random_length", "6-8")
        custom_slug = data.get("custom_slug", "custom_slug").strip()
        custom_article = data.get("custom_article", "custom_article").strip()
        # 从配置获取最小长度和最大长度
        min_len, max_len = map(int, random_length.split("-"))

        # 生成闭区间随机长度（包含两端点）
        random_int = random.randint(min_len, max_len)
        # 生成包含大小写字母和数字的 6 位随机字符串
        random_str = "".join(
            random.choices(
                string.ascii_lowercase + string.digits, k=random_int  # 62 种字符 (a-z, A-Z, 0-9)
            )
        )
        # 生成列表页URL
        list_url = self._build_list_url(front, mid, suffix, random_str, custom_slug)

        # 生成内容页URL
        detail_url = self._build_detail_url(
            front, mid, suffix, random_str, custom_article, custom_slug
        )

        return JsonResponse({"list_url": list_url, "detail_url": detail_url})

    def _build_list_url(self, front, mid, suffix, random_length, custom_slug):
        base = ""
        if front == "model":
            base = "model_name/"
        elif front == "slug":
            base = "slug/"
        elif front == "moreslug":
            base = "slug1/slug2/"
        elif front == "random":
            base = f"slug/"
        elif front == "custom":
            base = f"{custom_slug}/" if custom_slug else "{custom_slug}/"
        identifier = ""
        if suffix:
            if front == "slug" or front == "moreslug" or front == "random":
                base += "index"
            else:
                identifier = "1" if mid == "id" else "a1b2c3"
        return f"/{base}{identifier}{suffix}"

    def _build_detail_url(self, front, mid, suffix, random_length, custom_article, custom_slug):
        base = ""
        if front == "model":
            base = "model_name/"
        elif front == "slug":
            base = "slug/"
        elif front == "moreslug":
            base = "slug1/slug2/slug/"
        elif front == "random":
            base = f"{random_length}/"
        elif front == "custom":
            base = f"{custom_article}/" if custom_article else "{custom_article}/"

        identifier = "1" if mid == "id" else "a1b2c3"
        return f"/{base}{identifier}{suffix}"

    def url_preview(self, obj):
        return format_html(
            """
            <div id="url_preview">
                <p>列表页URL：<span id="list_url" class="preview-url"></span></p>
                <p>内容页URL：<span id="detail_url" class="preview-url"></span></p>
            </div>
        """
        )

    url_preview.short_description = "URL预览"

    def save_model(self, request, obj, form, change):
        # # 打印表单提交的原始数据
        # print("=== 表单提交的原始数据 ===")
        # for field_name, value in form.cleaned_data.items():
        #     print(f"表单字段 {field_name}: {value}")

        super().save_model(request, obj, form, change)
