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


def _dedupe_popuppage(apps, schema_editor):
    PopupPage = apps.get_model('config', 'PopupPage')
    for row in PopupPage.objects.values('club_id', 'page_key').annotate(max_id=Max('id')):
        PopupPage.objects.filter(
            club_id=row['club_id'],
            page_key=row['page_key'],
        ).exclude(id=row['max_id']).delete()


def _dedupe_tupianpeizhi(apps, schema_editor):
    Tupianpeizhi = apps.get_model('config', 'Tupianpeizhi')
    for row in Tupianpeizhi.objects.values('club_id', 'ImageType').annotate(max_id=Max('id')):
        Tupianpeizhi.objects.filter(
            club_id=row['club_id'],
            ImageType=row['ImageType'],
        ).exclude(id=row['max_id']).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('config', '0005_szjilu_club_id'),
    ]

    operations = [
        migrations.AddField(
            model_name='gonggao',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='俱乐部ID'),
        ),
        migrations.AddField(
            model_name='lunbo',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='俱乐部ID'),
        ),
        migrations.AddField(
            model_name='lunbo',
            name='page_key',
            field=models.CharField(
                db_index=True, default='order_pool', max_length=32,
                verbose_name='页面标识(order_pool/accept_order/merchant_home/dashou_center)',
            ),
        ),
        migrations.AddField(
            model_name='popuppage',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='俱乐部ID'),
        ),
        migrations.AddField(
            model_name='tupianpeizhi',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='俱乐部ID'),
        ),
        migrations.AlterUniqueTogether(
            name='popuppage',
            unique_together=set(),
        ),
        migrations.AlterField(
            model_name='popuppage',
            name='page_key',
            field=models.CharField(db_index=True, max_length=50, verbose_name='页面标识'),
        ),
        migrations.RunPython(_dedupe_popuppage, migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='popuppage',
            unique_together={('club_id', 'page_key')},
        ),
        migrations.RunPython(_dedupe_tupianpeizhi, migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='tupianpeizhi',
            unique_together={('club_id', 'ImageType')},
        ),
        migrations.AddIndex(
            model_name='lunbo',
            index=models.Index(fields=['club_id', 'page_key', 'ImageType'], name='lunbo_club_page_type_idx'),
        ),
    ]
