from datetime import datetime as dt
from typing import List

import pandas as pd
from py_jftech import component, autowired

from api import RoboReportor


@component(bean_name='year-range-report')
class YearRangeReport(RoboReportor):

    @autowired(names={'combo': 'combo-report'})
    def __init__(self, combo: RoboReportor = None):
        self._combo = combo

    @property
    def report_name(self) -> str:
        return '单年区间业绩'

    def load_report(self, max_date=dt.today(), min_date=None) -> List[dict]:
        datas = pd.DataFrame(self._combo.load_report(max_date=max_date, min_date=min_date))
        if not datas.empty:
            datas['year'] = datas['date'].dt.year
            datas.set_index('date', inplace=True)
            result = pd.DataFrame(columns=datas.columns)
            last_data = None
            for year, group_data in datas.groupby(by='year', group_keys=False):
                group_data = group_data.drop(columns='year')
                if last_data is None:
                    last_data = group_data.iloc[0]
                result.loc[year] = group_data.iloc[-1] / last_data - 1
                last_data = group_data.iloc[-1]
            result.drop(columns='year', inplace=True)
            result = round(result * 100, 4)
            result.reset_index(inplace=True)
            result.rename(columns={'index': 'year'}, inplace=True)
            return result.to_dict('records')
        return []
