"""按充值订单 / 订单 / 用户回填 gsfenhong.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_penalty import resolve_gsfenhong_club_id
from products.models import Gsfenhong


class Command(BaseCommand):
    help = '回填 gsfenhong.club_id'

    def handle(self, *args, **options):
        updated = 0
        with transaction.atomic():
            for row in Gsfenhong.query.all().only('dingdan_id', 'dashouid', 'club_id'):
                cid = resolve_gsfenhong_club_id(dingdan_id=row.dingdan_id, dashouid=row.dashouid)
                if not cid:
                    cid = CLUB_ID_DEFAULT
                if row.club_id != cid:
                    Gsfenhong.query.filter(dingdan_id=row.dingdan_id).update(club_id=cid)
                    updated += 1
        self.stdout.write(self.style.SUCCESS(f'gsfenhong club_id 更新 {updated} 条'))
