"""回填会员体验标记：czjilu.is_trial + huiyuangoumai.has_used_trial。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.services.member_recharge import (
    _order_is_trial_like,
    has_paid_trial_purchase,
)
from products.models import Czjilu, Huiyuangoumai


class Command(BaseCommand):
    help = '回填体验会员订单/权益标记（修复重复购买体验、正式计次错误）'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='仅统计，不写库',
        )

    def handle(self, *args, **options):
        dry_run = bool(options.get('dry_run'))
        czjilu_fixed = 0
        goumai_fixed = 0

        member_orders = list(Czjilu.query.filter(leixing=1, zhuangtai=3))
        with transaction.atomic():
            for order in member_orders:
                club_id = getattr(order, 'club_id', None)
                if _order_is_trial_like(order, club_id) and not order.is_trial:
                    czjilu_fixed += 1
                    if not dry_run:
                        Czjilu.query.filter(dingdan_id=order.dingdan_id).update(is_trial=True)

            goumai_rows = list(Huiyuangoumai.query.all())
            for row in goumai_rows:
                if row.has_used_trial:
                    continue
                if has_paid_trial_purchase(row.yonghu_id, row.huiyuan_id, row.club_id):
                    goumai_fixed += 1
                    if not dry_run:
                        Huiyuangoumai.query.filter(id=row.id).update(has_used_trial=True)

            if dry_run:
                transaction.set_rollback(True)

        mode = 'DRY-RUN' if dry_run else 'APPLIED'
        self.stdout.write(self.style.SUCCESS(
            f'[{mode}] czjilu.is_trial 修复 {czjilu_fixed} 条，'
            f'huiyuangoumai.has_used_trial 修复 {goumai_fixed} 条',
        ))
