"""
从订单/充值表恢复 daily_income_stat（不删订单，只重算统计表）。
repair/rebuild 搞乱后用这个，不要用 repair_wechat_income。

  预览：python manage.py restore_daily_income_from_orders
  执行：python manage.py restore_daily_income_from_orders --yes
"""
from datetime import date

from django.core.management.base import BaseCommand

from jituan.services.szjilu_accounting import restore_daily_income_from_orders


class Command(BaseCommand):
    help = '从订单/充值表恢复日收入统计（订单不动）'

    def add_arguments(self, parser):
        parser.add_argument('--since-year', type=int, default=0)
        parser.add_argument('--until-year', type=int, default=0)
        parser.add_argument('--yes', action='store_true')

    def handle(self, *args, **options):
        until_year = options['until_year'] or date.today().year
        since_year = options['since_year'] or (until_year - 1)
        dry_run = not options['yes']

        if dry_run:
            self.stdout.write(self.style.WARNING('【预览】订单数据不会动\n'))
        else:
            self.stdout.write(self.style.WARNING('【执行】按订单/充值重算日统计...\n'))

        r = restore_daily_income_from_orders(since_year, until_year, dry_run=dry_run)
        self.stdout.write(f'范围: {r["since_year"]} ~ {r["until_year"]}')
        self.stdout.write(f'  支付笔数(订单表): {r["payment_rows"]}')
        self.stdout.write(f'  日统计行数:       {r["daily_rows"]}')
        self.stdout.write(f'  当前 daily 合计:  {r["before_daily_total"]:.2f} 元')
        self.stdout.write(self.style.SUCCESS(
            f'  恢复后 daily 合计: {r["after_daily_total"]:.2f} 元'
        ))

        if dry_run:
            self.stdout.write(self.style.WARNING(
                '\n确认: python manage.py restore_daily_income_from_orders --yes'
            ))
        else:
            self.stdout.write(self.style.SUCCESS('\n完成。推 kefu 后刷新财务页。'))
