from app.service.portfolio_diagnose import PortfolioDiagnose
from app.service.result_service_v2 import UserCustomerResultAdaptor
import datetime
import json
import traceback
from app.utils.draw import draw_combination_chart
from app.utils.format_transfer import npEncoder


def recalculation_fund_comment(args):
    try:
        ifa_id = args.get("ifa_id")
        customer_id = args.get("customer_id")
        folio = args.get("folio")
        suggest_result = json.loads(args.get("suggest_data"))
        # ifa_id = "223164967317544960"
        # customer_id = "app6755804805140590592"

        suggest_fund_dict = {}
        suggest_fund_list = []
        suggest_amount_list = []
        all_sug_amount_dict = {}
        newprcode_dict = {}
        for key, value_list in suggest_result.items():
            if len(value_list) <= 0:
                continue
            for value in value_list:
                if len(value) == 0:
                    continue
                if value.get("newprcode"):
                    newprcode_dict[value["fund_id"]] = value["newprcode"]
                all_sug_amount_dict[value["fund_id"]] = value["after_optimization"]
                value["after_optimization"] = round(float(value["after_optimization"]), 2)
                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(sum_amount * 10000),
                                               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

        dict_result = {}
        new_suggestions_result, new_suggestions_result_asset,  return_compare_data, \
        indicator_compare, new_group_evaluation = \
            portfolio_diagnose.new_evaluation(folio, group_result, user_customer, suggest_fund_dict)
        for key_, value_ in new_suggestions_result.items():
            for new_sug in value_:
                new_sug["after_optimization"] = all_sug_amount_dict.get(new_sug["fund_id"], 0)
                if newprcode_dict.get(new_sug["fund_id"]):
                    new_sug["newprcode"] = newprcode_dict.get(new_sug["fund_id"])

        new_suggestions_result_asset["after"] = sum_amount
        dict_result["suggestions_result"] = new_suggestions_result
        dict_result["suggestions_result_asset"] = new_suggestions_result_asset
        # dict_result["return_compare_data"] = return_compare_data
        dict_result["indicator_compare"] = indicator_compare
        dict_result["new_group_evaluation"] = new_group_evaluation

        new_correlation = portfolio_diagnose.new_correlation
        new_correlation_columns = new_correlation.columns.tolist()
        new_correlation_values = new_correlation.values.tolist()
        dict_result["new_correlation"] = list(zip(range(1, len(new_correlation_columns)+1), new_correlation_columns, new_correlation_values))
        return_compare_data["origin_combination"]["data"] = return_compare_data["origin_combination"]["data"] - 100
        return_compare_data["origin_combination"]["data"][0] = 0.0
        dict_result["return_compare_pic"] = draw_combination_chart(
            return_compare_data["xlabels"],
            return_compare_data["new_combination"],
            return_compare_data["origin_combination"],
            return_compare_data["index"])
    except Exception as e:
        print(traceback.print_exc())
        return False
    print(json.dumps(dict_result, cls=npEncoder, ensure_ascii=False))
    return json.dumps(dict_result, cls=npEncoder, ensure_ascii=False)
