"""为每个启用俱乐部初始化 szjilu 收支流水行。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from config.models import Szjilu
from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import Club
from jituan.services.szjilu_accounting import normalize_szjilu_club_id


class Command(BaseCommand):
    help = '为每个俱乐部创建 szjilu 收支流水行（已有则跳过）'

    def add_arguments(self, parser):
        parser.add_argument(
            '--club-id',
            type=str,
            default='',
            help='仅处理指定 club_id，默认处理全部启用俱乐部',
        )

    def handle(self, *args, **options):
        club_id = (options.get('club_id') or '').strip()
        if club_id:
            club_ids = [normalize_szjilu_club_id(club_id)]
        else:
            club_ids = list(
                Club.query.filter(status=1).values_list('club_id', flat=True)
            )
            if CLUB_ID_DEFAULT not in club_ids:
                club_ids.append(CLUB_ID_DEFAULT)

        created = 0
        with transaction.atomic():
            for cid in club_ids:
                _, was_created = Szjilu.objects.get_or_create(club_id=cid)
                if was_created:
                    created += 1
                    self.stdout.write(f'创建 szjilu: club_id={cid}')
        self.stdout.write(self.style.SUCCESS(f'完成，新建 {created} 条 szjilu 记录'))
