import requests
from nonebot import get_plugin_config
from .config import Config
from nonebot import logger

plugin_config = get_plugin_config(Config)
router:dict = {
    "在线人数":"bot_online_count",
    "添加卡密":"bot_add_kami",
    "生成卡密":"bot_create_kami",
    "用户加时":"bot_add_user_viptime",
    "生成QQ验证码":"bot_generate_vcode",
    "获取日志":"bot_get_user_log"
}

async def post(router_name:str,user:str,data:dict={})->str:
    _url:str = plugin_config.DDApi_Host + router[router_name]
    data["user"]=user
    data["token"]=plugin_config.Token
    r = requests.post(url = _url,json=data)
    logger.debug(r)
    if r.status_code != 200:
        return '出错啦！'
    r=r.json()
    logger.debug(r)
    return r["message"]

async def post_vcode(user:str)->str:
    _url:str = plugin_config.DDApi_Host + router["生成QQ验证码"]
    data:dict={}
    data["user"]="1424473282"
    data["token"]=plugin_config.Token
    data["qq"]=user
    r = requests.post(url = _url,json=data)
    logger.debug(r)
    if r.status_code != 200:
        return '出错啦！'
    r=r.json()
    logger.debug(r)
    if "验证码生成成功" in r["message"]:
        resp_data = await send_mail(f'{user}@qq.com',"验证码生成成功",r["message"],"DanDing-Admin")
        if resp_data is None or resp_data.get("errorNo", -1) != 0:
            return r["message"]
        else:
            return f"生成的绑定验证码已经发送到 {user}@qq.com 邮箱中，请查收！"
    return r["message"]

async def get_log(user:str)->str:
    _url:str = plugin_config.DDApi_Host + router["获取日志"]
    r = requests.get(url = f"{_url}?user=1424473282&token={plugin_config.Token}&qq={user}")
    logger.debug(r)
    if r.status_code != 200:
        return '出错啦！'
    r=r.json()
    logger.debug(r)
    return r["message"]


def get_classes(classee:str):
    """
    将口语类型转换为程序可识别的标准卡密类型
    """
    cases = {
        'day': 'Day',
        'DAY': 'Day',
        '天': 'Day',
        '天卡': 'Day',

        'week': 'Week',
        'WEEK': 'Week',
        '周': 'Week',
        '周卡': 'Week',

        'month': 'Month',
        'MONTH': 'Month',
        '月': 'Month',
        '月卡': 'Month',
    }
    return cases.get(classee, '')


session_id: str = ""
# 登录pmail邮箱 获取cookie
login_url = plugin_config.EMAIL_LOGIN
login_pdata = {
	"account": plugin_config.EMAIL_USER,
	"password": plugin_config.EMAIL_PASSWORD
}
session = requests.session()  # 实例化session对象


def login_pmail():
	global session_id
	resp_data = None
	error_msg: str = ""
	retries = 3  # 设置重试次数
	for attempt in range(retries):
		try:
			resp_data = session.post(login_url, json=login_pdata, headers={'Content-Type': 'application/json'})
			if resp_data.status_code == 200 and resp_data.json().get('errorNo') == 0:
				logger.info('PMail App 启动成功！')
				session_id = resp_data.headers['Set-Cookie']
				return
		except ConnectionError:
			error_msg = "服务器连接失败！"
		except Exception as e:
			error_msg = str(e)
		logger.warning(f'PMail App 登录失败，正在重试... ({attempt + 1}/{retries})')
	
	# 如果重试次数用尽仍然失败
	logger.error(f'PMail App 登录失败！无法使用邮件功能!可能网络错误！{error_msg}')
	

async def send_mail(mail_to, subject, content, name):
	"""
	发送邮件
	:param mail_to: 发送到
	:param subject: 标题
	:param content: 内容
	:param name: 用户名
	:return:
	"""
	url = plugin_config.EMAIL_API

	pdata = {
		'from':
			{
				"name": "DanDing-Admin",
				"email": plugin_config.EMAIL_FROM
			},
		'to':
			[
				{
					"name": name,
					"email": mail_to
				}
			],
		'subject': subject,
		'html': content,
		"text": "text"
	}
	if session_id is None or "":
		logger.error("[error] 邮件发送失败，没有session_id，尝试重新登录邮箱服务！")
		login_pmail()

	resp_data = session.post(url, json=pdata, headers={"cookie": f"{session_id}"}).json()
	if resp_data is None or resp_data.get("errorNo", -1) != 0:
		logger.error("[error] 邮件发送失败，未知的错误，尝试重新登录邮箱服务！")
		# 重新登录pmail邮箱
		login_pmail()
		resp_data = session.post(url, json=pdata, headers={"cookie": f"{session_id}"}).json()
		if resp_data is None or resp_data.get("errorNo", -1) != 0:
			return {"errorNo": 0, "errorMsg": "", "data": ""}
		
	return resp_data