import json
import time
from enum import Enum
from lib.frame import TerFrame
from utils import FORMAT_TIME,FORMAT_TIME2,AppPrint
from log import Logger
logger = Logger(__name__)

class TaskSelect(Enum):
    TASK_HEARTBEAT = "0"
    TASK_GET_ORDER = "1"

class ETC0rderManager(object):
    def __init__(self,paySignal,scheduler,stream,cache) -> None:
        self.paySignal = paySignal
        self.scheduler = scheduler
        self.stream = stream
        self.cache = cache


    def __SendPaySignal(self):
        tf = TerFrame(b'\x50',(b'\x80',b'\x00',b'\x02'),"!sss")
        self.stream.write(tf.frame)

    def __write(self,keyFrameLogPath,lane,order):
        with open(f"{keyFrameLogPath}lane{lane}-{FORMAT_TIME('%Y-%m-%d')}.log","+a") as file:
            print("-------------------------start-------------------------",file=file)
            print(f"当前时间:{FORMAT_TIME2('%Y-%m-%d %H:%M:%S.%f')[:-3]}",file=file)
            print(f"收到订单:\n{json.dumps(order,indent=4,ensure_ascii=False)}",file=file)

    async def get(self,*args, **kwargs):
        lane = kwargs.get("lane")
        keyFrameLogPath = kwargs["keyFrameLogPath"]
        ETCOrderStr = self.paySignal.GetPaySignal(lane)
        if not ETCOrderStr:
            return
        ETCOrder = json.loads(ETCOrderStr)
        ETCOrderByOld = self.cache.get("order")
        if ETCOrderByOld:
            if ETCOrderByOld['payNo'] == ETCOrder['payNo']: # 因为是异步执行防止在交易中再次捕获同一笔订单
                self.paySignal.ClearPaySignal(lane)
                return
        self.scheduler.pause_job(TaskSelect.TASK_HEARTBEAT.value) # 暂时停止心跳,会影响交易链路
        ETCOrder.update({"realRequestTime":int(time.time())})
        self.cache.set("order", ETCOrder,5)
        logger.info(f"收到订单消息:\n{AppPrint(ETCOrder)}")
        self.__SendPaySignal()
        self.__write(keyFrameLogPath,lane,ETCOrder)

    async def query(self):
        self.__SendPaySignal()
        

async def  SendHeartbeat(*args, **kwargs):
    stream = kwargs.get("stream")
    tf = TerFrame(b'\x11',(1,0,0),"!bbb")
    stream.write(tf.frame)