from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django.conf import settings
import uuid
from django.core.cache import cache


def send_sms(phone_number, code):
    """发送验证码"""
    client = AcsClient(
        settings.ALIYUN_SMS_ACCESS_KEY_ID,
        settings.ALIYUN_SMS_ACCESS_KEY_SECRET,
        'cn-hangzhou'
    )

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('PhoneNumbers', phone_number)
    request.add_query_param('SignName', settings.ALIYUN_SMS_SIGN_NAME)
    request.add_query_param('TemplateCode', settings.ALIYUN_SMS_TEMPLATE_CODE)
    request.add_query_param('TemplateParam', '{"code":"%s"}' % code)

    response = client.do_action_with_exception(request)
    return response


def generate_token(user_id, is_admin=False):
    token = str(uuid.uuid4())
    prefix = "admin_token:" if is_admin else "token:"
    cache.set(f"{prefix}{token}", user_id, timeout=2592000)  # Token 有效期为30天
    return token

def get_user_id_from_token(token):
    # 优先尝试从管理员token中获取
    user_id = cache.get(f"admin_token:{token}")
    if user_id is not None:
        return user_id
    # 再尝试从普通用户token中获取
    return cache.get(f"token:{token}")


