"""回填用户 ClubID（缺省或空时设为 xq 或 user_wx_openid 绑定）。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import UserWxOpenid
from users.business_models import User


class Command(BaseCommand):
    help = '回填 User.ClubID：OpenID 绑定 → user_wx_openid，否则默认 xq'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='仅统计不落库',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        updated = 0
        skipped = 0

        users = User.query.all()
        for user in users:
            current = getattr(user, 'ClubID', None) or ''
            if current and current != CLUB_ID_DEFAULT:
                skipped += 1
                continue

            new_club = CLUB_ID_DEFAULT
            if user.OpenID:
                binding = UserWxOpenid.query.filter(openid=user.OpenID).order_by('id').first()
                if binding:
                    new_club = binding.club_id

            if current == new_club:
                skipped += 1
                continue

            if dry_run:
                self.stdout.write(f'[dry-run] {user.UserUID} -> ClubID={new_club}')
                updated += 1
                continue

            with transaction.atomic():
                user.ClubID = new_club
                user.save(update_fields=['ClubID'])
            updated += 1

        suffix = '（dry-run）' if dry_run else ''
        self.stdout.write(self.style.SUCCESS(f'完成{suffix}：更新 {updated}，跳过 {skipped}'))
