"""从 xq 模板复制配置，创建新子公司俱乐部。"""
from decimal import Decimal

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

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import Club, ClubHuiyuanPrice, ClubLilubiao, ClubTixianQuota, ClubWithdrawConfig
from jituan.services.szjilu_accounting import normalize_szjilu_club_id
from jituan.services.display_config import copy_display_config
from config.models import Szjilu


class Command(BaseCommand):
    help = '从 xq 复制支付/会员价/利率配置，创建新俱乐部'

    def add_arguments(self, parser):
        parser.add_argument('club_id', type=str, help='新俱乐部 ID，如 xy')
        parser.add_argument('--name', type=str, required=True, help='展示名称')
        parser.add_argument('--wx-appid', type=str, default='', help='小程序 appid')
        parser.add_argument('--from-club', type=str, default=CLUB_ID_DEFAULT, help='模板俱乐部')

    def handle(self, *args, **options):
        new_id = (options['club_id'] or '').strip()
        name = (options['name'] or '').strip()
        template_id = normalize_szjilu_club_id(options.get('from_club'))

        if not new_id or len(new_id) > 16:
            raise CommandError('club_id 无效')
        if new_id == template_id:
            raise CommandError('新 club_id 不能与模板相同')

        try:
            template = Club.query.get(club_id=template_id)
        except Club.DoesNotExist:
            raise CommandError(f'模板俱乐部 {template_id} 不存在，请先 seed_club_xq')

        with transaction.atomic():
            if Club.query.filter(club_id=new_id).exists():
                raise CommandError(f'俱乐部 {new_id} 已存在')

            Club.query.create(
                club_id=new_id,
                name=name,
                status=1,
                wx_appid=options.get('wx_appid') or template.wx_appid,
                wx_secret=template.wx_secret,
                mch_id=template.mch_id,
                pay_app_id=template.pay_app_id or options.get('wx_appid') or template.wx_appid,
                api_v3_key=template.api_v3_key,
                cert_serial_no=template.cert_serial_no,
                private_key_path=template.private_key_path,
                platform_cert_dir=template.platform_cert_dir,
                official_appid=template.official_appid,
                official_secret=template.official_secret,
                official_token=template.official_token,
                encoding_aes_key=template.encoding_aes_key,
                template_id=template.template_id,
                template_max_per_minute=template.template_max_per_minute,
                h5_domain=template.h5_domain,
                oss_prefix=template.oss_prefix or new_id,
                goeasy_appkey=template.goeasy_appkey,
                goeasy_secret=template.goeasy_secret,
                config_json=dict(template.config_json or {}),
                sort_order=template.sort_order + 1,
            )

            for row in ClubHuiyuanPrice.query.filter(club_id=template_id):
                ClubHuiyuanPrice.query.create(
                    club_id=new_id,
                    huiyuan_id=row.huiyuan_id,
                    jiage=row.jiage or Decimal('0'),
                    guanshifc=row.guanshifc or Decimal('0'),
                    zuzhangfc=row.zuzhangfc or Decimal('0'),
                    formal_days=row.formal_days or 30,
                    trial_enabled=bool(row.trial_enabled),
                    trial_price=row.trial_price or Decimal('0'),
                    trial_days=row.trial_days or 0,
                    trial_guanshifc=row.trial_guanshifc or Decimal('0'),
                    trial_zuzhangfc=row.trial_zuzhangfc or Decimal('0'),
                    is_enabled=row.is_enabled,
                    bankuai_id=row.bankuai_id,
                )

            for row in ClubLilubiao.query.filter(club_id=template_id):
                ClubLilubiao.query.create(
                    club_id=new_id,
                    config_type=row.config_type,
                    lilv=row.lilv or Decimal('0'),
                    remark=row.remark or '',
                )

            try:
                tpl_wd = ClubWithdrawConfig.query.get(club_id=template_id)
                ClubWithdrawConfig.query.create(club_id=new_id, mode=tpl_wd.mode)
            except ClubWithdrawConfig.DoesNotExist:
                ClubWithdrawConfig.query.create(club_id=new_id, mode=1)

            for row in ClubTixianQuota.query.filter(club_id=template_id):
                ClubTixianQuota.query.create(
                    club_id=new_id,
                    leixing=row.leixing,
                    daily_limit=row.daily_limit or Decimal('0'),
                )

            Szjilu.objects.get_or_create(club_id=new_id)

            copy_display_config(template_id, new_id)

        self.stdout.write(self.style.SUCCESS(f'俱乐部 {new_id} ({name}) 已创建，配置自 {template_id} 复制'))
