import sys
import numpy as np
import pandas as pd
import string
import os
from pandas import Series
from matplotlib import pyplot as plt
from pandas.core.frame import DataFrame
from pandas.core.indexes.base import Index
from LIB.BACKEND import DBManager
import datetime
import time
import string
import re



class CtrlSafty:
    def __init__(self):
        pass
    def main(sn,param,bms_info,df_Diag_Ram_in):
        df_Diag_Ram_Update_inside=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
        df_Diag_Ram_Update_inside=df_Diag_Ram_Update_inside.append(df_Diag_Ram_in)
        global QuitErrCount 
        VolStarkCount=[0 for i in range(param.CellVoltNums)]
        VolCount=0
        QuitErrCount=[0 for i in range(param.FaultCount)]

        #--------------该电池的所有当前故障-------------




        df_Diag_Ram_Update_inside=CtrlSafty.TempCtrlDiag(sn,bms_info,param,df_Diag_Ram_Update_inside) 
        return df_Diag_Ram_Update_inside



    def TempCtrlDiag(sn,bms_info,param,df_Diag_Ram):
        ErrorFlg=0
        CellTempMax=0
        OtherTempMax=0

        CellTempNum=['单体温度'+str(i) for i in range(1,param.CellTempNums+1)]
        if 'MXMLX' in sn:
            OtherTempNum=['其他温度1','其他温度3','其他温度4','其他温度5']
        else:
            OtherTempNum=['其他温度'+str(i) for i in range(1,param.OtherTempNums+1)]
        
        CellTempMax=bms_info[bms_info[CellTempNum]>(param.CellMaxUSBTemp-5)]
        CellTempMax=CellTempMax[CellTempMax<(param.CellMaxUSBTemp+5)].dropna(axis=0,how='all')
        OtherTempMax=bms_info[bms_info[OtherTempNum]>(param.OtherOTlmt-10)]
        OtherTempMax=OtherTempMax[OtherTempMax[OtherTempNum]<(param.OtherOTlmt+5)].dropna(axis=0,how='all')
        if len(CellTempMax) and len(OtherTempMax):
            QuitErrCount[57]=0
            if not 'C357' in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障，则压入该故障
                df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_info.loc[len(bms_info)-1,'时间戳'],'0000-00-00 00:00:00',sn,'C357',3,'电芯温度高','立即联系用户确认电池状态']
                ErrorFlg=1            
            else:#如果故障发生当前故障中有该故障，则不进行操作
                pass
        else:
            if 'C357' in df_Diag_Ram['code'].values.tolist():
                QuitErrCount[57]=QuitErrCount[57]+1
                if QuitErrCount[57]>3:
                    QuitErrCount[57]=4
                    end_time=datetime.datetime.now()
                    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
                    df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']=='C357'].index,['end_time']]=end_time
                else:
                    pass
            else:
                pass
        return df_Diag_Ram
