import numpy as np
import pandas as pd
from LIB.MIDDLE.SaftyCenter.Common import FeiShuData
from LIB.MIDDLE.SaftyCenter.Common import DBDownload
import time, datetime
from datetime import timedelta
from pandas.core.frame import DataFrame
from apscheduler.schedulers.blocking import BlockingScheduler

class DataSta():
    def __init__(self) -> None:
        pass
    def SaftyWarningSta(df_fltinfo,start_time,end_time,factory_info):
        if  '骑享' in factory_info:
            df_fltinfo=df_fltinfo[~df_fltinfo['product_id'].str.contains('TJMCL')]
            start_time=start_time+str(' 00:00:00')
            start_time=datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            start_time=start_time+datetime.timedelta(days=1)
            start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
            SftyPlt_Data_Total=len(df_fltinfo)#总报警数
            CS_Warning_Total_Finish=df_fltinfo[df_fltinfo['batpos']==1]
            CS_Warning_Total_Finish_Count=len(CS_Warning_Total_Finish) #平台报警总运维数
            SftyPlt_Data_day=len(df_fltinfo[df_fltinfo['start_time']>=start_time])#日、周总报警数
            CS_Warning_day_Finish=CS_Warning_Total_Finish[CS_Warning_Total_Finish['start_time']>=start_time]#日/周运维数
            CS_Warning_day_Finish_Count=len(CS_Warning_day_Finish)
            SftyPlt_EmgcyData_day=df_fltinfo[df_fltinfo['start_time']>=start_time] #紧急报警数
            SftyPlt_EmgcyData_day=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['level']>3]
            SftyPlt_EmgcyData_day_Count=len(SftyPlt_EmgcyData_day)
            SftyPlt_EmgcyData_day_Finish=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['batpos']==1]
            SftyPlt_EmgcyData_day_Finish_Count=len(SftyPlt_EmgcyData_day_Finish)
            if int(SftyPlt_Data_day)>0:
                OprationManageRate=round(float(CS_Warning_day_Finish_Count/SftyPlt_Data_day)*100,2)
            else:
                OprationManageRate=100
            if int(SftyPlt_EmgcyData_day_Count)>0:
                OprationManageEmgcyRate=round(float(SftyPlt_EmgcyData_day_Finish_Count/SftyPlt_EmgcyData_day_Count)*100,2)
            else:
                OprationManageEmgcyRate=100
            PK504FltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('PK504')])
            PK502FltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('PK502')])
            PK500FltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('PK500')])
            MGMCLFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('MGMCL')])
            MGMLXFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('MGMLX')])
            # print('总报警数=',SftyPlt_Data_Total)
            # print('总完成运维数=',CS_Warning_Total_Finish_Count)
            # print('周报警数=',SftyPlt_Data_day)
            # print('周完成运维数=',CS_Warning_day_Finish_Count)
            # print('周紧急报警数=',SftyPlt_EmgcyData_day)
            # print('周紧急完成运维数=',SftyPlt_EmgcyData_day_Finish_Count)
            # print('周运维率=',OprationManageRate)
            # print('周紧急运维率=',OprationManageEmgcyRate)
            # print('PK504总报警=',PK504FltData_Count)
            # print('PK502总报警=',PK502FltData_Count)
            # print('PK500总报警=',PK500FltData_Count)
            # print('格林美总报警=',MGMCLFltData_Count)
            # print('自研总报警=',MGMLXFltData_Count)
            FltAlarmInfo=DataFrame(columns=['SftyPlt_Data_Total','CS_Warning_Total_Finish_Count','SftyPlt_Data_day','CS_Warning_day_Finish_Count','SftyPlt_EmgcyData_day','SftyPlt_EmgcyData_day_Finish_Count','OprationManageRate','OprationManageEmgcyRate'])
            Celltype=DataFrame(columns=['PK504','PK502','PK500','MGMCL','MGMLX'])
            FltAlarmInfo.loc[0]=[SftyPlt_Data_Total,CS_Warning_Total_Finish_Count,SftyPlt_Data_day,CS_Warning_day_Finish_Count,SftyPlt_EmgcyData_day_Count,SftyPlt_EmgcyData_day_Finish_Count,OprationManageRate,OprationManageEmgcyRate]
            Celltype.loc[0]=[PK504FltData_Count,PK502FltData_Count,PK500FltData_Count,MGMCLFltData_Count,MGMLXFltData_Count]
        elif '金茂换电' in factory_info:
            df_fltinfo=df_fltinfo[df_fltinfo['product_id'].str.contains('TJMCL')]
            start_time=start_time+str(' 00:00:00')
            start_time=datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            start_time=start_time+datetime.timedelta(days=1)
            start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
            SftyPlt_Data_Total=len(df_fltinfo)#总报警数
            CS_Warning_Total_Finish=df_fltinfo[df_fltinfo['batpos']==1]
            CS_Warning_Total_Finish_Count=len(CS_Warning_Total_Finish) #平台报警总运维数
            SftyPlt_Data_day=len(df_fltinfo[df_fltinfo['start_time']>=start_time])#日、周总报警数
            CS_Warning_day_Finish=CS_Warning_Total_Finish[CS_Warning_Total_Finish['start_time']>=start_time]#日/周运维数
            CS_Warning_day_Finish_Count=len(CS_Warning_day_Finish)
            SftyPlt_EmgcyData_day=df_fltinfo[df_fltinfo['start_time']>=start_time] #紧急报警数
            SftyPlt_EmgcyData_day=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['level']>3]
            SftyPlt_EmgcyData_day_Count=len(SftyPlt_EmgcyData_day)
            SftyPlt_EmgcyData_day_Finish=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['batpos']==1]
            SftyPlt_EmgcyData_day_Finish_Count=len(SftyPlt_EmgcyData_day_Finish)
            if int(SftyPlt_Data_day)>0:
                OprationManageRate=round(float(CS_Warning_day_Finish_Count/SftyPlt_Data_day)*100,2)
            else:
                OprationManageRate=100
            if int(SftyPlt_EmgcyData_day_Count)>0:
                OprationManageEmgcyRate=round(float(SftyPlt_EmgcyData_day_Finish_Count/SftyPlt_EmgcyData_day_Count)*100,2)
            else:
                OprationManageEmgcyRate=100
            TJMCLFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('TJMCL')])
            # print('总报警数=',SftyPlt_Data_Total)
            # print('总完成运维数=',CS_Warning_Total_Finish_Count)
            # print('周报警数=',SftyPlt_Data_day)
            # print('周完成运维数=',CS_Warning_day_Finish_Count)
            # print('周紧急报警数=',SftyPlt_EmgcyData_day)
            # print('周紧急完成运维数=',SftyPlt_EmgcyData_day_Finish_Count)
            # print('周运维率=',OprationManageRate)
            # print('周紧急运维率=',OprationManageEmgcyRate)
            # print('PK504总报警=',PK504FltData_Count)
            # print('PK502总报警=',PK502FltData_Count)
            # print('PK500总报警=',PK500FltData_Count)
            # print('格林美总报警=',MGMCLFltData_Count)
            # print('自研总报警=',MGMLXFltData_Count)
            FltAlarmInfo=DataFrame(columns=['SftyPlt_Data_Total','CS_Warning_Total_Finish_Count','SftyPlt_Data_day','CS_Warning_day_Finish_Count','SftyPlt_EmgcyData_day','SftyPlt_EmgcyData_day_Finish_Count','OprationManageRate','OprationManageEmgcyRate'])
            Celltype=DataFrame(columns=['TJMCL'])
            FltAlarmInfo.loc[0]=[SftyPlt_Data_Total,CS_Warning_Total_Finish_Count,SftyPlt_Data_day,CS_Warning_day_Finish_Count,SftyPlt_EmgcyData_day_Count,SftyPlt_EmgcyData_day_Finish_Count,OprationManageRate,OprationManageEmgcyRate]
            Celltype.loc[0]=[TJMCLFltData_Count]
        else:
            FltAlarmInfo=DataFrame(columns=['SftyPlt_Data_Total','CS_Warning_Total_Finish_Count','SftyPlt_Data_day','CS_Warning_day_Finish_Count','SftyPlt_EmgcyData_day','SftyPlt_EmgcyData_day_Finish_Count','OprationManageRate','OprationManageEmgcyRate'])
            Celltype=DataFrame(columns=['None'])
        return FltAlarmInfo,Celltype
    def WeekInfoSta(df_fltinfo,start_time,end_time):
        df_fltinfo=df_fltinfo[df_fltinfo['start_time']>=start_time]
        FaultLvlCount=DataFrame(columns=['level','count'])
        FaultLvlCount=df_fltinfo.groupby('level').count().T.head(1).T
        FaultLvlCount=FaultLvlCount.reset_index(drop=False)
        
        return FaultLvlCount
    def SftyWrngClsfy(df_fltinfo):
        DsnSaftyCode=[]
        DataSaftyCode=[]
        SamplingSaftyCode=[2,10,50,53,54,55,56]
        HvSaftyCode=[]
        SysSaftyCode=[]
        CellSaftyCode=[3,5,6,7,8,9,10,11,13,14,15,16,17,19,20,21,15,16,17,19,23,24,25,26,29,30,31,51,119]
        CtrlSatyCode=[4,12,18,20,21,22,57]
        StateSaftyCode=[27,28,52]
        
        DsnSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(DsnSaftyCode)])
        DataSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(DataSaftyCode)])
        HvSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(HvSaftyCode)])
        SysSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(SysSaftyCode)])
        SamplingSatyCount=len(df_fltinfo[df_fltinfo['code'].isin(SamplingSaftyCode)])
        CellSaftyCount=len(df_fltinfo[df_fltinfo['code'].isin(CellSaftyCode)])
        CtrlSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(CtrlSatyCode)])
        StateSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(StateSaftyCode)])
        SatftyCount=DataFrame(columns=['DsnSaftyCodeCount','DataSaftyCodeCount','HvSaftyCodeCount','SysSaftyCodeCount','SamplingSatyCount','CellSaftyCount','CtrlSaftyCodeCount','StateSaftyCodeCount'])
        SatftyCount.loc[0]=[DsnSaftyCodeCount,DataSaftyCodeCount,HvSaftyCodeCount,SysSaftyCodeCount,SamplingSatyCount,CellSaftyCount,CtrlSaftyCodeCount,StateSaftyCodeCount]
        # print('设计安全分数为',DsnSaftyCodeCount)
        # print('数据安全分数为',DataSaftyCodeCount)
        # print('高压安全分数为',HvSaftyCodeCount)
        # print('系统安全分数为',SysSaftyCodeCount)
        # print('采样安全分数为',SamplingSatyCount)
        # print('电芯安全分数为',CellSaftyCount)
        # print('控制安全分数为',CtrlSaftyCodeCount)
        # print('状态安全分数为',StateSaftyCodeCount)
        # print('---------------------------------------------------------------------------')
        return SatftyCount
    def AccumInfo(df_last_accum,df_FirstDataTime,end_time,factory_info):
        if '骑享' in factory_info:
            df_last_accum=df_last_accum[~df_last_accum['devcode'].str.contains('TJMCL')]
            MaxAccumAh=df_last_accum['dsg_ahaccum'].max()
            TotalAccumAh=df_last_accum['dsg_ahaccum'].sum()
            PK504_Ah=df_last_accum[df_last_accum['devcode'].str.contains('PK504')]
            PK504_Ah_Max=(PK504_Ah['dsg_ahaccum'].max())/60
            PK502_Ah=df_last_accum[df_last_accum['devcode'].str.contains('PK502')]
            PK502_Ah_Max=(PK502_Ah['dsg_ahaccum'].max())/40
            PK500_Ah=df_last_accum[df_last_accum['devcode'].str.contains('PK500')]
            PK500_Ah_Max=(PK500_Ah['dsg_ahaccum'].max())/40
            MGMCL_Ah=df_last_accum[df_last_accum['devcode'].str.contains('MGMCL')]
            MGMCL_Ah_Max=(MGMCL_Ah['dsg_ahaccum'].max())/50
            MGMLX_Ah=df_last_accum[df_last_accum['devcode'].str.contains('MGMLX')]
            MGMLX_Ah_Max=(MGMLX_Ah['dsg_ahaccum'].max())/50
            MaxCycle=round(max(PK504_Ah_Max,PK502_Ah_Max,PK500_Ah_Max,MGMCL_Ah_Max,MGMLX_Ah_Max),0)
            deltatimeMax=0
            deltatime=DataFrame(columns=['runningdate'])
            df_FirstDataTime=df_FirstDataTime[~df_FirstDataTime['sn'].str.contains('TJMCL')]
            df_FirstDataTime=df_FirstDataTime.dropna(how='any')
            df_FirstDataTime=df_FirstDataTime.reset_index(drop=False)
            for i in range(0,len(df_FirstDataTime)):
                End_time=datetime.datetime.now()
                df_FirstDataTime.loc[i,'first_data_time']=df_FirstDataTime.loc[i,'first_data_time'].strftime('%Y-%m-%d')
                df_FirstDataTime.loc[i,'first_data_time']=datetime.datetime.strptime(df_FirstDataTime.loc[i,'first_data_time'],'%Y-%m-%d')
                deltatime.loc[i,'runningdate']=(End_time-df_FirstDataTime.loc[i,'first_data_time'])
                deltatime.loc[i,'runningdate']= deltatime.loc[i,'runningdate'].total_seconds()/3600
            MaxRunningHour=int(deltatime['runningdate'].max())
            TotalRunHour=int(deltatime['runningdate'].sum())
        elif '金茂换电' in factory_info:
            df_last_accum=df_last_accum[df_last_accum['devcode'].str.contains('TJMCL')]
            df_last_accum=df_last_accum[df_last_accum['dsg_ahaccum']<429496729]
            MaxAccumAh=df_last_accum['dsg_ahaccum'].max()
            TotalAccumAh=df_last_accum['dsg_ahaccum'].sum()
            TJMCL_Ah=df_last_accum[df_last_accum['devcode'].str.contains('TJMCL')]
            TJMCL_Ah_Max=(TJMCL_Ah['dsg_ahaccum'].max())/(228*2)
            MaxCycle=round(TJMCL_Ah_Max,0)
            deltatimeMax=0
            deltatime=DataFrame(columns=['runningdate'])
            df_FirstDataTime=df_FirstDataTime[df_FirstDataTime['sn'].str.contains('TJMCL')]
            df_FirstDataTime=df_FirstDataTime.dropna(how='any')
            df_FirstDataTime=df_FirstDataTime.reset_index(drop=False)
            for i in range(0,len(df_FirstDataTime)):
                End_time=datetime.datetime.now()
                df_FirstDataTime.loc[i,'first_data_time']=df_FirstDataTime.loc[i,'first_data_time'].strftime('%Y-%m-%d')
                df_FirstDataTime.loc[i,'first_data_time']=datetime.datetime.strptime(df_FirstDataTime.loc[i,'first_data_time'],'%Y-%m-%d')
                deltatime.loc[i,'runningdate']=(End_time-df_FirstDataTime.loc[i,'first_data_time'])
                deltatime.loc[i,'runningdate']= deltatime.loc[i,'runningdate'].total_seconds()/3600
            MaxRunningHour=int(deltatime['runningdate'].max())
            TotalRunHour=int(deltatime['runningdate'].sum())
        return MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour

    def FltBatPosition(df_last_pos,df_fltinfo,factory_info):
        df_Diag_Ram=df_fltinfo[df_fltinfo['batpos']==0].drop_duplicates(subset=['product_id'],keep=False)
        all_location_info=DataFrame(columns=['factory','product_id','lat','lon'])
        df_last_pos.rename(columns={'devcode':'product_id'},inplace=True)
        df_Diag_Ram_Pos_a=pd.concat([df_Diag_Ram,df_last_pos]).drop_duplicates(subset=['product_id'],keep='first')
        df_Diag_Ram_Pos_b=pd.concat([df_Diag_Ram,df_last_pos]).drop_duplicates(subset=['product_id'],keep=False)
        df_Diag_Ram_Pos=df_Diag_Ram_Pos_a.append(df_Diag_Ram_Pos_b).drop_duplicates(subset=['product_id'],keep=False)
        df_Diag_Ram_Pos=df_Diag_Ram_Pos.reset_index(drop=True)
        for i in range(0,len(df_Diag_Ram_Pos)):
            df_last_pos_list=df_last_pos['product_id'].values.tolist()
            if  str(df_Diag_Ram_Pos.loc[i,'product_id']) in df_last_pos_list:
                pos_la_temp=df_last_pos[df_last_pos['product_id']==(df_Diag_Ram_Pos.loc[i,'product_id'])].reset_index(drop=True)
                all_location_info.loc[i,'lat']=pos_la_temp.loc[0,'latitude']
                all_location_info.loc[i,'lon']=pos_la_temp.loc[0,'longitude']
                all_location_info.loc[i,'factory']=factory_info
                all_location_info.loc[i,'product_id']=df_Diag_Ram_Pos.loc[i,'product_id']
        return all_location_info