from django.core.management.base import BaseCommand, CommandError

from basic_info import models as basic_models
from business.external_finance_sync import sync_customer_finance
from django.conf import settings


class Command(BaseCommand):
    help = '按指定客户名从 HaoBuYe 外部财务接口同步收款/退款到 ReceiptOrder'

    def add_arguments(self, parser):
        parser.add_argument('customer_name', type=str, help='外部客户名称（精确匹配）')
        parser.add_argument('--operator-id', type=int, default=None, help='本地经办人 Employee.id')
        parser.add_argument(
            '--allow-create-customer',
            action='store_true',
            default=False,
            help='当本地客户不存在时自动创建',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            default=False,
            help='仅拉取和校验，不实际写入',
        )
        parser.add_argument(
            '--force-update',
            action='store_true',
            default=False,
            help='当已有记录与外部数据不一致时，强制用外部数据覆盖本地记录',
        )
        parser.add_argument(
            '--progress-every',
            type=int,
            default=200,
            help='长任务进度输出步长，默认每 200 条输出一次',
        )

    def handle(self, *args, **options):
        customer_name = str(options['customer_name'] or '').strip()
        operator_id = options.get('operator_id') or getattr(settings, 'HAOBUYE_FINANCE_SYNC_OPERATOR_ID', 0)
        if not operator_id:
            raise CommandError('必须提供 --operator-id，或配置 HAOBUYE_FINANCE_SYNC_OPERATOR_ID')

        try:
            operator = basic_models.Employee.objects.select_related('merchant').get(id=operator_id)
        except basic_models.Employee.DoesNotExist as exc:
            raise CommandError(f'经办人不存在: {operator_id}') from exc

        try:
            self.stdout.write(f'[sync] 开始处理客户: {customer_name}')
            payload = sync_customer_finance(
                customer_name=customer_name,
                operator=operator,
                allow_create_customer=options['allow_create_customer'],
                dry_run=bool(options['dry_run']),
                force_update=bool(options['force_update']),
                progress_callback=lambda message: self.stdout.write(f'[sync] {message}'),
                progress_every=max(1, int(options.get('progress_every') or 200)),
            )
        except Exception as exc:
            raise CommandError(str(exc)) from exc

        self.stdout.write(self.style.SUCCESS(str(payload)))
