"""按用户 ClubID 回填提现流水 club_id。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT
from jituan.services.club_user import get_user_club_id
from users.business_models import User
from users.models import TixianAutoRecord, Tixianjilu, TixianShenheJilu


class Command(BaseCommand):
    help = '回填 tixianjilu / tixian_shenhe_jilu / tixian_auto_record 的 club_id'

    def handle(self, *args, **options):
        uid_club = {}
        for u in User.query.all().only('UserUID', 'ClubID'):
            uid_club[u.UserUID] = get_user_club_id(u)

        updated = {'jilu': 0, 'shenhe': 0, 'auto': 0}

        with transaction.atomic():
            for row in Tixianjilu.query.all().only('id', 'yonghuid', 'club_id'):
                cid = uid_club.get(row.yonghuid) or CLUB_ID_DEFAULT
                if row.club_id != cid:
                    Tixianjilu.query.filter(id=row.id).update(club_id=cid)
                    updated['jilu'] += 1

            for row in TixianShenheJilu.query.all().only('id', 'yonghuid', 'club_id'):
                cid = uid_club.get(row.yonghuid) or CLUB_ID_DEFAULT
                if row.club_id != cid:
                    TixianShenheJilu.query.filter(id=row.id).update(club_id=cid)
                    updated['shenhe'] += 1

            for row in TixianAutoRecord.query.all().only('id', 'yonghuid', 'club_id'):
                cid = uid_club.get(row.yonghuid) or CLUB_ID_DEFAULT
                if row.club_id != cid:
                    TixianAutoRecord.query.filter(id=row.id).update(club_id=cid)
                    updated['auto'] += 1

        self.stdout.write(self.style.SUCCESS(
            f'回填完成: jilu={updated["jilu"]}, shenhe={updated["shenhe"]}, auto={updated["auto"]}'
        ))
