import os
from concurrent.futures import ThreadPoolExecutor

from django.conf import settings
from django.db import close_old_connections, transaction
from django.db.models import F
from django.db.models.functions import Greatest

# 初始化线程池（建议放在单独文件避免重复初始化）
executor = ThreadPoolExecutor(max_workers=4)


def safe_db_task(task_func):
    """保证数据库连接安全的装饰器"""

    def wrapper(*args, **kwargs):
        try:
            result = task_func(*args, **kwargs)
            return result
        except Exception as e:
            print(f"异步任务执行失败: {str(e)}", exc_info=True)
        finally:
            close_old_connections()  # 关键！关闭当前线程的数据库连接

    return wrapper


def process_keywords(instance):
    """
    处理文章关键词的完整流程
    :param article_instance: 文章实例（需已保存）
    :param min_length: 关键词最小长度
    # 基础用法（使用默认参数）
    process_keywords(article_instance)

    """
    from apps.content.models.tag import Tag
    from apps.core.models.content_config import ContentConfig
    content_config = ContentConfig.get_solo()
    min_length = content_config.min_tag_length
    try:

        with transaction.atomic():

            # 获取新旧标签状态
            old_tags = set(instance.related_tags.all())
            new_tags = []

            # 处理关键词拆分
            keywords = instance.meta_keywords.split(
                ',') if instance.meta_keywords else []

            # 创建或获取标签
            for kw in keywords:
                clean_kw = kw.strip()
                if len(clean_kw) >= min_length:
                    tag, _ = Tag.objects.get_or_create(title=clean_kw)
                    new_tags.append(tag)

            # 更新多对多关系
            instance.related_tags.set(new_tags)
            # 计算标签差异
            current_tags = set(new_tags)
            added_tags = current_tags - old_tags
            removed_tags = old_tags - current_tags
            # 原子更新使用计数
            if added_tags:
                Tag.objects.filter(id__in=[t.id for t in added_tags]).update(
                    usage_count=F('usage_count') + 1)
            if removed_tags:
                try:
                    Tag.objects.filter(
                        id__in=[t.id for t in removed_tags],
                        usage_count__gte=1).update(
                            usage_count=Greatest(F('usage_count') - 1, 0))
                except Exception as e:
                    import traceback
                    traceback.print_exc()  # 打印异常堆栈
    except Exception as e:
        print(f'该内容处理tags发生错误：{e}')


# 缩略图


def creatThumImg(file):
    if not file:
        print('creatThumImg===>没有ThumImg文件')
    print('现在根据来处理{}缩略图'.format(file))
    # path中没有文件名
    # imgpath 为项目目录+media+上面拼接的路径
    try:
        imgpath = os.path.join(settings.BASE_DIR, "media", str(file))

        filename = os.path.basename(imgpath)
        ext = filename.split(".")[-1]
        from PIL import Image
        image = Image.open(imgpath)
        # 生成缩略图
        image = image.resize((336, 208), Image.ANTIALIAS)
        quality_val = 90
        thumname = "{}.{}".format(filename.split(".")[0] + "_336_208", ext)
        thmimg = os.path.join(os.path.dirname(imgpath), thumname)
        image.save(thmimg, quality=quality_val)
    except Exception as e:
        print("websetting.utils.py==>CreatThumImg===>", e)
