"""各俱乐部价格 / 利率（严格按 club_id，不读全局 huiyuan 会员表）。"""
from decimal import Decimal

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import ClubHuiyuanPrice, ClubLilubiao
from orders.models import CommissionRate


def get_club_huiyuan_price_row(club_id, huiyuan_id, require_enabled=True):
    club_id = club_id or CLUB_ID_DEFAULT
    qs = ClubHuiyuanPrice.query.filter(club_id=club_id, huiyuan_id=huiyuan_id)
    if require_enabled:
        qs = qs.filter(is_enabled=True)
    return qs.first()


def get_huiyuan_price(club_id, huiyuan_id, huiyuan_obj=None):
    """会员售价：仅 club_huiyuan_price。"""
    row = get_club_huiyuan_price_row(club_id, huiyuan_id, require_enabled=True)
    if row and row.jiage is not None:
        return Decimal(str(row.jiage))
    return Decimal('0')


def get_huiyuan_fenchong(club_id, huiyuan_id, huiyuan_obj=None):
    """首次购买默认分成：仅 club_huiyuan_price（管事/组长各公司独立配置）。"""
    row = get_club_huiyuan_price_row(club_id, huiyuan_id, require_enabled=False)
    if row:
        return Decimal(str(row.guanshifc or 0)), Decimal(str(row.zuzhangfc or 0))
    return Decimal('0'), Decimal('0')


def get_commission_rate(club_id, platform_key):
    """
    读取分成利率。platform_key 与 lilubiao.Platform 一致（如 '1','3','13'）。
    """
    club_id = club_id or CLUB_ID_DEFAULT
    config_type = int(platform_key or 0)
    row = ClubLilubiao.query.filter(club_id=club_id, config_type=config_type).first()
    if row is not None:
        return Decimal(str(row.lilv))
    cr = CommissionRate.query.filter(Platform=str(platform_key)).first()
    if cr and cr.Rate is not None:
        return Decimal(str(cr.Rate))
    return Decimal('0')


def get_commission_rate_object(club_id, platform_key):
    """兼容旧代码 CommissionRate.Rate 访问方式。"""
    rate = get_commission_rate(club_id, platform_key)
    return type('ClubRate', (), {'Rate': rate, 'Platform': str(platform_key)})()
