"""回填 chufajilu / fadan / duoci_fenhong 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,
    resolve_penalty_club_id,
    resolve_penalty_record_club_id,
)
from orders.models import Penalty, PenaltyRecord
from products.models import DuociFenhong


class Command(BaseCommand):
    help = '回填 PenaltyRecord / Penalty / DuociFenhong 的 club_id'

    def handle(self, *args, **options):
        pr_updated = 0
        fd_updated = 0
        df_updated = 0
        with transaction.atomic():
            for row in PenaltyRecord.query.all().only('id', 'OrderID', 'PlayerID', 'ClubID'):
                cid = resolve_penalty_record_club_id(order_id=row.OrderID, player_id=row.PlayerID)
                if row.ClubID != cid:
                    PenaltyRecord.query.filter(id=row.id).update(ClubID=cid)
                    pr_updated += 1
            for row in Penalty.query.all().only('id', 'RelatedOrderID', 'PenalizedUserID', 'ClubID'):
                cid = resolve_penalty_club_id(
                    order=None,
                    penalized_user_id=row.PenalizedUserID,
                )
                if row.RelatedOrderID:
                    from orders.models import Order
                    o = Order.query.filter(OrderID=row.RelatedOrderID).first()
                    if o:
                        cid = resolve_penalty_club_id(order=o, penalized_user_id=row.PenalizedUserID)
                if row.ClubID != cid:
                    Penalty.query.filter(id=row.id).update(ClubID=cid)
                    fd_updated += 1
            for row in DuociFenhong.query.all().only('huiyuan', 'yonghuid', 'cishu', 'club_id'):
                cid = resolve_gsfenhong_club_id(dashouid=row.yonghuid) or CLUB_ID_DEFAULT
                if row.club_id != cid:
                    DuociFenhong.query.filter(
                        club_id=row.club_id,
                        huiyuan=row.huiyuan,
                        yonghuid=row.yonghuid,
                        cishu=row.cishu,
                    ).update(club_id=cid)
                    df_updated += 1
        self.stdout.write(self.style.SUCCESS(
            f'PenaltyRecord={pr_updated}, Penalty={fd_updated}, DuociFenhong={df_updated}'
        ))
