import time
from handler.base import BaseHandler
from tornado.web import authenticated
from src.object import LaneSignal,OrderResultItem,OrderRevokeItem,OrderCheckPayItem,PayResCallback,OrderWriteOffManger
from src.fun import WriteOff
from lib.alert import AlarmMsgManager,AlarmLevel,AlarmType
from utils import FORMAT_TIME
from log import app_log
logger = app_log(__name__)

class PayHandler(BaseHandler):
    #@authenticated
    async def post(self):
        data = self.json()
        logger.info(f"payData:{data}")
        lane = data.get("lane")
        if not lane:
            self.write_resp400("传入参数不完整")
        ls = LaneSignal()
        ls.lane = lane
        ls.ClearResSignal(data.get("serviceId")) #清理上次交易中的缓存结果
        ls.SetOrderSignal(data) #存入新的扣费信息
        orderResultItem = OrderResultItem()
        orderResultItem.payNo = data.get("payNo")
        orderResultItem.transNumber = ""
        orderResultItem.plate = data.get("plate", "")
        orderResultItem.date = data.get("statisticDate", "")

        self.write_resp200("")  #先断开连接不完成结果返回

        #---------------延迟后续完成-------------------------------------------
        res = "E13-未知" #初始化结果
        try:
            res =  await ls.GetRes(data.get("serviceId")) #异步等待扣费结果..
        except Exception as e:
            logger.error(f"等待交易结果异常:{e}")
        
        logger.info(f"{orderResultItem.payNo}:{res}")
        orderResultItem.res = res
        orderRevokeItem = OrderRevokeItem(data.get("payNo"))
        callbackUrl = data["callbackUrl"]
        # callbackUrl = "http://127.0.0.1:5999/api/v1/rec/service/test/pay/callback/" #测试
        payResCallback = PayResCallback(callbackUrl) #车道软件回调对象
        title = f"【{AlarmLevel.WARNING.value}-{AlarmType.CALLBACK_ERROR.value}】"
        alarmMsg = f"停车场编号:   {data['serviceId']}\n订单编号:   {orderResultItem.payNo}\n车牌号:   {orderResultItem.plate}\n告警时间:   {FORMAT_TIME('%Y-%m-%d %H:%M:%S')}"
        alarmMsgManager = AlarmMsgManager(title=title,msg=alarmMsg)
        payResCallback.callbacErrorAlarmManger = alarmMsgManager # 注册回调结果保存失败告警对象
        orderWriteOffManger = OrderWriteOffManger(payResCallback,orderRevokeItem,orderResultItem)
        await orderWriteOffManger.WriteOffBySavePayRes()  #step1
        await orderWriteOffManger.WriteOffByCallback(data["exitLane"],data["exitTime"],data["fee"]) #step2


'''class XgsPayHandler(BaseHandler):
    #@authenticated
    async def post(self):
        data = self.json()
        logger.info(f"payData:{data}")
        lane = data.get("lane")
        if not lane:
            self.write_resp400("传入参数不完整")
        ls = XgsLaneSignal()
        # ls.lane = "" #手动更改
        data["payNo"] = ls.CreateOrderId(data.get("serviceId")) #换成西工所需要订单格式
        ls.SetOrderSignal(data) #存入新的扣费信息
        orderResultItem = OrderResultItem()
        orderResultItem.payNo = data.get("payNo")
        orderResultItem.transNumber = ""
        orderResultItem.plate = data.get("plate", "")
        orderResultItem.date = data.get("statisticDate", "")

        # self.write_resp200("")  #先断开连接不完成结果返回

        #---------------延迟后续完成-------------------------------------------
        res = "E13-未知" #初始化结果
        try:
            res =  await ls.GetRes("") #异步等待扣费结果..
        except Exception as e:
            logger.error(f"等待交易结果异常:{e}")
        return self.write_resp200("")
        # logger.info(f"{orderResultItem.payNo}:{res}")
        # orderResultItem.res = res
        # orderRevokeItem = OrderRevokeItem(data.get("payNo"))
        # callbackUrl = data["callbackUrl"]
        # #callbackUrl = "http://127.0.0.1:5999/api/v1/rec/service/test/pay/callback/" #测试
        # payResCallback = PayResCallback(callbackUrl) #车道软件回调对象
        # xgsPayResCallback = XgsPayResCallback("/payConfirm") #西公所服务回调对象
        # title = f"【{AlarmLevel.WARNING.value}-{AlarmType.CALLBACK_ERROR.value}】"
        # alarmMsg = f"停车场编号:   {data['serviceId']}\n订单编号:   {orderResultItem.payNo}\n车牌号:   {orderResultItem.plate}\n告警时间:   {FORMAT_TIME('%Y-%m-%d %H:%M:%S')}"
        # alarmMsgManager = AlarmMsgManager(title=title,msg=alarmMsg)
        # payResCallback.callbacErrorAlarmManger = alarmMsgManager # 注册回调结果保存失败告警对象
        # orderWriteOffManger = XgsOrderWriteOffManger(payResCallback,xgsPayResCallback,orderRevokeItem,orderResultItem)
        # await orderWriteOffManger.WriteOffBySavePayRes()  #step1
        # await orderWriteOffManger.WriteOffByCallback(data["exitLane"],data["exitTime"],data["fee"]) #step2'''


class RevokePayHandler(BaseHandler):
    #@authenticated
    async def post(self):
        data = self.json()

        ori = OrderRevokeItem(data.get("payNo"))
        try:
            res = await ori.revok()
        except Exception as e:
            logger.error(f"撤销过程中异常:{e}")
            res = "E03-未知"
        if res == -1:
            logger.error("撤销失败")
            res = "E01-扣款模块未响应"
        try:
            await ori.save(res)
        except Exception as e:
            logger.error(f"记录撤销异常:{e}")

        return self.write_resp200(res)
        
class CheckPayHandler(BaseHandler):
    #@authenticated
    async def post(self):
        data = self.json()
        oci = OrderCheckPayItem(data)
        try:
            qs = await oci.CheckPay()
        except Exception as e:
            logger.error(f"对账过程中异常:{e}")
            return self.write_resp500("服务器内部异常")
        if qs == -1:
            await self.write_resp500("服务器内部异常")
            return
        ls = [[item['payNo'],item["content"]["fee"]] for item in qs]
        return self.write_resp200(ls)


class FreePassVerificationHandler(BaseHandler):
    #@authenticated
    async def post(self):
        data = self.json()
        try:
            res = await WriteOff(data)
        except Exception as e:
            logger.error(f"核销过程中异常:{e}")
            return self.write_resp500("服务器内部异常")
        if res == -1:
            logger.error(f"核销过程中失败:{res}")
            return self.write_resp500(f"服务器内部异常")
        return self.write_resp200(res)


class TestHandler(BaseHandler):
    async def post(self):
        return self.write_resp200("hello easy ETC")
    

class TestCallbackHadnler(BaseHandler):
    async def post(self):
        data = self.json()
        logger.info(f"收到回调信息:{data}")
        return self.write_resp200(
            {
                "payNo":data["payNo"],
                "status":1,
                "confirmTime":int(time.time())
            }
        )