"""回填角色日统计 club_id（按用户归属俱乐部）。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from backend.models import (
    LeaderDailyStats,
    ManagerDailyStats,
    ManagerRenewalDailyStats,
    MerchantDailyStats,
    PlayerDailyStats,
)
from backend.utils import _club_id_for_yonghuid


MODELS = [
    (MerchantDailyStats, 'MerchantID'),
    (PlayerDailyStats, 'PlayerID'),
    (LeaderDailyStats, 'LeaderID'),
    (ManagerDailyStats, 'ManagerID'),
    (ManagerRenewalDailyStats, 'ManagerID'),
]


class Command(BaseCommand):
    help = '回填 5 张角色日统计表的 club_id'

    def handle(self, *args, **options):
        updated = 0
        with transaction.atomic():
            for model, uid_field in MODELS:
                for row in model.query.all().only('id', uid_field, 'club_id'):
                    cid = _club_id_for_yonghuid(getattr(row, uid_field))
                    if row.club_id != cid:
                        model.query.filter(id=row.id).update(club_id=cid)
                        updated += 1
        self.stdout.write(self.style.SUCCESS(f'角色日统计 club_id 更新 {updated} 条'))
