# 历史罚款 czjilu 从 leixing=4 纠正为 6，club_id 对齐罚单申请人俱乐部

from django.db import migrations

from products.czjilu_types import (
    CZJILU_LEIXING_FAKUAN,
    CZJILU_LEIXING_SHANGJIA,
    is_legacy_penalty_leixing4,
)


def _backfill_penalty_czjilu(apps, schema_editor):
    Czjilu = apps.get_model('products', 'Czjilu')
    Penalty = apps.get_model('orders', 'Penalty')

    for cz in Czjilu.objects.filter(leixing=CZJILU_LEIXING_SHANGJIA).iterator():
        if not is_legacy_penalty_leixing4(cz):
            continue
        updates = {'leixing': CZJILU_LEIXING_FAKUAN}
        shuoming = (cz.shuoming or '')
        if '#fadan:' in shuoming:
            try:
                fadan_id = int(shuoming.split('#fadan:')[1].split()[0].strip())
                fadan = Penalty.objects.filter(id=fadan_id).first()
                if fadan and getattr(fadan, 'ClubID', None):
                    updates['club_id'] = fadan.ClubID
            except (ValueError, IndexError):
                pass
        Czjilu.objects.filter(pk=cz.pk).update(**updates)


class Migration(migrations.Migration):

    dependencies = [
        ('products', '0006_member_trial_fields'),
        ('orders', '0009_penalty_bonus_lock_fields'),
    ]

    operations = [
        migrations.RunPython(_backfill_penalty_czjilu, migrations.RunPython.noop),
    ]
