from unify_api.constants import BASE_PRJ_DIR
from unify_api.modules.shidianu.service.componentStage import componentStage
from unify_api.modules.shidianu.service.decomp_main import pieceWise
from unify_api.modules.shidianu.service.electricProportion import \
    electricProportion
import os
import pandas as pd
import matplotlib.pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
illegalConfig_hold = 2500
highPowerEquip_hold = 3000

SDU_DIR = os.path.join(BASE_PRJ_DIR, "unify_api/modules/shidianu")


# 设备识别算法，结果
def hisPieceFind(params, each_data):
    day_time = each_data["time"].values.tolist()
    power_pa = each_data["p"].values

    day_time_all = [pd.to_datetime(day_time[i], format='%Y-%m-%d %H:%M:%S')
                    for i in
                    range(len(day_time))]
    power_pa_Series = pd.Series(power_pa, index=day_time_all)

    power_pa_Series_diff = power_pa_Series.diff(1)

    power_pa_Series_diff_list = list(power_pa_Series_diff[1:])
    power_pa_Series_diff_index_list = list(power_pa_Series_diff.index[1:])

    maxVals = [max(power_pa_Series_diff_list) * 1000,
               power_pa_Series_diff_index_list[
                   power_pa_Series_diff_list.index(
                       max(power_pa_Series_diff_list))],
               max(power_pa) * 1000,
               day_time_all[list(power_pa).index(max(power_pa))]]
    # wf.write(str(maxVals[1]) + "," + str(maxVals[0]) + "," + str(
    #     maxVals[3]) + "," + str(maxVals[2]) + "\n")
    aircondRunStages, electroRunStages, heaterRunStages, refrigRunStages = pieceWise(
        eachdata=each_data,
        params=params)
    stageComponent, timestage, timeOrder, actionOrder = componentStage(
        aircondRunStages=aircondRunStages,
        electroRunStages=electroRunStages,
        heaterRunStages=heaterRunStages,
        refrigRunStages=refrigRunStages)
    if len(aircondRunStages) > 0:
        aircondRunStages = [
            [aircondRunStages[i * 2], aircondRunStages[i * 2 + 1]] for i in
            range(len(aircondRunStages) // 2)]
    if len(electroRunStages) > 0:
        electroRunStages = [
            [electroRunStages[i * 2], electroRunStages[i * 2 + 1]] for i in
            range(len(electroRunStages) // 2)]
    if len(heaterRunStages) > 0:
        heaterRunStages = [[heaterRunStages[i * 2], heaterRunStages[i * 2 + 1]]
                           for i in range(len(heaterRunStages) // 2)]
    if len(refrigRunStages) > 0:
        refrigRunStages = [[refrigRunStages[i * 2], refrigRunStages[i * 2 + 1]]
                           for i in range(len(refrigRunStages) // 2)]

    resultDict = {"设备运行情况": stageComponent, "运行时间段": timestage,
                  "行为列表": actionOrder, "行为时间": timeOrder,
                  "空调运行时段": aircondRunStages, "电磁炉运行时段": electroRunStages,
                  "热水器运行时段": heaterRunStages,
                  "电冰箱运行时段": refrigRunStages}

    return resultDict, power_pa, day_time


def addLabels(sid="sid", aircondRunStages="", electroRunStages="",
              heaterRunStages="", refrigRunStages="", timeOrder="",
              actionOrder="", power="", timeAll=""):
    fig, ax = plt.subplots()
    ax.plot(power)
    for eachtime in range(len(timeOrder)):
        index = timeAll.index(timeOrder[eachtime])
        if actionOrder[eachtime][:2] == "关闭":

            if 0.6691 + power[index] < max(power[index - 3:index + 3]):
                plt.annotate(actionOrder[eachtime], xy=(index, power[index]),
                             xytext=(index + 30, 1.6691 + power[index]),
                             arrowprops=dict(arrowstyle='->'), fontsize=6)
            else:
                plt.annotate(actionOrder[eachtime], xy=(index, power[index]),
                             xytext=(index + 30, 0.6691 + power[index]),
                             arrowprops=dict(arrowstyle='->'), fontsize=6)
        elif actionOrder[eachtime][:2] == "开启":
            if power[index] > 2.3:
                plt.annotate(actionOrder[eachtime], xy=(index, power[index]),
                             xytext=(index - 100, 0.3691 + power[index]),
                             arrowprops=dict(arrowstyle='->'), fontsize=6)
            else:
                plt.annotate(actionOrder[eachtime], xy=(index, power[index]),
                             xytext=(index - 100, 0.6691 + power[index]),
                             arrowprops=dict(arrowstyle='->'), fontsize=6)
    x = [each.split(" ")[1][:-3] for each in timeAll]
    plt.show()
    return 0

