from handler.base import BaseHandler
from utils import FORMAT_TIME
from src.object import Order,LaneSignal,OrderResultItem,OrderRevokeItem,KtPayResCallback
from src.fun import NoticePayFail,ConfirmOrRelieveSigned
from log import app_log
logger = app_log(__name__)

FAILRES =[
    "E01-天线故障",
    "E02-未装ETC",
    "E03-ETC拆卸",
    "E04-ETC未插卡",
    "E05-ETC未绑定",
    "E06-ETC失效",
    "E07-车牌不符",
    "E08-非陕西卡",
    "E09-ETC黑名单",
    "E10-余额不足",
    "E11-交易失败",
    "E12-交易超时",
    "E13-未知",
    "E14-读卡错误",
    "E15-云端不通",
    "E16-云端异常",
    "E17-超额消费",
    "E18-取TAC失败",
    "E19-记账B卡"
]


class EnterContractHnadler(BaseHandler):
    '''科拓定制车场入场签约,扫描车辆是否安装OBU,此场景统一回复安装'''
    async def post(self):
        data = self.json()
        logger.info(f"----in:{data}")
        res = await ConfirmOrRelieveSigned(data,1)
        if res == -1:
            logger.error(f"签约异常:{res}")
            return self.write_resp500("服务器内部异常")
        return self.write_resp200({"parkId":data.get("parkId")},_err="进场上报成功")


class KtcustomMadePayHandler(BaseHandler):
    '''科拓定制出场支付接口'''
    async def post(self):
        data = self.json()
        logger.info(f"----out data:{data}")
        parkId = data.get("parkId")
        order = Order()
        try:
            order.statisticDate = int(FORMAT_TIME("%Y%m%d"))
            order.payNo = data.get("orderNo")
            order.plate = data.get("plateNo")
            order.plateColor = 0
            order.entryLane = 2
            order.entryTime = str(data.get("entryTime")).replace('-','').replace(':','').replace(' ','')
            order.exitTime = FORMAT_TIME("%Y%m%d%H%M%S")
            order.exitLane = data.get("leaveNodeId")
            order.fee = data.get("money")
        except Exception as e:
            logger.error(f"初始化订单异常:{e}")
        orderMap = order.format()


        ls = LaneSignal()
        ls.lane = orderMap["exitLane"]
        ls.ClearResSignal() #清理上次交易中的缓存结果
        ls.SetOrderSignal(orderMap) #存入新的扣费信息

        resultItem = OrderResultItem()
        resultItem.payNo = order.payNo
        resultItem.transNumber = ""
        resultItem.plate = order.plate
        resultItem.date = order.exitTime[0:8]

        # body,porxy = resultItem.SaveInit()
        self.write_resp200("",_err="成功扣款")  #先断开连接不完成结果返回

        #---------------延迟后续完成-------------------------------------------
        res = "E13-未知" #初始化结果
        try:
            res =  await ls.GetRes() #异步等待扣费结果.. serviceId
        except Exception as e:
            logger.error(f"等待交易结果异常:{e}")
        resultItem.res = res
        # body["res"] = res #修改最终扣费结果
        # logger.info(f"{body.get('payNo')}:{res}")
        try:
            await resultItem.save()
        except Exception as e:
            logger.error(f"记录交易结果时异常,不影响返回结果:{e}")
        
        if res in FAILRES:
            #扣费失败通知
            logger.info(f"-------failres:{res};order:{order.payNo}")
            try:
                noticeRes = await NoticePayFail(
                    order.payNo,
                    data.get("entryTime"),
                    order.payNo,resultItem.res,
                    parkId
                )
            except Exception as e:
                logger.error(f"扣费失败通知异常:{e};{order.payNo}")
                return
            if noticeRes == -1:
                logger.error(f"扣费失败通知失败:{order.payNo}")
            return



        # #同步返回改异步回调
        pcb = KtPayResCallback()
        pcb.callBackUrl = "/api/v1/free/pass/platform/kt/penetrate/gateway/"
        callBackErr = ""
        try:
            callBackRes = await pcb.callback(res,orderMap,parkId)
        except Exception as e:
            callBackErr = f"扣费结果回调异常:{e}"
            logger.error(callBackErr)
            # 主动撤销
            ori = OrderRevokeItem(orderMap.get("payNo"))
            res = await ori.revok()
            logger.info(f"回调异常主动撤销结果:{res}")
        if callBackRes == -1:
            # 主动撤销
            callBackErr = "扣费结果回调失败"
            logger.error(callBackErr)
            ori = OrderRevokeItem(orderMap.get("payNo"))
            res = await ori.revok()
            logger.info(f"回调失败主动撤销结果:{res}")
        #记录回调结果
        res = await pcb.save(orderMap["payNo"],callBackRes,callbackErr=callBackErr)
        if res == -1:
            logger.info("记录回调失败,请管理员检查异常")


