from django.db import migrations, models
from django.db.models import Max


def _dedupe_withdrawal_daily(apps, schema_editor):
    Model = apps.get_model('backend', 'WithdrawalDailyStats')
    for row in Model.objects.values('club_id', 'Date', 'WithdrawalType').annotate(max_id=Max('id')):
        Model.objects.filter(
            club_id=row['club_id'],
            Date=row['Date'],
            WithdrawalType=row['WithdrawalType'],
        ).exclude(id=row['max_id']).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('backend', '0002_rename_abnormal_us_create__ee16da_idx_abnormal_us_createt_38f96c_idx'),
    ]

    operations = [
        migrations.AddField(
            model_name='withdrawaldailystats',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='俱乐部ID'),
        ),
        migrations.AlterUniqueTogether(
            name='withdrawaldailystats',
            unique_together=set(),
        ),
        migrations.RunPython(_dedupe_withdrawal_daily, migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='withdrawaldailystats',
            unique_together={('club_id', 'Date', 'WithdrawalType')},
        ),
        migrations.AddIndex(
            model_name='withdrawaldailystats',
            index=models.Index(fields=['club_id', 'Date', 'WithdrawalType'], name='tixian_ri_club_date_type_idx'),
        ),
    ]
