import re
from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _  # 添加导入
from django.utils.safestring import mark_safe
from django.core.validators import RegexValidator
from datetime import datetime
from .common import ConfigCommonModel

time_int = datetime.now().strftime("%d%H%M%S")


class CacheConfig(ConfigCommonModel):
    # 内存缓存配置
    caches_setting = models.JSONField(
        verbose_name=_('缓存配置'),
        default=dict,
        blank=True,
        validators=[
            RegexValidator(regex=r'^\{.*\}$',
                           message=_('必须为合法的JSON对象格式（如{"key":"value"}）'),
                           flags=re.DOTALL)
        ],
        help_text=mark_safe(
            _('''
<div class="json-help">
<div style="background:#f8f9fa;padding:15px;border-radius:8px;margin:10px 0">
<p><strong>基础结构：</strong></p>
<p>单项配置:可以在下方选择属于自己的单项进行设置</p>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee;border-radius:4px">
{
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",  # 需保持唯一性以区分多进程内存缓存
        "TIMEOUT": 300,  # 默认缓存超时时间（秒）
        "OPTIONS": {
            "MAX_ENTRIES": 1000,  # 最大缓存条目数
            "CULL_FREQUENCY": 3  # 缓存满时删除比例（1/3）
        }
    }
}
</pre>
<p>多项配置：可以在下方选择属于自己的多个选项进行设置</p>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee;border-radius:4px">
{
    "default": {  // 必需配置
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake"
    },
    "redis_cache": {  // 可选额外缓存
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1"
    }
}
</pre>
</div>

<div style="background:#f8f9fa;padding:15px;border-radius:8px">        
<strong>常用配置示例：</strong>
<details style="margin-top:10px">
<summary style="cursor:pointer;">locmem缓存配置（默认缓存）</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee;border-radius:4px">
{
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",  # 需保持唯一性以区分多进程内存缓存
        "TIMEOUT": 300,  # 默认缓存超时时间（秒）
        "OPTIONS": {
            "MAX_ENTRIES": 1000,  # 最大缓存条目数
            "CULL_FREQUENCY": 3  # 缓存满时删除比例（1/3）
        }
    }
}
</pre>
</details>
<details style="margin-top:10px">
<summary style="cursor:pointer;">Redis缓存配置</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">
{
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",  # 需安装 django-redis 库
        "LOCATION": "redis://:password@127.0.0.1:6379/1",  # 格式：redis://[user:password]@host:port/db
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "SOCKET_CONNECT_TIMEOUT": 5,  # 连接超时时间（秒）
            "SOCKET_TIMEOUT": 5  # 读写超时时间
        },
        "KEY_PREFIX": "myapp"  # 全局缓存键前缀
    }
}
</pre>
</details>

<details style="margin-top:10px">
<summary style="cursor:pointer;">Memcached 缓存</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">
{
    "default": {
        "BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
        "LOCATION": "127.0.0.1:11211",  # 支持多服务器配置（逗号分隔）
        "OPTIONS": {
            "server_max_value_length": 1024 * 1024 * 2  # 单个值最大支持 2MB
        }
    }
}
</pre>  
</details>
<details style="margin-top:10px">
<summary style="cursor:pointer;">数据库缓存配置</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">
{
    "default": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": "my_cache_table",  # 需预先执行 python manage.py createcachetable 创建表
        "TIMEOUT": 600,
        "OPTIONS": {
            "MAX_ENTRIES": 2000
        }
    }
}
</pre>
</details>
<details style="margin-top:10px">
<summary style="cursor:pointer;">文件系统缓存</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">
{
    "default": {
        "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
        "LOCATION": "/var/tmp/django_cache",  # 需确保目录存在且有读写权限
        "TIMEOUT": 3600,
        "OPTIONS": {
            "MAX_ENTRIES": 10000
        }
    }
}
</pre>
</details>
<details style="margin-top:10px">
<summary style="cursor:pointer;">虚拟缓存（DummyCache）</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',  # 仅用于开发环境
    }
}
</pre>
</details>
<details style="margin-top:10px">
<summary style="cursor:pointer;">DjaCore智能三级缓存</summary>
<pre style="margin:10px 0;padding:10px;background:#fff;border:1px solid #eee">
{"locmem": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",  # 需保持唯一性以区分多进程内存缓存
        "TIMEOUT": 300,  # 默认缓存超时时间（秒）
        "OPTIONS": {
            "MAX_ENTRIES": 1000,  # 最大缓存条目数
            "CULL_FREQUENCY": 3  # 缓存满时删除比例（1/3）
        }
    },
    "redis": {
        "BACKEND": "django_redis.cache.RedisCache",  # 需安装 django-redis 库
        "LOCATION": "redis://:password@127.0.0.1:6379/1",  # 格式：redis://[user:password]@host:port/db
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "SOCKET_CONNECT_TIMEOUT": 5,  # 连接超时时间（秒）
            "SOCKET_TIMEOUT": 5,  # 读写超时时间
        },
        "KEY_PREFIX": "myapp"  # 全局缓存键前缀
    },
    "database": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": "my_cache_table",  # 需预先执行 python manage.py createcachetable 创建表
        "TIMEOUT": 600,
        "OPTIONS": {
            "MAX_ENTRIES": 2000
        }
    },
    # 智能路由缓存（业务实际使用的缓存）
    "smart_cache": {
        "BACKEND": "apps.core.cache.router.SmartCache",
        "OPTIONS":
        {  # 参数需置于OPTIONS字段 
            "LAYERS": ["locmem", "redis", "database"],
            "TIMEOUT": 300,
            "JITTER": (60, 120)
        }
    }
}
</pre>
</details>
</div>
</div>
</div>
''')))

    global_cache_enabled = models.BooleanField(
        verbose_name=_('启用全站缓存'),
        default=False,
        help_text=_('启用后将应用HTTP缓存头与视图缓存'))

    # 视图级缓存配置
    index_timeout = models.PositiveIntegerField(
        verbose_name=_('首页缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    channel_timeout = models.PositiveIntegerField(
        verbose_name=_('频道页缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    tag_timeout = models.PositiveIntegerField(
        verbose_name=_('标签页缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    list_timeout = models.PositiveIntegerField(
        verbose_name=_('列表页缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)],
        help_text=_('暂未启用'))
    item_timeout = models.PositiveIntegerField(
        verbose_name=_('内容页缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])

    # 模板缓存配置
    top_main_timeout = models.PositiveIntegerField(
        verbose_name=_('顶部主区域缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    top_top_timeout = models.PositiveIntegerField(
        verbose_name=_('顶部上区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    top_center_timeout = models.PositiveIntegerField(
        verbose_name=_('顶部中区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    top_bottom_timeout = models.PositiveIntegerField(
        verbose_name=_('顶部下区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])

    body_main_timeout = models.PositiveIntegerField(
        verbose_name=_('主体主区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_left_main_timeout = models.PositiveIntegerField(
        verbose_name=_('主体左区整体缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_left_top_timeout = models.PositiveIntegerField(
        verbose_name=_('主体左侧上区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_left_center_timeout = models.PositiveIntegerField(
        verbose_name=_('主体左侧中区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_left_bottom_timeout = models.PositiveIntegerField(
        verbose_name=_('主体左侧下区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_right_main_timeout = models.PositiveIntegerField(
        verbose_name=_('主体右侧整体缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    body_right_top_timeout = models.PositiveIntegerField(
        verbose_name=_('主体右侧上区缓存时间(秒)'),
        default=600,
        validators=[MinValueValidator(0)])
    body_right_center_timeout = models.PositiveIntegerField(
        verbose_name=_('主体右侧中区缓存时间(秒)'),
        default=600,
        validators=[MinValueValidator(0)])
    body_right_bottom_timeout = models.PositiveIntegerField(
        verbose_name=_('主体右侧下区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])

    foot_main_timeout = models.PositiveIntegerField(
        verbose_name=_('底部主区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    foot_top_timeout = models.PositiveIntegerField(
        verbose_name=_('底部上区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])
    foot_center_timeout = models.PositiveIntegerField(
        verbose_name=_('底部中区缓存时间(秒)'),
        default=86400,
        validators=[MinValueValidator(0)])
    foot_bottom_timeout = models.PositiveIntegerField(
        verbose_name=_('底部下区缓存时间(秒)'),
        default=0,
        validators=[MinValueValidator(0)])

    class Meta:
        verbose_name = _('缓存配置')
        verbose_name_plural = _('缓存配置')

    def __str__(self):
        return str(_("系统缓存配置"))
