from unify_api.modules.energy_optimize.procedures.energy_utils import \
    get_slots_between_date, get_current_date, format_chart_data, DATA_FORMAT, \
    format_value


def process_capacity(capacity):
    pcs = capacity["PCS"]
    battery = capacity["battery"]
    return {
        "PCS": {
            "value": pcs,
            "unit": "kW"
        },
        "battery": {
            "value": battery,
            "unit": "kWh"
        }
    }


def process_opt_analysis(opt_analysis):
    """用户侧储能"""
    processed_result = {}
    for k in opt_analysis:
        flag = "%s_flag" % k
        processed_result[k] = {}
        red_place = []
        if opt_analysis[k][flag] == False:
            status = "good"
            info = "无储能优化空间。"
        else:
            status = "bad"
            if k == "peak_valley":
                info = "可减少峰时段电网用电%s度/月。" % \
                       opt_analysis["peak_valley"]["peak_valley_kwh"]
                red_place = ["%s度/月" % opt_analysis[k]["peak_valley_kwh"]]
            elif k == "max_demand":
                info = "存在空间，可降低用电成本%s元/月。" % \
                       opt_analysis["max_demand"]["max_demand_benifit"]
                red_place = [
                    "%s元/月" % opt_analysis["max_demand"]["max_demand_benifit"]]
            elif k == "economic_operation":
                info = "存在空间，可降低峰荷%skW，最高负载率降低为%s。" % \
                       (opt_analysis["economic_operation"]["reduce_peak"],
                        opt_analysis["economic_operation"][
                            "reduce_load_factor"])
                red_place = [
                    "%skW" % opt_analysis["economic_operation"]["reduce_peak"],
                    "%s" % opt_analysis["economic_operation"][
                        "reduce_load_factor"]]

        processed_result[k]["status"] = status
        processed_result[k]["info"] = info
        processed_result[k]["red_place"] = red_place
    return processed_result


def pv_process_opt_analysis(opt_analysis):
    """分布式光伏"""
    processed_result = {}
    for k in opt_analysis:
        flag = "%s_flag" % k
        processed_result[k] = {}
        red_place = []
        if opt_analysis[k][flag] == False:
            status = "good"
            # info = "根据用户负荷特效及算法分析，该指标无储能优化空间．"
            info = "无优化空间．"

        else:
            status = "bad"
            if k == "peak_clip":
                info = "可减少峰段电网用电量%s度/月，消纳光伏用电费用需根据用户与光伏电站协商电价确定。" % \
                       opt_analysis[k]["peak_clip_kwh"]
                red_place = ["%s度/月" % opt_analysis[k]["peak_clip_kwh"]]
            elif k == "max_demand":
                info = "存在空间，可降低用电成本%s元/月。" % \
                       opt_analysis["max_demand"]["max_demand_benifit"]
                red_place = [
                    "%s元/月" % opt_analysis["max_demand"]["max_demand_benifit"]]
            elif k == "economic_operation":
                info = "存在空间，可降低峰荷%skW，最高负载率降低为%s。" % \
                       (opt_analysis["economic_operation"]["reduce_peak"],
                        opt_analysis["economic_operation"][
                            "reduce_load_factor"])
                red_place = [
                    "%skW" % opt_analysis["economic_operation"]["reduce_peak"],
                    "%s" % opt_analysis["economic_operation"][
                        "reduce_load_factor"]]

        processed_result[k]["status"] = status
        processed_result[k]["info"] = info
        processed_result[k]["red_place"] = red_place
    return processed_result


def get_user_energy_storage_curve(inlid, storage_optimize_tools_data):
    # 优化曲线
    opt_curve = storage_optimize_tools_data["opt_curve"]

    slots = get_slots_between_date(get_current_date(), get_current_date(),
                                   "15min")
    curve_datas = {}
    for slot in slots:
        curve_datas[slot[0]] = {}
        for item in ["Unoptimized load curve", "Optimized load curve",
                     "Load action curve"]:
            curve_datas[slot[0]][item] = ""
        for value in opt_curve:
            if value["quarter_time"] == slot[0].strftime("%H:%M:%S"):
                curve_datas[slot[0]]["Unoptimized load curve"] = value[
                    "load_curve"]
                curve_datas[slot[0]]["Optimized load curve"] = value[
                    "load_bat_curve"]
                curve_datas[slot[0]]["Load action curve"] = value["bat_curve"]
    capacity_scale_chart = {
        "data": format_chart_data(curve_datas, date_type="15min"),
        "unit": DATA_FORMAT["default"]["unit"]
    }
    return capacity_scale_chart


def get_user_energy_storage_economic_evaluate(inlid,
                                              storage_optimize_tools_data):
    """
    工厂版　用电优化　综合能源优化工具　用户侧储能　经济测算
    :param inlid:
    :return:
    """
    # 经济测算
    invest_income_table = {}
    for values in storage_optimize_tools_data["economic_evaluate"][
        "invest_income_table"]:
        keys = list(values.keys())
        k = values["rate_of_investment"]
        invest_income_table[k] = [format_value(values[sub_k], "big_money4")[0]
                                  for sub_k in keys[1:]]
    return {
        "investment": {
            "value": format_value(
                storage_optimize_tools_data["economic_evaluate"]["ttl_invest"],
                "big_money")[0],
            "unit": DATA_FORMAT["big_money"]["unit"]
        },
        "conversion_days": {
            "value":
                format_value(storage_optimize_tools_data["economic_evaluate"][
                                 "year_use_days"],
                             "day")[0],
            "unit": DATA_FORMAT["day"]["unit"]
        },
        "peak_valley_year_income": {
            "value": format_value(
                storage_optimize_tools_data["economic_evaluate"][
                    "peak_valley_year_income"],
                "big_money")[0],
            "unit": DATA_FORMAT["big_money"]["unit"]
        },
        "max_demand_year_income": {
            "value": format_value(
                storage_optimize_tools_data["economic_evaluate"][
                    "max_demand_year_income"],
                "big_money")[0],
            "unit": DATA_FORMAT["big_money"]["unit"]
        },
        "ttl_income": {
            "value": format_value(
                storage_optimize_tools_data["economic_evaluate"]["ttl_income"],
                "big_money")[0],
            "unit": DATA_FORMAT["big_money"]["unit"]
        },
        "static_invest_years": {
            "value": format_value(
                storage_optimize_tools_data["economic_evaluate"][
                    "static_invest_years"], "year")[0],
            "unit": DATA_FORMAT["year"]["unit"]
        },
        "invest_income_table": invest_income_table
    }
