import pandas as pd

class VoltageStray:
    def __init__(self):  #参数初始化
        pass

    def cal_vol_uniform(self, df, roll=1, alarm_threshold=5):
        volt_column = [x for x in df.columns if "单体电压" in x]
        all_columns = volt_column.copy()
        all_columns.append("时间戳")
        df = df[all_columns]
        df_filt = df.copy()
        if len(df_filt) > 0:

            # df_filt = df_t.dropna(how='all')
            df_filt = df_filt.reset_index(drop=True)
            volt_count = len(volt_column)-1
            volt_column = volt_column
            df_cell_volt = df_filt[all_columns]
            df_cell_volt = df_cell_volt.dropna().reset_index(drop=True)
            

            # 观察单体电压
            df_rolling = df_cell_volt.loc[:, volt_column].rolling(roll, center=True, min_periods=1).mean()  # 滑动平均值

            # df_temp_change = df_temp_change.dropna().reset_index(drop=True)
            # df_temp_change_2 = df_temp_change_2.dropna().reset_index(drop=True)

            mean = df_rolling.mean(axis=1)
            std = df_rolling.std(axis=1)
            df_rolling_norm = df_rolling.sub(mean, axis=0).div(std,axis=0)

            # fig = plt.figure(figsize=(20,12))
            # ax1 = fig.add_subplot(2,1,1)
            # ax1.set_title("电压 - " + file[0:-5])
            # ax1.plot(df_rolling_norm)

            # plt.savefig('./res/'+str(count) + '-' + file[0:-5] +"--原始电压-"+ '.png')
            # plt.close()
            # plt.clf()
            # plt.cla()

            all_alarm = {'alarm_time':[], 'alarm_cell':[]}
            df_alarm = df_rolling_norm[abs(df_rolling_norm)>1].dropna(how='all')
            for index in df_alarm.index:
                print(index)
                df_temp = df_alarm.loc[index, :].dropna(how='all', axis=0)
                all_alarm['alarm_time'].append(df_cell_volt.loc[index, '时间戳'])
                alarm_cell = df_temp.keys().tolist()
                all_alarm['alarm_cell'].append(str([x[4:] for x in alarm_cell]))
            df_alarm = pd.DataFrame(all_alarm)
            return df_alarm
