from app.service.portfolio_diagnose import PortfolioDiagnose
from app.service.result_service_v2 import UserCustomerResultAdaptor
import datetime

from app.utils.draw import draw_combination_chart


def recalculation_fund_comment(ifa_id, customer_id, folio, suggest_result):
    suggest_fund_dict = {}
    suggest_fund_list = []
    suggest_amount_list = []
    for key, value_list in suggest_result.items():
        for value in value_list:
            if value["after_optimization"] <= 0:
                continue
            suggest_fund_dict[value["fund_id"]] = value["fund_type"]
            suggest_fund_list.append(value["fund_id"])
            suggest_amount_list.append(value["after_optimization"])
    sum_amount = sum(suggest_amount_list)
    suggest_weight_list = [round(amount / sum_amount, 4) for amount in suggest_amount_list]

    user_customer = UserCustomerResultAdaptor(ifa_id, customer_id, end_date=datetime.datetime.now().strftime("%Y-%m-%d"))
    group_result = user_customer.calculate_group_result_data()
    cur_folio_result = group_result[folio]

    portfolio_diagnose = PortfolioDiagnose(client_type=1, portfolio=user_customer.all_fund_type_dict,
                                           invest_amount=float(cur_folio_result["total_cost"]),
                                           start_date=user_customer.start_date)

    portfolio_diagnose.proposal_customize(suggest_fund_list, suggest_weight_list, suggest_fund_dict)

    abandon_fund = list(set(cur_folio_result["fund_id_list"]) - set(suggest_fund_list))
    portfolio_diagnose.abandon_fund_score = abandon_fund

    finall_reslut = {}
    finall_reslut["suggestions_result"], finall_reslut["suggestions_result_asset"], \
    finall_reslut["return_compare_data"], \
    finall_reslut["indicator_compare"], finall_reslut["new_group_evaluation"] = \
        portfolio_diagnose.new_evaluation(folio, group_result, user_customer, suggest_fund_dict)

    finall_reslut["return_compare_pic"] = draw_combination_chart(
        finall_reslut["return_compare_data"]["xlabels"],
        finall_reslut["return_compare_data"]["new_combination"],
        finall_reslut["return_compare_data"]["origin_combination"],
        finall_reslut["return_compare_data"]["index"])

    return finall_reslut