"""
阿龙电竞 - 用户定时任务
处理每日/每月清零等用户相关定时任务
完整版本，包含所有异常处理
"""

from celery import shared_task
from django.db import transaction
from django.db.models import F, Q
from django.utils import timezone
from datetime import datetime
import logging

# 导入模型
from yonghu.models import UserDashou, UserShangjia, UserGuanshi
from utils.celery_utils import log_task_execution, rollback_on_failure

logger = logging.getLogger(__name__)

@shared_task
@rollback_on_failure("每日清零任务")
def daily_reset_task():
    """
    每日清零任务 - 每天凌晨0点执行
    清零打手、商家、管事的今日相关字段
    """
    try:
        with transaction.atomic():
            start_time = timezone.now()
            today = datetime.now().strftime('%Y-%m-%d')

            logger.info(f"开始执行每日清零任务，日期: {today}")

            # 1. 清零打手今日数据
            dashou_updated = UserDashou.objects.filter(
                Q(jinrijiedan__gt=0) | Q(jinrishouyi__gt=0)
            ).update(
                jinrijiedan=0,
                jinrishouyi=0
            )

            logger.info(f"打手今日数据清零完成，影响记录: {dashou_updated}条")

            # 2. 清零商家今日数据
            shangjia_updated = UserShangjia.objects.filter(
                Q(jinridingdan__gt=0) | Q(jinriliushui__gt=0)
            ).update(
                jinridingdan=0,
                jinriliushui=0
            )

            logger.info(f"商家今日数据清零完成，影响记录: {shangjia_updated}条")

            # 3. 清零管事今日数据
            guanshi_updated = UserGuanshi.objects.filter(
                jinrichongzhi__gt=0
            ).update(
                jinrichongzhi=0
            )

            logger.info(f"管事今日数据清零完成，影响记录: {guanshi_updated}条")

            end_time = timezone.now()
            duration = (end_time - start_time).total_seconds()

            # 记录执行结果
            result_msg = (
                f"每日清零完成 - 日期: {today}, "
                f"打手: {dashou_updated}条, "
                f"商家: {shangjia_updated}条, "
                f"管事: {guanshi_updated}条, "
                f"耗时: {duration:.2f}秒"
            )

            log_task_execution("每日清零任务", True, result_msg)

            return {
                "success": True,
                "date": today,
                "updated_dashou": dashou_updated,
                "updated_shangjia": shangjia_updated,
                "updated_guanshi": guanshi_updated,
                "duration_seconds": duration,
                "message": result_msg
            }

    except Exception as e:
        error_msg = f"每日清零任务失败: {str(e)}"
        logger.error(error_msg)
        log_task_execution("每日清零任务", False, error_msg)

        return {
            "success": False,
            "error": str(e),
            "date": datetime.now().strftime('%Y-%m-%d'),
            "message": error_msg
        }

@shared_task
@rollback_on_failure("每月清零任务")
def monthly_reset_task():
    """
    每月清零任务 - 每月1日凌晨0点执行
    清零打手、商家、管事的本月相关字段
    """
    try:
        with transaction.atomic():
            start_time = timezone.now()
            current_month = datetime.now().strftime('%Y-%m')

            logger.info(f"开始执行每月清零任务，月份: {current_month}")

            # 1. 清零打手本月数据
            dashou_updated = UserDashou.objects.filter(
                Q(jinyuejiedan__gt=0) | Q(jinyueshouyi__gt=0)
            ).update(
                jinyuejiedan=0,
                jinyueshouyi=0
            )

            logger.info(f"打手本月数据清零完成，影响记录: {dashou_updated}条")

            # 2. 清零商家本月数据
            shangjia_updated = UserShangjia.objects.filter(
                Q(jinyuedingdan__gt=0) | Q(jinyueliushui__gt=0)
            ).update(
                jinyuedingdan=0,
                jinyueliushui=0
            )

            logger.info(f"商家本月数据清零完成，影响记录: {shangjia_updated}条")

            # 3. 清零管事本月数据
            guanshi_updated = UserGuanshi.objects.filter(
                jinyuechongzhi__gt=0
            ).update(
                jinyuechongzhi=0
            )

            logger.info(f"管事本月数据清零完成，影响记录: {guanshi_updated}条")

            end_time = timezone.now()
            duration = (end_time - start_time).total_seconds()

            # 记录执行结果
            result_msg = (
                f"每月清零完成 - 月份: {current_month}, "
                f"打手: {dashou_updated}条, "
                f"商家: {shangjia_updated}条, "
                f"管事: {guanshi_updated}条, "
                f"耗时: {duration:.2f}秒"
            )

            log_task_execution("每月清零任务", True, result_msg)

            return {
                "success": True,
                "month": current_month,
                "updated_dashou": dashou_updated,
                "updated_shangjia": shangjia_updated,
                "updated_guanshi": guanshi_updated,
                "duration_seconds": duration,
                "message": result_msg
            }

    except Exception as e:
        error_msg = f"每月清零任务失败: {str(e)}"
        logger.error(error_msg)
        log_task_execution("每月清零任务", False, error_msg)

        return {
            "success": False,
            "error": str(e),
            "month": datetime.now().strftime('%Y-%m'),
            "message": error_msg
        }