"""只恢复今日收入（修复后台四个板子显示 0）。"""
from datetime import date

from django.core.management.base import BaseCommand
from django.db.models import Sum

from config.models import DailyIncomeStat
from jituan.services.szjilu_accounting import repopulate_today_income_stats


class Command(BaseCommand):
    help = '重建今日 daily_income_stat（修复财务页今日收入为 0）'

    def add_arguments(self, parser):
        parser.add_argument('--date', type=str, default='', help='日期 YYYY-MM-DD，默认今天')
        parser.add_argument('--yes', action='store_true', help='确认执行')

    def handle(self, *args, **options):
        stat_date = date.fromisoformat(options['date']) if options['date'] else date.today()
        dry_run = not options['yes']

        if dry_run:
            self.stdout.write(self.style.WARNING('【预览】\n'))
        else:
            self.stdout.write(self.style.WARNING('【执行】重建今日收入...\n'))

        r = repopulate_today_income_stats(stat_date, dry_run=dry_run)
        self.stdout.write(f'日期: {r["date"]}')
        self.stdout.write(f'  当前: {r["before_amount"]:.2f} 元 / {r["before_count"]} 笔')
        self.stdout.write(self.style.SUCCESS(
            f'  重建后: {r["after_amount"]:.2f} 元 / {r["after_count"]} 笔'
        ))
        if r['items']:
            for ref, cid, amt, kind in r['items']:
                self.stdout.write(f'    {ref}  {amt}元  club={cid}  ({kind})')

        if not dry_run:
            agg = DailyIncomeStat.objects.filter(date=stat_date).aggregate(
                amt=Sum('total_amount'), cnt=Sum('total_count'),
            )
            self.stdout.write(self.style.SUCCESS(
                f'\n完成。今日日统计: {float(agg["amt"] or 0):.2f} 元 / {int(agg["cnt"] or 0)} 笔'
            ))
            self.stdout.write('请刷新后台财务页。')
        else:
            self.stdout.write(self.style.WARNING(
                '\n确认后: python manage.py repopulate_today_income --yes'
            ))
