"""客户案例栏目与案例详情页。详见 documents/设计方案分析与完善版.md §2.5 页面树结构。"""
from django.db import models
from wagtail.admin.panels import FieldPanel
from wagtail.fields import StreamField
from wagtail.search import index

from apps.core.blocks import COMMON_BLOCKS
from apps.core.models import SEOablePage


class CaseStudyIndexPage(SEOablePage):
    """客户案例栏目列表页，子页面为 CaseStudyPage。"""

    intro = models.TextField(blank=True, verbose_name="栏目简介")

    content_panels = SEOablePage.content_panels + [
        FieldPanel("intro"),
    ]

    subpage_types = ["cases.CaseStudyPage"]
    parent_page_types = ["home.HomePage"]

    class Meta:
        verbose_name = "客户案例栏目页"

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context["case_studies"] = (
            CaseStudyPage.objects.live().descendant_of(self).order_by("-published_at")
        )
        return context


class CaseStudyPage(SEOablePage):
    """单个客户案例详情页。"""

    client_name = models.CharField(max_length=100, verbose_name="客户名称")
    industry = models.CharField(max_length=100, blank=True, verbose_name="所属行业")
    published_at = models.DateTimeField(verbose_name="发布时间")
    summary = models.CharField(max_length=250, blank=True, verbose_name="案例摘要")
    cover_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name="封面图",
    )
    body = StreamField(COMMON_BLOCKS, use_json_field=True, blank=True)

    search_fields = SEOablePage.search_fields + [
        index.SearchField("client_name"),
        index.SearchField("summary"),
        index.SearchField("body"),
    ]

    content_panels = SEOablePage.content_panels + [
        FieldPanel("client_name"),
        FieldPanel("industry"),
        FieldPanel("published_at"),
        FieldPanel("summary"),
        FieldPanel("cover_image"),
        FieldPanel("body"),
    ]

    parent_page_types = ["cases.CaseStudyIndexPage"]
    subpage_types = []

    class Meta:
        verbose_name = "客户案例"
