from nonebot import get_plugin_config, on_command
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me
from nonebot.adapters.onebot.v11 import Message,MessageEvent
from nonebot.params import ArgPlainText,CommandArg
from .config import Config
from nonebot.typing import T_State
from .AccountSpider import AccountSpider
from nonebot_plugin_saa import Text, Image, MessageFactory
import os
import random
import asyncio

__plugin_meta__ = PluginMetadata(
    name="大漠余额查询",
    description="查询大漠插件平台账户余额的插件",
    usage="""
    指令：
    - 大漠余额
    - 余额查询
    
    权限：
    仅限指定用户（QQ：1424473282）使用
    
    使用流程：
    1. 发送"大漠余额"或"余额查询"指令
    2. 机器人会返回验证码图片
    3. 输入验证码完成查询
    """,
    config=Config,
)

config = get_plugin_config(Config)

spider = AccountSpider()

# 指令：大漠余额
check_balance = on_command("大漠余额", aliases={"余额查询"}, priority=5,block=True)

@check_balance.handle()
async def handle_first_receive(event: MessageEvent, state: T_State):
    user_id = event.user_id
    if user_id not in [1424473282]:
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.finish("你没有权限进行此操作")

    global spider
    spider = AccountSpider()
    # 获取验证码并存储
    spider.get_verification_code(True)
    # 获取当前脚本所在目录的绝对路径
    current_dir = os.path.dirname(__file__)
    # 构造图片的绝对路径
    image_path = os.path.join(current_dir, "verification_code.png")
    # 发送图片
    with open(image_path, "rb") as f:
        image_bytes = f.read()
    await asyncio.sleep(random.uniform(2, 3))
    await MessageFactory([Text("请发送验证码图片中的内容进行验证："),Image(image_bytes)]).send()

# 验证用户输入的验证码
@check_balance.got("captcha", prompt="请输入验证码：")
async def handle_captcha(event: MessageEvent, state: T_State, captcha: str = ArgPlainText("captcha")):
    user_id = event.user_id
    if user_id not in [1424473282]:
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.finish("你没有权限进行此操作")

    # 账号密码配置
    USERNAME = "xsllovemlj"
    PASSWORD = "xsl1314520mlj"

    global spider
    if spider.login(USERNAME, PASSWORD, captcha):
        print("登录成功！")
        balance = spider.get_balance()
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.finish(f"大漠账户余额：{balance}元")
    else:
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.reject("获取失败、登录失败，请检查账号密码或验证码是否正确")
