"""创建新俱乐部并从模板复制配置。"""
from decimal import Decimal

from django.db import transaction

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


def bootstrap_club_from_template(
    new_id: str,
    name: str,
    wx_appid: str = '',
    template_club_id: str = CLUB_ID_DEFAULT,
    extra_fields: dict = None,
):
    """
    从模板俱乐部复制支付/会员价/利率等配置，创建新俱乐部。
    返回新建的 Club 实例。
    """
    new_id = (new_id or '').strip()
    name = (name or '').strip()
    template_id = normalize_szjilu_club_id(template_club_id)
    extra_fields = extra_fields or {}

    if not new_id or len(new_id) > 16:
        raise ValueError('club_id 无效')
    if not name:
        raise ValueError('俱乐部名称不能为空')
    if new_id == template_id:
        raise ValueError('新 club_id 不能与模板相同')
    if Club.query.filter(club_id=new_id).exists():
        raise ValueError(f'俱乐部 {new_id} 已存在')

    template = Club.query.get(club_id=template_id)

    with transaction.atomic():
        club = Club.query.create(
            club_id=new_id,
            name=name,
            status=int(extra_fields.get('status', 1)),
            wx_appid=wx_appid or extra_fields.get('wx_appid') or template.wx_appid,
            wx_secret=extra_fields.get('wx_secret', template.wx_secret),
            mch_id=extra_fields.get('mch_id', template.mch_id),
            pay_app_id=extra_fields.get('pay_app_id') or wx_appid or template.pay_app_id or template.wx_appid,
            api_v3_key=extra_fields.get('api_v3_key', template.api_v3_key),
            cert_serial_no=extra_fields.get('cert_serial_no', template.cert_serial_no),
            private_key_path=extra_fields.get('private_key_path', template.private_key_path),
            platform_cert_dir=extra_fields.get('platform_cert_dir', template.platform_cert_dir),
            official_appid=extra_fields.get('official_appid', template.official_appid),
            official_secret=extra_fields.get('official_secret', template.official_secret),
            official_token=extra_fields.get('official_token', template.official_token),
            encoding_aes_key=extra_fields.get('encoding_aes_key', template.encoding_aes_key),
            template_id=extra_fields.get('template_id', template.template_id),
            template_max_per_minute=extra_fields.get(
                'template_max_per_minute', template.template_max_per_minute,
            ),
            h5_domain=extra_fields.get('h5_domain', template.h5_domain),
            oss_prefix=extra_fields.get('oss_prefix') or new_id,
            goeasy_appkey=extra_fields.get('goeasy_appkey', template.goeasy_appkey),
            goeasy_secret=extra_fields.get('goeasy_secret', template.goeasy_secret),
            config_json=dict(template.config_json or {}),
            sort_order=int(extra_fields.get('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'),
                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)
        from jituan.services.club_shangpin_leixing import copy_club_shangpin_leixing_config
        from jituan.services.club_kaohe_chenghao import copy_club_kaohe_chenghao_config
        copy_club_shangpin_leixing_config(template_id, new_id)
        copy_club_kaohe_chenghao_config(template_id, new_id)
        from jituan.services.dashou_exam import copy_exam_config
        copy_exam_config(template_id, new_id)

    return club
