from apps.content.models.tag import Tag
from apps.core.models.base import SEOMixin
from apps.core.models.url_style import UrlStyle
from apps.core.utils.hash import hash_id
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_ckeditor_5.fields import CKEditor5Field

from .common import CreateCommon

# Create your models here.


class Wiki(CreateCommon, SEOMixin):
    ALLOW_COMMENT_CHOICES = ((True, "允许"), (False, "不允许"))
    # 字段名改为小写命名法
    subtitle = models.CharField(max_length=200,
                                verbose_name=_('副标题'),
                                blank=True,
                                default='')
    alias = models.CharField(max_length=200,
                             verbose_name=_('别名'),
                             blank=True,
                             default='')
    category = models.ForeignKey(
        'content.Category',
        on_delete=models.CASCADE,
        verbose_name=_('所属分类'),
        limit_choices_to={'content_type__model': 'wiki'},
        db_index=True  # 显式要求Django创建索引
    )
    basic = CKEditor5Field(verbose_name=_('基本资料'),
                           blank=True,
                           default='',
                           config_name='default')
    editor = models.ForeignKey(  # 修复拼写错误
        User,
        on_delete=models.CASCADE,
        verbose_name="内容编辑",
        related_name="edited_wikis")

    about = models.ManyToManyField('self',
                                   blank=True,
                                   verbose_name=_('相关百科'),
                                   help_text=_('选择相关百科，如果没有可以添加'))
    related_tags = models.ManyToManyField(  # 修复拼写错误
        Tag,
        blank=True,
        related_name="wikis",
        verbose_name="关键词",
        help_text="与模型 Tag 相关联。")
    filtered_tags = models.ManyToManyField("content.Tag",
                                           blank=True,
                                           related_name="filtered_wikis",
                                           verbose_name="动态匹配标签",
                                           help_text="通过标签标题模糊匹配关联的标签")

    def __str__(self):
        return self.title

    class Meta:
        db_table = "wiki"
        verbose_name = _('百科')
        verbose_name_plural = _('百科列表')
        # 优化索引配置
        indexes = [
            # 复合索引（时间字段统一降序）
            models.Index(fields=['category', 'status', '-update_time'],
                         name='wiki_cate_status_utime_desc'),
            models.Index(fields=['category', 'status', '-create_time'],
                         name='wiki_cate_status_ctime_desc'),

            # 状态+降序时间组合
            models.Index(fields=['status', '-update_time'],
                         name='wiki_status_utime_desc'),
            models.Index(fields=['status', '-create_time'],
                         name='wiki_status_ctime_desc'),

            # 独立时间索引（显式降序）
            models.Index(fields=['-create_time'], name='wiki_ctime_desc'),
            models.Index(fields=['-update_time'], name='wiki_utime_desc'),

            # 业务索引（修正字段分隔符）
            models.Index(fields=['hits', 'status'], name='wiki_hits_status'),
            models.Index(fields=['category', 'hits', 'status'],
                         name='wiki_cate_hits_status'),
            models.Index(fields=['title'], name='wiki_title'),
            models.Index(fields=['category', '-update_time', '-id'],
                         name='wiki_cate_utime_id_desc'),
            models.Index(fields=['-update_time', '-id'],
                         name='wiki_utime_id_desc'),
            models.Index(fields=['category'], name='wiki_category_idx'),
        ]

    # 添加性能优化方法
    def get_related_articles(self):
        """预取相关百科的优化查询"""
        return self.about.select_related('category').only(
            'title', 'category__name', 'create_time')

    def get_absolute_url(self):
        '''
        变量为objects
        url_front=[('model', '模型路径（/model/123.html）'),
        ('slug', '单级Slug（/news/123.html）'),
        ('moreslug', '多级Slug（/news/sports/123.html）'),
        ('random', '随机字符（/jklfdsa/1.html）'),
        ('custom', '自定义路径（/mycategory/myarticle/1.shtml）')]
        '''
        #无论前端怎么变量都为tag
        urlconfig = UrlStyle.get_solo()
        prefix = 'wiki'
        if urlconfig.url_mid == 'wiki':
            url_mid = hash_id(self.id)
        else:
            url_mid = self.id
        return f'/wiki/{url_mid}{urlconfig.url_suffix}'

    def delete_with_relations(self):
        # 更新所有指向当前实例的Previous和Next字段
        Wiki.objects.filter(Previous=self).update(Previous=None)
        Wiki.objects.filter(Next=self).update(Next=None)

        # 删除当前实例
        self.delete()
