from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from mptt.models import MPTTModel, TreeForeignKey


class Comment(MPTTModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE,
                             verbose_name="用户")
    content = models.TextField(max_length=3000, verbose_name="评论内容")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    # 通用外键字段
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    # MPTT树结构
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            null=True,
                            blank=True,
                            related_name='children',
                            verbose_name="父评论")
    is_public = models.BooleanField(default=False, verbose_name="公开显示")

    class MPTTMeta:
        order_insertion_by = ['create_time']

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"
        indexes = [
            models.Index(fields=["content_type", "object_id"]),
        ]

    def __str__(self):
        return f"{self.user} 的评论 ({self.create_time:%Y-%m-%d %H:%M})"

    @classmethod
    def get_tree_list(cls, content_type, object_id, is_public=True):
        """
        获取特定内容的树形结构评论列表
        参数：
            content_type: ContentType实例
            object_id: 目标对象ID
            is_public: 是否公开（默认True）
        返回：
            按层级结构组织的评论列表
        """
        return cls.objects.filter(content_type=content_type,
                                  object_id=object_id,
                                  is_public=is_public).order_by(
                                      'tree_id', 'lft')  # 按MPTT树结构排序
