import CBMSSafetyAlarm
import datetime
import pandas as pd
import multiprocessing
from LIB.BACKEND import DBManager, Log
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log


#...................................电池包电芯安全诊断函数......................................................................................................................
def diag_cal(sn_list, df_diag_ram, df_bms_ram):
    
    start=time.time()
    now_time=datetime.datetime.now()
    start_time=now_time-datetime.timedelta(seconds=70)
    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
    end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')

    for sn in sn_list:
        if 'PK500' in sn:
            celltype=1 #6040三元电芯
        elif 'PK502' in sn:
            celltype=2 #4840三元电芯
        elif 'K504B' in sn:
            celltype=99    #60ah林磷酸铁锂电芯
        elif 'MGMLXN750' in sn:
            celltype=3 #力信50ah三元电芯
        elif 'MGMCLN750' or 'UD' in sn: 
            celltype=4 #CATL 50ah三元电芯
        else:
            print('SN：{}，未找到对应电池类型！！！'.format(sn))
            continue
            # sys.exit()

        #读取原始数据库数据........................................................................................................................................................
        dbManager = DBManager.DBManager()
        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
        df_bms = df_data['bms']
        # print(df_bms)

        #电池诊断................................................................................................................................................................
        if not df_bms.empty:
            df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
            df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
            if df_diag_ram_sn.empty:
                SafetyAlarm=CBMSSafetyAlarm.SafetyAlarm(sn,celltype,df_bms, df_bms_ram_sn)
                df_diag_res, df_bms_res=SafetyAlarm.diag() 

                #更新bms的ram数据 和 diag的Ram数据
                sn_index=df_bms_ram.loc[df_bms_ram['sn']==sn].index
                df_bms_ram=df_bms_ram.drop(index=sn_index)
                df_bms_ram=df_bms_ram.append(df_bms_res)

                sn_index=df_diag_ram.loc[df_diag_ram['product_id']==sn].index
                df_diag_ram=df_diag_ram.drop(index=sn_index)
                df_diag_ram=df_diag_ram.append(df_diag_res)
                df_diag_ram.reset_index(inplace=True,drop=True)     #重置索引

                #当前热失控故障写入数据库
                if not df_diag_res.empty:
                    with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控.txt','a') as file:
                        file.write(str(tuple(df_diag_res.iloc[-1]))+'\n')
                
            #当前热失控已超过三天变为历史故障并写入数据库，并删除原有数据库中的当前故障和ram中的当前故障
            elif (now_time-df_bms_ram_sn.iloc[-1]['time']).total_seconds()>3*24*3600:
                df_diag_ram=df_diag_ram.drop(df_diag_ram['sn']==sn)    #删除ram中的当前故障
                df_bms_ram_sn.iloc[-1]['end_time']=now_time
                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控.txt','a') as file:
                        file.write(str(tuple(df_diag_res.iloc[-1]))+'\n')



        #故障处理........................................................................................................................................................

        end=time.time()
        print(end-start)
        # print(df_soh)

#...................................................主进程...........................................................................................................
def mainprocess():
    global SNnums
    global df_diag_ram
    global df_bms_ram
    process = 2
    pool = multiprocessing.Pool(processes = process)

    for i in range(process):
        sn_list = SNnums[i]
        pool.apply_async(diag_cal, (sn_list,df_diag_ram,df_bms_ram))

    pool.close()
    pool.join()


#...............................................主函数起定时作用.......................................................................................................................
if __name__ == "__main__":
    
    excelpath=r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\sn-20210903.xlsx'
    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
    SNnums_6060=SNdata_6060['SN号'].tolist()
    SNnums_6040=SNdata_6040['SN号'].tolist()
    SNnums_4840=SNdata_4840['SN号'].tolist()
    SNnums_L7255=SNdata_L7255['SN号'].tolist()
    SNnums_C7255=SNdata_C7255['SN号'].tolist()
    SNnums_U7255=SNdata_U7255['SN号'].tolist()
    SNnums=[SNnums_L7255 + SNnums_C7255 + SNnums_U7255, SNnums_6040 + SNnums_4840 + SNnums_6060]
    # SNnums=['PK50201A000002201']
    
    mylog=log.Mylog('log_diag.txt','error')
    mylog.logcfg()

    #............................模块运行前，先读取数据库中所有结束时间为0的数据，需要从数据库中读取...................................
    result=pd.read_excel(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\result.xlsx')
    df_diag_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']==119)]
    df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])

    #定时任务.......................................................................................................................................................................
    scheduler = BlockingScheduler()
    scheduler.add_job(mainprocess, 'interval', seconds=60, id='diag_job')

    try:  
        scheduler.start()
    except Exception as e:
        scheduler.shutdown()
        print(repr(e))
        mylog.logopt(e)