import sys
import os

file_path = os.path.abspath(__file__)
end = file_path.index('mns') + 16
project_path = file_path[0:end]
sys.path.append(project_path)
from mns_common.db.MongodbUtil import MongodbUtil
import mns_common.constant.db_name_constant as db_name_constant
from datetime import datetime
import mns_common.utils.data_frame_util as data_frame_util
import mns_common.api.em.gd.east_stock_gd_free_top_10_by_period_api as east_stock_gd_free_top_10_by_period_api
import mns_common.api.em.gd.east_stock_gd_top_10_by_period_api as east_stock_gd_top_10_by_period_api
import mns_common.utils.common_util as common_util
from loguru import logger

mongodb_util = MongodbUtil('27017')


# 同步十大流通股东
def sync_top_ten_free_gd_task(period, is_new):
    big_df = east_stock_gd_free_top_10_by_period_api.stock_gdfx_free_holding_analyse_em(period, is_new)
    now_date = datetime.now()
    sync_time = now_date.strftime('%Y-%m-%d %H:%M:%S')
    create_day = now_date.strftime('%Y-%m-%d')
    big_df['create_day'] = create_day
    big_df['sync_time'] = sync_time
    big_df['update_time'] = sync_time
    big_df['_id'] = big_df['symbol'] + '_' + big_df['period'] + '_' + big_df['shares_number_str']
    query_exist = {'period': period}
    stock_gdfx_top_10_new_df_exist = mongodb_util.find_query_data(db_name_constant.STOCK_GDFX_FREE_TOP_10_NEW,
                                                                  query_exist)
    if data_frame_util.is_not_empty(stock_gdfx_top_10_new_df_exist):
        symbol_mapping_create_day = dict(
            zip(stock_gdfx_top_10_new_df_exist['symbol'], stock_gdfx_top_10_new_df_exist['create_day']))

        symbol_mapping_sync_time = dict(
            zip(stock_gdfx_top_10_new_df_exist['symbol'], stock_gdfx_top_10_new_df_exist['sync_time']))

        big_df['create_day'] = big_df['symbol'].map(
            symbol_mapping_create_day).fillna(create_day)
        big_df['sync_time'] = big_df['symbol'].map(
            symbol_mapping_sync_time).fillna(create_day)

    mongodb_util.save_mongo(big_df, db_name_constant.STOCK_GDFX_FREE_TOP_10_NEW)


# 同步十大股东
def sync_top_ten_gd_task(period, is_new):
    big_df = east_stock_gd_top_10_by_period_api.stock_gdfx_holding_analyse_em(period, is_new)
    now_date = datetime.now()
    sync_time = now_date.strftime('%Y-%m-%d %H:%M:%S')
    create_day = now_date.strftime('%Y-%m-%d')
    big_df['create_day'] = create_day
    big_df['sync_time'] = sync_time
    big_df['update_time'] = sync_time
    big_df['_id'] = big_df['symbol'] + '_' + big_df['period'] + '_' + big_df['shares_number_str']
    query_exist = {'period': period}
    stock_gdfx_top_10_new_df_exist = mongodb_util.find_query_data(db_name_constant.STOCK_GDFX_TOP_10_NEW,
                                                                  query_exist)
    if data_frame_util.is_not_empty(stock_gdfx_top_10_new_df_exist):
        symbol_mapping_create_day = dict(
            zip(stock_gdfx_top_10_new_df_exist['symbol'], stock_gdfx_top_10_new_df_exist['create_day']))

        symbol_mapping_sync_time = dict(
            zip(stock_gdfx_top_10_new_df_exist['symbol'], stock_gdfx_top_10_new_df_exist['sync_time']))

        big_df['create_day'] = big_df['symbol'].map(
            symbol_mapping_create_day).fillna(create_day)
        big_df['sync_time'] = big_df['symbol'].map(
            symbol_mapping_sync_time).fillna(create_day)

    mongodb_util.save_mongo(big_df, db_name_constant.STOCK_GDFX_TOP_10_NEW)


# 同步最新三个季度股东列表
def sync_new_period_ten_gd():
    quarter_list_new = common_util.generate_finance_quarter_dates()
    quarter_list_third = quarter_list_new[0:3]
    for quarter in quarter_list_third:
        try:
            sync_top_ten_free_gd_task(quarter, False)
            sync_top_ten_gd_task(quarter, False)
            logger.info("同步完成:{}", quarter)
        except BaseException as e:
            logger.error("同步异常:{},{}", quarter, str(e))


if __name__ == '__main__':
    quarter_list = common_util.generate_finance_quarter_dates()
    for quarter_test in quarter_list:
        try:
            sync_top_ten_gd_task(quarter_test, False)
            logger.info("同步完成:{}", quarter_test)
        except BaseException as e:
            logger.error("同步异常:{},{}", quarter_test, str(e))
    # sync_top_ten_free_gd_task('20221231')
    # sync_top_ten_gd_task('20251231')
