import pandas

from one_piece_server import TQZTianQinClient
from tqz_extern.json_operator import TQZJsonOperator

import re

class TQZAutoMakeConfig:

    __trading_time_config = './config/trading_time.json'
    __main_futures_xlsx = './config/main_futures.xlsx'


    @classmethod
    def auto_make_session_json(cls):
        all_tq_main_futures = TQZTianQinClient().load_all_tq_main_futures()

        ret = {}
        for tq_main_future in all_tq_main_futures:
            _tq_future = f'{tq_main_future.split(".")[0]}.{re.match(r"^[a-zA-Z]{1,3}", tq_main_future.split(".")[1]).group()}'
            tq_main_future_data = TQZTianQinClient().query_single_quote(tq_future=tq_main_future)

            ret[_tq_future] = {
                'day': vars(tq_main_future_data['trading_time'])['day'],
                'night': vars(tq_main_future_data['trading_time'])['night']
            }

        for instrument, data in ret.items():
            for session_data in data.values():
                for i in range(len(session_data)):
                    for j in range(len(session_data[i])):
                        hour = session_data[i][j].split(':')[0]
                        if hour >= '24':
                            new_hour = str(int(hour) - int('24')).zfill(2)
                            session_data[i][j] = f'{new_hour}:{session_data[i][j].split(":")[1]}:{session_data[i][j].split(":")[2]}'

        TQZJsonOperator.tqz_write_jsonfile(content=ret, target_jsonfile=cls.__trading_time_config)


    @classmethod
    def auto_make_main_contracts_excel(cls):
        """
        根据所有合约的日线收盘数据, 更新当日的所有品种的主力合约
        """

        # last_day, main_futures_list = '2023-04-29', ['SHFE.sn2306', 'DCE.c2307']
        last_day, main_futures_list = TQZTianQinClient().get_lastDay_mainFuturesList()

        daily_main_futures_df = pandas.read_excel(io=cls.__main_futures_xlsx)
        if last_day != daily_main_futures_df['date'].values.tolist()[-1]:
            new_row = len(daily_main_futures_df)
        else:
            new_row = len(daily_main_futures_df) - 1

        daily_main_futures_df.loc[new_row, 'date'] = last_day
        for main_future in main_futures_list:
            main_fut = f'{main_future.split(".")[0]}.{re.match(r"^[a-zA-Z]{1,3}", main_future.split(".")[1]).group()}'

            if main_fut not in daily_main_futures_df.columns:
                daily_main_futures_df[main_fut] = main_future
            else:
                daily_main_futures_df.loc[new_row, main_fut] = main_future

        daily_main_futures_df.to_excel(cls.__main_futures_xlsx, index=False)


if __name__ == '__main__':
    TQZAutoMakeConfig.auto_make_main_contracts_excel()