from nonebot import on_command, get_plugin_config,logger
from nonebot.permission import SUPERUSER
from nonebot.rule import to_me
from nonebot.adapters.onebot.v11 import PrivateMessageEvent, GroupMessageEvent, MessageSegment
from nonebot.params import Depends
from .config import Config
from .utils import post, get_classes, post_vcode, get_log
import random
import asyncio
import time

plugin_config = get_plugin_config(Config)


help = on_command("咸鸭蛋",rule=to_me(),aliases={"apihelp", "sudhelp"},permission=SUPERUSER, priority=0, block=True)
@help.handle()
async def _():
    await asyncio.sleep(random.uniform(2, 3))
    await help.finish(plugin_config.HelpStr)

ddonline = on_command("在线人数",rule=to_me(),aliases={"ddonline", "ddop"}, priority=0, block=True)
@ddonline.handle()
async def _(event:PrivateMessageEvent):
    id:str = str(event.user_id)
    msg:str = await post("在线人数",id)
    await asyncio.sleep(random.uniform(2, 3))
    await ddonline.finish(msg)

addkami = on_command("添加卡密",rule=to_me(),aliases={"addkami", "akm"},permission=SUPERUSER, priority=0, block=True)
@addkami.handle()
async def handle_addkami(event: PrivateMessageEvent):
    user_id = str(event.user_id)
    msg = event.get_plaintext()
    parts = msg.split(' ')
    if len(parts) != 3:
        await asyncio.sleep(random.uniform(2, 3))
        await addkami.finish("参数不正确！格式: /添加卡密 <类型> <卡密>")

    classes = get_classes(parts[1])
    if not classes:
        await addkami.finish("卡密类型不正确！支持: 天/周/月")

    try:
        result = await post("添加卡密", user_id, {"classes": classes, "kami": parts[2]})
    except Exception as e:
        logger.error(f"添加卡密失败: {e}")
        await addkami.finish("添加卡密失败，请稍后再试")
    await asyncio.sleep(random.uniform(2, 3))
    await addkami.finish(result)

createkami = on_command("生成卡密",rule=to_me(),aliases={"createkami", "ckm"},permission=SUPERUSER, priority=0, block=True)
@createkami.handle()
async def handle_createkami(event: PrivateMessageEvent):
    user_id = str(event.user_id)
    msg = event.get_plaintext()
    parts = msg.split(' ')
    if len(parts) != 2:
        await asyncio.sleep(random.uniform(2, 3))
        await createkami.finish("参数不正确！格式: /生成卡密 <类型>")

    classes = get_classes(parts[1])
    if not classes:
        await createkami.finish("卡密类型不正确！支持: 天/周/月")

    try:
        result = await post("生成卡密", user_id, {"classes": classes})
    except Exception as e:
        logger.error(f"生成卡密失败: {e}")
        await createkami.finish("生成卡密失败，请稍后再试")
    await asyncio.sleep(random.uniform(2, 3))
    await createkami.finish(result)

addviptime = on_command("用户加时",rule=to_me(),aliases={"addviptime", "avt"},permission=SUPERUSER, priority=0, block=True)
@addviptime.handle()
async def handle_addviptime(event: PrivateMessageEvent):
    user_id = str(event.user_id)
    msg = event.get_plaintext()
    parts = msg.split(' ')
    if len(parts) != 3:
        await asyncio.sleep(random.uniform(2, 3))
        await addviptime.finish("参数不正确！格式: /用户加时 <用户名> <类型>")

    username = parts[1]
    classes = get_classes(parts[2])
    if not classes:
        await addviptime.finish("卡密类型不正确！支持: 天/周/月")

    try:
        result = await post("用户加时", user_id, {"username": username, "classes": classes})
    except Exception as e:
        logger.error(f"用户加时失败: {e}")
        await addviptime.finish("用户加时失败，请稍后再试")
    await asyncio.sleep(random.uniform(2, 3))
    await addviptime.finish(result)

generate_qq_vcode = on_command("绑定QQ",aliases={"bindqq", "绑定qq"}, priority=0, block=True)

# 添加用户使用时间记录字典
user_last_use_time = {}

@generate_qq_vcode.handle()
async def _(event: GroupMessageEvent): # GroupMessageEvent PrivateMessageEvent
    # 检查是否来自指定群组
    if event.group_id != 621016172:
        return
    # if event.user_id != 1424473282:
    #     return
        
    id:str = str(event.user_id)
    
    # 限流检查：检查用户上次使用时间
    current_time = time.time()
    if id in user_last_use_time:
        time_diff = current_time - user_last_use_time[id]
        if time_diff < 60:  # 60秒内已使用过
            await generate_qq_vcode.finish(f"请求过于频繁，请在{int(60 - time_diff)}秒后再试")
            return
    
    # 更新用户最后使用时间
    user_last_use_time[id] = current_time
    
    msg:str = await post_vcode(id)
    await asyncio.sleep(random.uniform(2, 3))
    # 在消息前添加@用户
    at_user = MessageSegment.at(event.user_id)
    await generate_qq_vcode.finish(at_user + " " + msg)




view_logs = on_command("查看日志",aliases={"logs", "查询日志"}, priority=0, block=True)
@view_logs.handle()
async def _(event:GroupMessageEvent): # GroupMessageEvent PrivateMessageEvent
    # 检查是否来自指定群组
    if event.group_id != 621016172:
        return
    # if event.user_id != 1424473282:
    #     return
        
    id:str = str(event.user_id) 
    msg:str = await get_log(id)
    await asyncio.sleep(random.uniform(2, 3))
    # 在消息前添加@用户
    at_user = MessageSegment.at(event.user_id)
    await view_logs.finish(at_user + " " + msg)