"""
阿龙电竞 - 收支记录定时任务
处理收支记录表的每日清零
固定使用ID=1的记录
"""

from celery import shared_task
from django.db import transaction
from django.utils import timezone
from datetime import datetime
from decimal import Decimal
import logging

# 导入模型
from peizhi.models import Szjilu
from utils.celery_utils import log_task_execution, rollback_on_failure

logger = logging.getLogger(__name__)

@shared_task
@rollback_on_failure("收支记录每日清零")
def daily_sz_reset_task():
    """
    收支记录每日清零 - 每天凌晨0点5分执行
    清零收支记录表的今日相关字段，固定使用ID=1的记录
    """
    try:
        with transaction.atomic():
            # 获取今天的日期
            today = datetime.now().strftime('%Y-%m-%d')

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

            # 查询ID=1的收支记录，如果不存在则创建
            try:
                szjilu = Szjilu.objects.get(id=1)
                logger.info(f"找到ID=1的收支记录")
            except Szjilu.DoesNotExist:
                # 创建ID=1的初始记录
                szjilu = Szjilu.objects.create(
                    id=1,
                    zongsy=Decimal('0.00'),
                    zongls=Decimal('0.00'),
                    zongzc=Decimal('0.00'),
                    jrzc=Decimal('0.00'),
                    jrls=Decimal('0.00')
                )
                logger.info(f"创建ID=1的收支记录")

            # 记录清零前的值（用于日志）
            old_jrzc = szjilu.jrzc
            old_jrls = szjilu.jrls

            # 清零今日字段
            szjilu.jrzc = Decimal('0.00')
            szjilu.jrls = Decimal('0.00')
            szjilu.save(update_fields=['jrzc', 'jrls', 'update_time'])

            logger.info(f"收支记录清零完成，今日支出原值: {old_jrzc}，今日流水原值: {old_jrls}")

            result_msg = f"收支记录清零完成 - 日期: {today}, 记录ID: {szjilu.id}"

            log_task_execution("收支记录每日清零", True, result_msg)

            return {
                "success": True,
                "date": today,
                "record_id": szjilu.id,
                "jrzc_cleared": True,
                "jrls_cleared": True,
                "old_jrzc": str(old_jrzc),
                "old_jrls": str(old_jrls),
                "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
        }