import requests
import threading
import json
from .models import AdminPhoneNumber

# SMS API Configuration
SMS_API_URL = "https://data.tangledup-ai.com/api/send-sms/diy"
SIGN_NAME = "叠加态科技云南"

def send_sms(phone_number, template_code, template_params):
    """
    通用发送短信函数 (异步)
    """
    def _send():
        try:
            payload = {
                "phone_number": phone_number,
                "template_code": template_code,
                "sign_name": SIGN_NAME,
                "template_params": template_params
            }
            headers = {
                "Content-Type": "application/json",
                "accept": "application/json"
            }
            # print(f"Sending SMS to {phone_number} with params: {template_params}")
            response = requests.post(SMS_API_URL, json=payload, headers=headers, timeout=15)
            print(f"SMS Response for {phone_number}: {response.status_code} - {response.text}")
        except Exception as e:
            print(f"发送短信异常: {str(e)}")

    threading.Thread(target=_send).start()

def notify_admins_order_paid(order):
    """
    通知管理员有新订单支付成功
    """
    # 获取激活的管理员手机号，最多3个
    admins = AdminPhoneNumber.objects.filter(is_active=True)[:3]
    if not admins.exists():
        print("未配置管理员手机号，跳过管理员通知")
        return

    # 构造参数
    # 模板变量: consignee, order_id, address
    # order_id 格式要求: "订单编号/电话号码"
    params = {
        "consignee": order.customer_name or "未填写",
        "order_id": f"{order.id}/{order.phone_number}", 
        "address": order.shipping_address or "无地址"
    }

    print(f"准备发送管理员通知，共 {admins.count()} 人")
    for admin in admins:
        send_sms(admin.phone_number, "SMS_501735480", params)

def notify_user_order_paid(order):
    """
    通知用户下单成功 (支付成功)
    """
    if not order.phone_number:
        return

    # 模板变量: user_nick, address
    # 尝试获取用户昵称，如果没有则使用收货人姓名
    user_nick = order.customer_name
    if order.wechat_user and order.wechat_user.nickname:
        user_nick = order.wechat_user.nickname

    params = {
        "user_nick": user_nick or "用户",
        "address": order.shipping_address or "无地址"
    }
    
    print(f"准备发送用户支付成功通知: {order.phone_number}")
    send_sms(order.phone_number, "SMS_501850529", params)

def notify_user_order_shipped(order):
    """
    通知用户已发货
    """
    if not order.phone_number:
        return

    # 模板变量: user_nick, address, delivery_company, order_id (这里指快递单号)
    user_nick = order.customer_name
    if order.wechat_user and order.wechat_user.nickname:
        user_nick = order.wechat_user.nickname

    params = {
        "user_nick": user_nick or "用户",
        "address": order.shipping_address or "无地址",
        "delivery_company": order.courier_name or "快递",
        "order_id": order.tracking_number or "暂无单号"
    }
    
    print(f"准备发送用户发货通知: {order.phone_number}")
    #send_sms(order.phone_number, "SMS_501650557", params)
    send_sms(order.phone_number, "SMS_501665569", params)

def notify_user_activity_signup_success(order, signup):
    """
    通知用户活动报名成功 (支付成功后)
    模板CODE: SMS_501990528
    模板变量: user_nick, unit_name, time, address
    """
    if not order.phone_number:
        return

    # 1. user_nick
    user_nick = order.customer_name
    if order.wechat_user and order.wechat_user.nickname:
        user_nick = order.wechat_user.nickname
        
    # 2. unit_name (Activity Title)
    unit_name = f"【{signup.activity.title}】"
    
    # 3. time
    start_time = signup.activity.start_time
    # Format time as YYYY-MM-DD HH:MM
    time_str = start_time.strftime("%Y-%m-%d %H:%M") if start_time else "待定"
    
    # 4. address
    address = signup.activity.location or "线上活动"
    
    # 5. Handle phone number format (remove +86 or spaces if any)
    phone_number = str(order.phone_number) if order.phone_number else ""
    if phone_number:
        phone_number = phone_number.replace("+86", "").replace(" ", "").strip()
        
    # Ensure phone number is valid (11 digits)
    if not phone_number or len(phone_number) != 11 or not phone_number.isdigit():
        print(f"无效的手机号: {phone_number}, 跳过短信发送")
        return

    params = {
        "user_nick": user_nick or "用户",
        "unit_name": unit_name,
        "time": time_str,
        "address": address
    }
    
    print(f"准备发送活动报名成功通知: {phone_number}")
    send_sms(phone_number, "SMS_501990528", params)