from typing import Any
import yagmail
from utils import ReadConf

from log import app_log
logger = app_log(__name__)

from enum import Enum

class AlarmLevel(Enum):
    WARNING = "警告"
    SERIOUS = "严重"
    URGENT = "紧急"


class AlarmType(Enum):
    NOT_RECORD_MODULE_REPLY = "记录组件停止服务" #记录组件未响应
    PUSH_TRADE_DATE_FAIL = "交易数据上传失败"
    PAY_RES_SAVE_FAIL = "扣费结果存储失败"
    CALLBACK_ERROR = "订单结果推送通知错误"

class AlarmMsgManager(object):
    def __init__(self,title="",msg="") -> None:
        alarmConf = ReadConf("ALARM")
        self.addressee = alarmConf.get("ADDRESSEE") #告警收件人邮箱
        self.title = title
        self.msg = msg
    
    def send(self):
        # 发送告警
        email = Email()
        email.send(self.title,self.msg,self.addressee)

class Email(object):
    def __init__(self) -> None:
        emailConf = ReadConf("ALARM")
        self.host = emailConf.get("EMAIL_GATEWAY_HOST")
        self.gatewayPwd = emailConf.get("EMAIL_GATEWAY_PWD")
        self.sender = emailConf.get("SENDER")


    def send(self,alarmTitle:str,alarmlMsg:str,contact:str="")->Any:
        try:
            yag = yagmail.SMTP(user=self.sender, password=self.gatewayPwd, host=self.host)
            yag.send(to=contact, subject=alarmTitle, contents=alarmlMsg)
        except Exception as e:
            sendErrMsg = f"邮件发送时异常:{e}"
            logger.error(sendErrMsg)
            raise RuntimeError(sendErrMsg)

def AlarmContentTemplate(parkId,payNo,alarmTime,**kwargs):
        template = f"停车场编号: {parkId}\n时间: {alarmTime}\n订单号: {payNo}"
        return template