from sqlalchemy import Boolean, Column, Integer, String
from app.database import Base

import requests
from sqlalchemy.orm import Session
from sqlalchemy import event
from sqlalchemy.orm.attributes import get_history

class User(Base):
    __tablename__ = "users"

    # id = Column(Integer, primary_key=True, index=True)
    # nickname = Column(String, index=True)
    # remark = Column(String)
    # wechat_number = Column(String)
    # wxid = Column(String, index=True, unique=True)
    # gender = Column(String)
    # friendaddtime = Column(String)
    # openid = Column(String, index=True)
    # ebook = Column(Boolean, default=False)  # 新增电子书字段
    # activity_status = Column(String, default="0")  # 新增活动报名字段
    # vip_member = Column(Boolean, default=False)  # 新增VIP会员字段
    # verification_code = Column(String, index=True)  # 新增验证码字段
    # phone_number = Column(String, index=True, unique=True)  # 新增手机号字段
    
    # 迁移mysql
    id = Column(Integer, primary_key=True, index=True)
    nickname = Column(String(255), index=True)  # 添加长度限制
    remark = Column(String(255))  # 你也可以为其他字符串列添加长度限制
    wechat_number = Column(String(255))
    wxid = Column(String(255), index=True, unique=True)
    gender = Column(String(10))  # 可以考虑为性别列添加长度限制
    friendaddtime = Column(String(50))  # 你也可以为日期时间字段选择合适的长度
    openid = Column(String(255), index=True)
    ebook = Column(Boolean, default=False)
    activity_status = Column(String(50))  # 为活动状态添加合适的长度
    vip_member = Column(Boolean, default=False)
    verification_code = Column(String(50), index=True)  # 验证码的长度
    phone_number = Column(String(20), index=True, unique=True)  # 电话号码长度


def sengTgmesage(message):
    url = "http://192.168.31.38:8521/send_message"
    data = {"message":message}
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, json=data, headers=headers)
    try:
        response_data = response.json()
        print(response_data)
    except requests.exceptions.JSONDecodeError:
        print("Response content is not in JSON format")
        print("Response content:", response.text)
    


def handle_change(mapper, connection, target):
    """监听器函数"""
    if target.__class__.__name__ == 'User':  # 确保只监听User类的变动
        changed_fields = []
        original_value=None
        new_value=None
        
        
        for attr in target.__mapper__.column_attrs:
            history = get_history(target, attr.key)
            if history.has_changes():
                changed_fields.append(attr.key)
                original_value = history.deleted[0] if history.deleted else None
                new_value = history.added[0] if history.added else None
                
        
        if changed_fields:
            print(f"检测到用户 {target.nickname}-{target.remark} 的字段变化: {changed_fields}-{new_value}")
            msg=f"检测到用户 {target.nickname}-{target.remark} 的字段变化: {changed_fields}-{new_value}"
            sengTgmesage(msg)
            # 发起HTTP请求
            # requests.post("http://your-fastapi-endpoint/notify_change", json={"user_id": target.id, "changed_fields": changed_fields})

event.listen(User, "after_update", handle_change)