import time
from typing import Any
from enum import Enum
from lib.config_manager import ConfigMangaer,ConfigModuleEnum
from lib.proxy import ProxyDataPlatform,OAuthModeEnum
from lib.alert import AlarmMsgManager,AlarmLevel,AlarmType,AlarmContentTemplate
from utils import FORMAT_TIME
from log import Logger
logger = Logger(__name__)

CM = ConfigMangaer()
config = CM.load(ConfigModuleEnum.PARXY_MODULE)
configByRecord = CM.load(ConfigModuleEnum.RECORD_MODULE)
configByEmail = CM.load(ConfigModuleEnum.EMAIL_MODULE)

class Api(Enum):
    PUSH_IN_QUEUE = "/api/v1/park/order/controller/enqueue/"
    PUSH_IN_LOCAL_FAIL_LISTA = "/api/v1/terminal/record/service/failed/transac/"
    PUSH_BOOK_KEEP = "/api/v1/terminal/record/service/keep/"
    PUSH_DEV_ONLANE = "/api/v1/dev/platform/park/dev/status/push/"
    PUSH_KEY_FRAME = '/api/v1/terminal/record/service/transaction/record/sava/key/frame/'

async def PushDevOnline(devNumber)->Any:
    '''
    通知平台设备上线
    '''
    body = {
        "push_time": int(time.time()),
        "dev_number": devNumber,
        "dev_type": "Terminal",
        "is_one": "1",
        "status_info": {}
    }
    api = Api.PUSH_DEV_ONLANE.value
    httpProxy = ProxyDataPlatform(proxyOAuth=OAuthModeEnum.V2.value)
    res = await httpProxy.post(api,body)
    if httpProxy.isErr:
        logger.error(httpProxy.errMsg)
        return -1
    return res

async def PushKeyFrame(payId,plate,frame):
    '''存储关键帧'''
    body = {
        "push_time": int(time.time()),
        "push_date":FORMAT_TIME("%Y-%m-%d"),
        "id":payId,
        "plate":plate,
        "key_frame": frame,
    }
    api = Api.PUSH_KEY_FRAME.value
    httpProxy = ProxyDataPlatform(proxyOAuth=OAuthModeEnum.V2.value)
    res = await httpProxy.post(api,body)
    if httpProxy.isErr:
        logger.error(httpProxy.errMsg)
        return -1
    return res


class PushQueueOperate(object):
    def __init__(self,pushUrl="") -> None:
        self.pushStatus = 0 #0;云端推送成功,1;本地推送成功,2;失败


    async def PushError(self,errBody:dict,alarmParam:str):
        '''交易原始数据提交失败,推送进本地失败列表等待二次提交'''
        api = Api.PUSH_IN_LOCAL_FAIL_LISTA.value
        httpProxy = ProxyDataPlatform()
        httpProxy.protocol = configByRecord["RECORD_MODULE_PROTOCOL"]  # 本地平台
        httpProxy.host = configByRecord["RECORD_MODULE_HOST"]
        httpProxy.port = configByRecord["RECORD_MODULE_PORT"]
        res = await httpProxy.post(api,errBody,timeOut=2)
        if httpProxy.isErr:
            title = f"【{AlarmLevel.SERIOUS.value}-{AlarmType.PUSH_TRADE_DATE_FAIL.value}】"
            alarmMsg = f"订单编号:   {alarmParam['payNo']}\n交易时间:   {alarmParam['programStartTime']}\n上传结果:   失败\n上传时间:   {alarmParam['pushDate']}"
            alarmMsgManager = AlarmMsgManager(title=title,msg=alarmMsg)
            alarmMsgManager.send(contact=configByEmail["ADDRESSEE"])
        return res

    async def push(self,queueData:dict,errBody:dict,alarmParam:dict):
        body = {
            "trans_list":[queueData]
        }

        httpProxy = ProxyDataPlatform(OAuthModeEnum.V2.value)
        #httpProxy.protocol = 'http'
        #httpProxy.host = '39.104.106.82'# 临时需要
        #httpProxy.port = 9000
        api = Api.PUSH_IN_QUEUE.value
        await httpProxy.post(api,body,timeOut=2)
        if httpProxy.isErr:
            await self.PushError(errBody,alarmParam)



class PushBookKeepOperate(object):
    def __init__(self) -> None:
        self.pushTime =  int(time.time())
        self.timeRelated = {
            "pushDate": FORMAT_TIME("%Y-%m-%d"),
            "pushTime": self.pushTime,
            "pushHour": time.localtime(self.pushTime).tm_hour
        }

    
    def PushError(self,payNo: str,parkId:str):
        #记账失败发送告警
        title = f"【{AlarmLevel.SERIOUS.value}-{AlarmType.NOT_RECORD_MODULE_REPLY.value}】"
        alarmMsg = AlarmContentTemplate(parkId,payNo,FORMAT_TIME("%Y-%m-%d %H:%M:%S"))
        alarmMsgManager = AlarmMsgManager(title=title,msg=alarmMsg)
        alarmMsgManager.send(configByEmail["ADDRESSEE"])

    async def push(self,content: dict,summary:dict,parkId):
        body = {"item":summary,"content":content}
        httpProxy = ProxyDataPlatform(OAuthModeEnum.V2.value)
        httpProxy.protocol = configByRecord["RECORD_MODULE_PROTOCOL"]   # 本地平台
        httpProxy.host = configByRecord["RECORD_MODULE_HOST"]
        httpProxy.port = configByRecord["RECORD_MODULE_PORT"]

        api = Api.PUSH_BOOK_KEEP.value
        await httpProxy.post(api,body,timeOut=2)
        if httpProxy.isErr: # 推送失败进行设置好的错误回调
            self.PushError(content["payNo"],parkId)