import requests
from django.core.cache import cache
from .models import WeChatPayConfig

def get_access_token(config=None):
    """
    获取微信接口调用凭证 (client_credential)
    """
    # 尝试从缓存获取
    cache_key = 'wechat_access_token'
    if config:
        cache_key = f'wechat_access_token_{config.app_id}'
        
    token = cache.get(cache_key)
    if token:
        return token

    if not config:
        # 优先查找指定 AppID
        config = WeChatPayConfig.objects.filter(app_id='wxdf2ca73e6c0929f0').first()
        if not config:
            config = WeChatPayConfig.objects.filter(is_active=True).first()
            
    if not config or not config.app_id or not config.app_secret:
        return None

    url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={config.app_id}&secret={config.app_secret}"
    try:
        response = requests.get(url, timeout=10)
        data = response.json()

        if 'access_token' in data:
            token = data['access_token']
            expires_in = data.get('expires_in', 7200)
            # 缓存 Token，留出 200 秒缓冲时间
            cache.set(cache_key, token, expires_in - 200)
            return token
        else:
            print(f"获取 AccessToken 失败: {data}")
    except Exception as e:
        print(f"获取 AccessToken 异常: {str(e)}")
    
    return None
