import sys
import os

file_path = os.path.abspath(__file__)
end = file_path.index('mns') + 17
project_path = file_path[0:end]
sys.path.append(project_path)
# 同步当天所有开盘数据
import mns_common.utils.date_handle_util as date_handle_util
from loguru import logger
from datetime import time
from mns_common.db.MongodbUtil import MongodbUtil
import mns_common.component.common_service_fun_api as common_service_fun_api
import mns_common.component.company.company_common_service_new_api as company_common_service_new_api
import mns_common.component.data.data_init_api as data_init_api
import mns_common.utils.db_util as db_util
import mns_common.utils.data_frame_util as data_frame_util
import mns_common.constant.db_name_constant as db_name_constant

mongodb_util = MongodbUtil('27017')


def sync_one_day_open_data(str_day):
    realtime_quotes_db_name = 'realtime_quotes_now_' + str_day

    number = db_util.get_realtime_quotes_now_min_number(str_day, None, None)

    query = {"number": number}
    db = db_util.get_db(str_day)
    realtime_quotes_now_list = db.find_query_data(realtime_quotes_db_name, query)

    realtime_quotes_now_one = realtime_quotes_now_list.iloc[0]
    str_now_date = realtime_quotes_now_one['_id']
    str_now_date = str_now_date[7:26]

    now_date = date_handle_util.str_to_date(str_now_date, "%Y-%m-%d %H:%M:%S")
    now_date_time = now_date.time()

    target_time_09_31 = time(9, 31)
    if now_date_time >= target_time_09_31:
        return

    realtime_quotes_now_list['str_day'] = str_day

    realtime_quotes_now_list = handle_init_real_time_quotes_data(
        realtime_quotes_now_list.copy(),
        str_now_date, number)

    mongodb_util.insert_mongo(realtime_quotes_now_list, 'realtime_quotes_now_open')

    logger.info("同步str_day:{}开盘数据", str_day)


def handle_init_real_time_quotes_data(real_time_quotes_now, str_now_date, number):
    #  fix industry
    real_time_quotes_now = company_common_service_new_api.amend_ths_industry(real_time_quotes_now.copy())
    #  exclude b symbol
    real_time_quotes_now = common_service_fun_api.exclude_b_symbol(real_time_quotes_now.copy())
    #  classification symbol
    real_time_quotes_now = common_service_fun_api.classify_symbol(real_time_quotes_now.copy())

    #  calculate parameter
    real_time_quotes_now = data_init_api.calculate_parameter_factor(real_time_quotes_now.copy())

    real_time_quotes_now = real_time_quotes_now.loc[real_time_quotes_now['amount'] != 0]
    real_time_quotes_now['str_now_date'] = str_now_date
    real_time_quotes_now['number'] = number
    return real_time_quotes_now


def choose_open_data_field(realtime_quotes_now_all_df, str_day):
    if data_frame_util.is_empty(realtime_quotes_now_all_df):
        logger.error("当天无开盘数据:{}", str_day)
        return None

    if 'up_speed_05' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['up_speed_05'] = realtime_quotes_now_all_df['up_speed']

    if 'sell_1_num' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['sell_1_num'] = 0

    if 'buy_1_num' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['buy_1_num'] = 0

    if 'wei_bi' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['wei_bi'] = 0

    if bool(1 - ("disk_diff_amount_exchange" in realtime_quotes_now_all_df.columns)) or bool(
            1 - ("disk_diff_amount" in realtime_quotes_now_all_df.columns)):
        try:
            if 'average_price' in realtime_quotes_now_all_df.columns:
                # 外盘与内盘的金额差额 100 为1手
                realtime_quotes_now_all_df['disk_diff_amount'] = round(
                    (realtime_quotes_now_all_df['outer_disk'] - realtime_quotes_now_all_df['inner_disk']) *
                    realtime_quotes_now_all_df[
                        "average_price"] * 100,
                    2)
            else:
                # 外盘与内盘的金额差额
                realtime_quotes_now_all_df['disk_diff_amount'] = round(
                    (realtime_quotes_now_all_df['outer_disk'] - realtime_quotes_now_all_df['inner_disk']) *
                    realtime_quotes_now_all_df[
                        "now_price"] * 100,
                    2)
        except BaseException as e:
            realtime_quotes_now_all_df['disk_diff_amount'] = 0
            logger.error("出现异常:{}", e)
        realtime_quotes_now_all_df.loc[:, 'reference_main_inflow'] = round(
            (realtime_quotes_now_all_df['flow_mv'] * (1 / 1000)), 2)

        realtime_quotes_now_all_df['disk_diff_amount_exchange'] = round(
            (realtime_quotes_now_all_df['disk_diff_amount'] / realtime_quotes_now_all_df['flow_mv']) * 1000, 2)

    if 'real_disk_diff_amount_exchange' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['real_disk_diff_amount_exchange'] = realtime_quotes_now_all_df[
            'disk_diff_amount_exchange']

    if 'sum_main_inflow_disk' not in realtime_quotes_now_all_df.columns:
        realtime_quotes_now_all_df['sum_main_inflow_disk'] = realtime_quotes_now_all_df[
            'disk_diff_amount_exchange']

    realtime_quotes_now_all_df = realtime_quotes_now_all_df[[
        "_id",
        "symbol",
        "chg",
        "quantity_ratio",
        "disk_ratio",
        "exchange",
        "amount",

        "real_disk_diff_amount_exchange",
        "disk_diff_amount_exchange",
        'disk_diff_amount',
        'sum_main_inflow_disk',
        'today_main_net_inflow',

        'large_order_net_inflow',
        'super_large_order_net_inflow',
        "now_price",
        "high",
        "low",
        "open",
        "yesterday_price",
        "volume",
        "total_mv",
        "flow_mv",
        "wei_bi",
        "buy_1_num",
        "outer_disk",
        "inner_disk",
        "average_price",
        "str_now_date",
        'up_speed',
        'up_speed_05',
        'sell_1_num',
        "number",
        'today_main_net_inflow_ratio',
        'super_large_order_net_inflow_ratio'
    ]]

    return realtime_quotes_now_all_df


def get_realtime_quotes_now_call_auction_max_number(str_day, field, symbol):
    if field is None:
        field = 'number'
    if symbol is None:
        symbol = '000001'
    realtime_quotes_db_name = 'realtime_quotes_now_' + str_day

    min_str_now_date = str_day + " 09:25:30"
    max_str_now_date = str_day + " 09:30:00"
    query = {'symbol': symbol,
             '$and': [{"str_now_date": {"$gte": min_str_now_date}},
                      {"str_now_date": {"$lt": max_str_now_date}}]}
    df = mongodb_util.descend_query(query, realtime_quotes_db_name, field, 1)
    if df is None or df.shape[0] == 0:
        logger.error("没有开盘数据:{}", str_day)
        return 0
    else:
        return list(df[field])[0]


def create_index(db_name):
    mongodb_util.create_index(db_name, [("str_day", 1)])


def sync_call_auction_data(str_day):
    realtime_quotes_db_name = 'realtime_quotes_now_' + str_day
    number = get_realtime_quotes_now_call_auction_max_number(str_day, None, None)

    query = {"number": number}
    realtime_quotes_now_list = mongodb_util.find_query_data(realtime_quotes_db_name, query)

    if data_frame_util.is_empty(realtime_quotes_now_list):
        logger.error("没有开盘数据:{}", str_day)
    else:
        realtime_quotes_now_list = choose_open_data_field(
            realtime_quotes_now_list.copy(), str_day)
        realtime_quotes_now_list['str_day'] = str_day
        now_year = str_day[0:4]
        db_name = db_name_constant.CALL_AUCTION_OPEN_DATA + '_' + now_year
        # 创建索引
        create_index(db_name)
        mongodb_util.save_mongo(realtime_quotes_now_list, db_name)
        logger.info("同步开盘数据:{}", str_day)


if __name__ == '__main__':
    sync_call_auction_data('2026-03-09')
