"""回填 lunbo / gonggao / popup_page / tupianpeizhi 的 club_id 与 lunbo.page_key。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT
from config.models import Gonggao, Lunbo, PopupPage, Tupianpeizhi


class Command(BaseCommand):
    help = '回填展示配置表的 club_id，并为 lunbo 补 page_key'

    def handle(self, *args, **options):
        updated = {'lunbo_club': 0, 'lunbo_page': 0, 'gonggao': 0, 'popup': 0, 'tupian': 0}

        with transaction.atomic():
            for row in Lunbo.query.all().only('id', 'club_id', 'page_key', 'ImageType'):
                fields = []
                if not row.club_id:
                    row.club_id = CLUB_ID_DEFAULT
                    fields.append('club_id')
                    updated['lunbo_club'] += 1
                if not row.page_key:
                    if row.ImageType == 2:
                        row.page_key = 'dashou_center'
                    else:
                        row.page_key = 'order_pool'
                    fields.append('page_key')
                    updated['lunbo_page'] += 1
                if fields:
                    row.save(update_fields=fields)

            for row in Gonggao.query.filter(club_id='').only('id', 'club_id'):
                Gonggao.query.filter(id=row.id).update(club_id=CLUB_ID_DEFAULT)
                updated['gonggao'] += 1

            for row in PopupPage.query.filter(club_id='').only('id', 'club_id'):
                PopupPage.query.filter(id=row.id).update(club_id=CLUB_ID_DEFAULT)
                updated['popup'] += 1

            for row in Tupianpeizhi.query.filter(club_id='').only('id', 'club_id'):
                Tupianpeizhi.query.filter(id=row.id).update(club_id=CLUB_ID_DEFAULT)
                updated['tupian'] += 1

        self.stdout.write(self.style.SUCCESS(
            f'回填完成: lunbo_club={updated["lunbo_club"]}, lunbo_page={updated["lunbo_page"]}, '
            f'gonggao={updated["gonggao"]}, popup={updated["popup"]}, tupian={updated["tupian"]}'
        ))
