import os
import uuid

from apps.core.models.base import BaseModel
from django.conf import settings
from django.contrib.auth.models import Group
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_ckeditor_5.fields import CKEditor5Field


def user_directory_path(instance, filename):
    ext = filename.split('.')[-1].lower()
    filename = f"{uuid.uuid4().hex[:10]}.{ext}"
    model_name = instance.__class__.__name__.lower()  # 获取模型类名

    if ext in {'jpg', 'jpeg', 'png', 'gif', 'webp'}:
        return os.path.join('upload', model_name, 'images', 'origin', filename)
    return os.path.join('upload', model_name, 'files', filename)


class CreateCommon(models.Model):
    ALLOW_COMMENT_CHOICES = ((True, "允许"), (False, "不允许"))
    class StatusChoices(models.IntegerChoices):
        REVIEW = 99, _('已发布')  # 正式发布
        STORED = 0, _('已入库')  # 新增入库状态 ★
        DRAFT = 1, _('草稿')  # 初始编辑状态
        SUBMITTED = 2, _('已提交')  # 提交待审
        IN_REVIEW = 3, _('审核中')  # 正在审核
        APPROVED = 4, _('已通过')  # 审核通过

        REJECTED = 5, _('已驳回')  # 审核驳回
        ARCHIVED = 6, _('已归档')  # 历史归档
    

    class BooleanFlags(models.IntegerChoices):
        NO = 0, _('否')
        YES = 1, _('是')

    title = models.CharField(max_length=200, verbose_name=_('标题'))
    py_title = models.CharField(max_length=200,
                                blank=True,
                                verbose_name=_('标题拼音'))
    content = CKEditor5Field(verbose_name=_("内容"),
                             blank=True,
                             default='',
                             config_name="full_features")

    # 在模板中生成缩略图URL
    # {{ article.thumb_image.url|replace:"origin","thumbnail"|replace:".", "_336x208." }}

    template = models.FilePathField(
        _("个性模板"),
        path=settings.TEMPLATES_THEME_DIR,  # 动态路径获取
        match=r'.*\.html$',
        recursive=True,
        allow_files=True,
        allow_folders=False,
        blank=True,
        max_length=500)

    allow_comment = models.BooleanField(  # 优化字段类型和命名
        verbose_name="允许评论",
        default=True,
        choices=ALLOW_COMMENT_CHOICES)
    previous_obj = models.ForeignKey('self',
                                     null=True,
                                     blank=True,
                                     on_delete=models.SET_NULL,
                                     verbose_name="上一篇",
                                     related_name="next_obj_rel")

    next_obj = models.ForeignKey('self',
                                 null=True,
                                 blank=True,
                                 on_delete=models.SET_NULL,
                                 verbose_name="下一篇",
                                 related_name="previous_obj_rel")
    status = models.PositiveSmallIntegerField(choices=BaseModel.StatusChoices.choices,
                                              default=BaseModel.StatusChoices.REVIEW,
                                              verbose_name=_('审核状态'))
    hits = models.PositiveIntegerField(verbose_name=_('点击量'),
                                       default=0,
                                       blank=True)
    is_top = models.BooleanField(choices=BooleanFlags.choices,
                                 default=BooleanFlags.NO,
                                 verbose_name=_('推荐'))
    create_time = models.DateTimeField(auto_now_add=True,
                                       verbose_name=_('创建时间'))
    update_time = models.DateTimeField(auto_now=True, verbose_name=_('更新时间'))
    thumb_image = models.ImageField(
        upload_to=user_directory_path,  # 使用字符串引用方法名
        max_length=200,
        verbose_name="缩略图",
        blank=True)
    staff_only = models.BooleanField(
        verbose_name="仅工作人员可见",
        default=False,
    )

    allowed_groups = models.ManyToManyField(Group,
                                            verbose_name="允许访问的用户组",
                                            blank=True,
                                            help_text="选择允许访问此内容的用户组(多选)")

    class Meta:
        abstract = True
        verbose_name = _('通用创建')
        verbose_name_plural = _('通用创建')
        permissions = [
            ("can_view_restricted", "可以查看受限内容"),
        ]

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        """
        自定义保存方法。
        在保存模型实例前，自动去除 title 字段的首尾空格。
        """
        # 如果 title 字段有值，则去除其首尾空格
        if self.title:
            self.title = self.title.strip()

        # 调用父类的 save() 方法以完成标准的保存流程
        super().save(*args, **kwargs)
