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

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

