"""从现网配置初始化 xq 俱乐部及覆盖表。"""
import logging
from decimal import Decimal

from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT
from jituan.services.wechat_pay import XQ_WX_PAY, WX_V3_CERT_SERIAL_NO_OVERRIDE
from jituan.models import (
    Club,
    ClubHuiyuanPrice,
    ClubLilubiao,
    ClubWithdrawConfig,
    UserWxOpenid,
)
from users.business_models import User

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '初始化星阙(xq)俱乐部主数据，并从 huiyuan/lilubiao 复制覆盖配置'

    def handle(self, *args, **options):
        with transaction.atomic():
            club, created = self._ensure_club_xq()
            self.stdout.write(self.style.SUCCESS(
                f'club xq: {"新建" if created else "已存在"}'
            ))
            self._copy_huiyuan_prices()
            self._copy_lilubiao()
            self._ensure_withdraw_config()
            migrated = self._migrate_openid_bindings()
            self.stdout.write(self.style.SUCCESS(f'user_wx_openid 迁移绑定: {migrated} 条'))

    def _ensure_club_xq(self):
        wx_v3 = dict(getattr(settings, 'WECHAT_PAY_V3_CONFIG', {}) or {})
        defaults = {
            'name': '星阙电竞',
            'status': 1,
            'wx_appid': getattr(settings, 'WEIXIN_APPID', ''),
            'wx_secret': getattr(settings, 'WEIXIN_SECRET', ''),
            'mch_id': XQ_WX_PAY['mch_id'],
            'pay_app_id': XQ_WX_PAY['wx_appid'],
            'mch_key': XQ_WX_PAY['mch_key'],
            'api_v3_key': XQ_WX_PAY['api_v3_key'],
            'cert_serial_no': WX_V3_CERT_SERIAL_NO_OVERRIDE,
            'private_key_path': wx_v3.get('PRIVATE_KEY_PATH', ''),
            'platform_cert_dir': wx_v3.get('PLATFORM_CERT_DIR', ''),
            'config_json': {
                'mch_key': getattr(settings, 'WEIXIN_SHANGHUMIYAO', ''),
                'transfer_scene_id': wx_v3.get('TRANSFER_SCENE_ID', '1005'),
            },
            'official_appid': getattr(settings, 'WEIXIN_OFFICIAL_APPID', ''),
            'official_secret': getattr(settings, 'WEIXIN_OFFICIAL_SECRET', ''),
            'official_token': getattr(settings, 'WEIXIN_OFFICIAL_TOKEN', ''),
            'encoding_aes_key': getattr(settings, 'WEIXIN_OFFICIAL_ENCODING_AES_KEY', ''),
            'template_id': getattr(settings, 'WEIXIN_TEMPLATE_ID', ''),
            'template_max_per_minute': getattr(settings, 'WEIXIN_TEMPLATE_MAX_PER_MINUTE', 950),
            'h5_domain': getattr(settings, 'H5_DOMAIN', ''),
            'goeasy_appkey': getattr(settings, 'GOEASY_APPKEY', ''),
            'goeasy_secret': getattr(settings, 'GOEASY_SECRET', ''),
            'sort_order': 0,
        }
        try:
            club = Club.query.get(club_id=CLUB_ID_DEFAULT)
            for k, v in defaults.items():
                if k == 'config_json':
                    merged = dict(club.config_json or {})
                    for ck, cv in v.items():
                        if cv and not merged.get(ck):
                            merged[ck] = cv
                    club.config_json = merged
                    continue
                if v and not getattr(club, k, None):
                    setattr(club, k, v)
            # V3 字段允许用 settings 补全（证书路径等）
            for field in ('mch_key', 'api_v3_key', 'cert_serial_no', 'private_key_path', 'platform_cert_dir', 'pay_app_id'):
                val = defaults.get(field)
                if val and not getattr(club, field, None):
                    setattr(club, field, val)
            club.save()
            return club, False
        except Club.DoesNotExist:
            club = Club.query.create(club_id=CLUB_ID_DEFAULT, **defaults)
            return club, True

    def _copy_huiyuan_prices(self):
        from products.models import Huiyuan
        count = 0
        for h in Huiyuan.query.all():
            bankuai_id = getattr(h, 'bankuai_id', None)
            existing = ClubHuiyuanPrice.query.filter(
                club_id=CLUB_ID_DEFAULT, huiyuan_id=h.huiyuan_id
            ).first()
            if existing:
                continue
            ClubHuiyuanPrice.query.create(
                club_id=CLUB_ID_DEFAULT,
                huiyuan_id=h.huiyuan_id,
                jiage=h.jiage or Decimal('0'),
                guanshifc=h.guanshifc or Decimal('0'),
                zuzhangfc=h.zuzhangfc or Decimal('0'),
                is_enabled=True,
                bankuai_id=bankuai_id,
            )
            count += 1
        self.stdout.write(f'club_huiyuan_price 新增 {count} 条')

    def _copy_lilubiao(self):
        from orders.models import CommissionRate
        count = 0
        for row in CommissionRate.query.all():
            config_type = int(row.Platform or 0)
            existing = ClubLilubiao.query.filter(
                club_id=CLUB_ID_DEFAULT, config_type=config_type
            ).first()
            if existing:
                continue
            ClubLilubiao.query.create(
                club_id=CLUB_ID_DEFAULT,
                config_type=config_type,
                lilv=row.Rate or Decimal('0'),
                remark='',
            )
            count += 1
        self.stdout.write(f'club_lilubiao 新增 {count} 条')

    def _ensure_withdraw_config(self):
        from config.models import WithdrawConfig, TixianQuotaDefault
        mode = 1
        try:
            wc = WithdrawConfig.query.first()
            if wc:
                mode = wc.mode
        except Exception:
            pass
        try:
            cfg = ClubWithdrawConfig.query.get(club_id=CLUB_ID_DEFAULT)
            cfg.mode = mode
            cfg.save(update_fields=['mode'])
        except ClubWithdrawConfig.DoesNotExist:
            ClubWithdrawConfig.query.create(club_id=CLUB_ID_DEFAULT, mode=mode)
        self._copy_tixian_quota()

    def _copy_tixian_quota(self):
        from config.models import TixianQuotaDefault
        from jituan.models import ClubTixianQuota
        count = 0
        for row in TixianQuotaDefault.query.all():
            existing = ClubTixianQuota.query.filter(
                club_id=CLUB_ID_DEFAULT, leixing=row.UserType,
            ).first()
            if existing:
                continue
            ClubTixianQuota.query.create(
                club_id=CLUB_ID_DEFAULT,
                leixing=row.UserType,
                daily_limit=row.default_quota or Decimal('0'),
            )
            count += 1
        self.stdout.write(f'club_tixian_quota 新增 {count} 条')

    def _migrate_openid_bindings(self):
        migrated = 0
        users = User.query.filter(OpenID__isnull=False).exclude(OpenID='')
        for u in users:
            exists = UserWxOpenid.query.filter(
                club_id=CLUB_ID_DEFAULT, openid=u.OpenID
            ).exists()
            if exists:
                continue
            UserWxOpenid.query.create(
                club_id=CLUB_ID_DEFAULT,
                openid=u.OpenID,
                yonghuid=u.UserUID,
                unionid=u.UnionID,
            )
            if hasattr(u, 'ClubID') and (not u.ClubID or u.ClubID != CLUB_ID_DEFAULT):
                u.ClubID = CLUB_ID_DEFAULT
                u.save(update_fields=['ClubID'])
            migrated += 1
        return migrated
