from datetime import datetime

from pyda.api import MarketApi


class MyMarketApi(MarketApi):
    """继承实现API接口类"""

    def __init__(self, userid: str, password: str) -> None:
        """构造函数"""
        super().__init__()

        self.login_status: bool = False
        self.connect_status: bool = False

        self.userid: str = userid
        self.password: str = password
        self.reqid: int = 0

        dt: datetime = datetime.now()
        log_file: str = f"MyRecvMk_{dt.year:04d}{dt.month:02d}{dt.day:02d}.md"

        self.log_file = open(log_file, "a")

    def __del__(self):
        """析构函数"""
        if self.log_file:
            self.log_file.close()

    def log_data(self, function_name: str, data: dict) -> None:
        """记录数据"""
        log_entry = f"{function_name}: " + " ".join(f"{key}={value}" for key, value in data.items()) + "\r\n"
        self.log_file.write(log_entry)  

    def login(self) -> None:
        """登录期货服务器"""
        # 发起连接登录
        login_req: dict = {
            "UserId": self.userid,
            "UserPwd": self.password,
            "AuthorCode": "123456",
            "ComputerName": "Dev Server",
            "SoftwareName": "VeighNa",
            "SoftwareVersion": "3.0",
            "BrokerIDForMarketPrice": "DAHK"
        }
        self.reqid += 1
        self.reqUserLogin(login_req, self.reqid)

    def onFrontConnected(self) -> None:
        """服务器连接回报"""
        print("API Version: " + self.getVersion())
        print("服务器连接成功")
        self.connect_status = True
        self.login()

    def onFrontDisconnected(self, iReason: int) -> None:
        """服务器连接断开回报"""
        self.connect_status = False
        self.login_status = False
        print(f"连接断开, 原因 = {iReason}")

    def onRspUserLogin(self, error: dict, reqid: int, last: bool) -> None:
        """用户登录回报"""
        if error.get("ErrorID", 0) == 0:
            self.login_status = True
            print("行情服务器登录成功")
        else:
            self.login_status = False
            print(f"行情服务器登录失败: ErrorID = {error['ErrorID']}, ErrorMsg = {error['ErrorMsg']}")

    def onRspUserLogout(self, error: dict, reqid: int, last: bool) -> None:
        """用户登出回报"""
        if error.get("ErrorID", 0) == 0:
            self.login_status = False
            print("行情服务器登出成功")
        else:
            print(f"行情服务器登出失败: ErrorID = {error['ErrorID']}, ErrorMsg = {error['ErrorMsg']}")

    def onRspMarketData(self, data: dict, error: dict, reqid: int, last: bool) -> None:
        """行情订阅回报"""
        if error.get("ErrorID", 0) == 0:
            print("订阅行情成功")
        else:
            print(f"订阅行情失败: ErrorID = {error['ErrorID']}, ErrorMsg = {error['ErrorMsg']}")

    def onRtnBrokerData(self, data: dict, error: dict, reqid: int, last: bool) -> None:
        """股票经济商数据回报"""
        if error.get("ErrorID", 0) == 0:
            print("onRtnBrokerData", data)
            self.log_data("onRtnBrokerData", data)
        else:
            print(f"onRtnBrokerData: ErrorID={error['ErrorID']} ErrorMsg={error['ErrorMsg']}")
            self.log_file.write(f"onRtnBrokerData: ErrorID={error['ErrorID']} ErrorMsg={error['ErrorMsg']}\r\n")

    def onRspError(self, error: dict, reqid: int, last: bool) -> None:
        """报错回报"""
        print("onRspError", error)
        self.log_data("onRspError", error)

    def onRtnMarketData(self, data: dict) -> None:
        """股票行情回报"""
        print("onRtnMarketData", data)
        self.log_data("onRtnMarketData", data)

    def onRtnSnapData(self, data: dict) -> None:
        """期货快照数据回报"""
        print("onRtnSnapData", data)
        self.log_data("onRtnSnapData", data)

    def onRtnDealData(self, data: dict) -> None:
        """期货逐笔成交数据回报"""
        print("onRtnDealData", data)
        self.log_data("onRtnDealData", data)

    def onRtnStatisticsData(self, data: dict) -> None:
        """期货统计数据回报"""
        print("onRtnStatisticsData", data)
        self.log_data("onRtnStatisticsData", data)

    def onHeartBeatWarning(self, iTimeLapse: int) -> None:
        """心跳警告"""
        print(f"onHeartBeatWarning: iTimeLapse={iTimeLapse}")
        self.log_file.write(f"onHeartBeatWarning: iTimeLapse={iTimeLapse}\r\n")

    def onRtnTradeDate(self, trade_date: dict, error: dict, reqid: int, last: bool) -> None:
        """交易日期回报"""
        if error.get("ErrorID", 0) == 0:
            print("onRtnTradeDate", trade_date)
            self.log_data("onRtnTradeDate", trade_date)
        else:
            print(f"onRtnTradeDate: ErrorID={error['ErrorID']} ErrorMsg={error['ErrorMsg']}")
            self.log_file.write(f"onRtnTradeDate: ErrorID={error['ErrorID']} ErrorMsg={error['ErrorMsg']}\r\n")
