import CBMSSafetyAlarm
import pymysql
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_bms_ram, df_alarm_ram):

    start=time.time()
    now_time=datetime.datetime.now() #-datetime.timedelta(seconds=3600*24+3600*14.6)
    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')

    #数据库配置
    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
    port=3306
    user='qx_algo_readonly'
    password = 'qx@123456'

    #读取故障结果库中code=='C599'且end_time='0000-00-00 00:00:00'...............................
    db='safety_platform'
    mysql = pymysql.connect (host=host, port=port, user=user, password=password, database=db)
    cursor = mysql.cursor()
    param='start_time,end_time,product_id,code,level,info,advice'
    tablename='all_fault_info'
    sql =  "select %s from %s where code='C599' and end_time='0000-00-00 00:00:00'" %(param,tablename)
    cursor.execute(sql)
    res = cursor.fetchall()
    df_diag_ram= pd.DataFrame(res,columns=param.split(','))
    cursor.close()
    mysql.close()

    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)

        #电池诊断................................................................................................................................................................
        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]
        df_alarm_ram_sn=df_alarm_ram[df_alarm_ram['sn']==sn]
        if df_diag_ram_sn.empty:   
            SafetyAlarm=CBMSSafetyAlarm.SafetyAlarm(sn,celltype,df_bms, df_bms_ram_sn, df_alarm_ram_sn)
            df_diag_res, df_bms_res, df_ram_res=SafetyAlarm.safety_alarm_diag() 

            #更新bms的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_alarm_ram.loc[df_alarm_ram['sn']==sn].index
            df_alarm_ram=df_alarm_ram.drop(index=sn_index)
            df_alarm_ram=df_alarm_ram.append(df_ram_res)

            #当前热失控故障写入数据库
            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')
              
        #当前热失控已超过一天变为历史故障并更改数据库
        else:
            fault_time=datetime.datetime.strptime(df_diag_ram_sn.iloc[-1]['start_time'], '%Y-%m-%d %H:%M:%S')
            if (now_time-fault_time).total_seconds()>24*3600:
                df_diag_ram_sn['end_time']=end_time
                df_diag_ram_sn['Batpos']=1
                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控报警.txt','a') as file:
                    file.write(str(tuple(df_diag_ram_sn.iloc[-1]))+'\n')

        end=time.time()
        print(end-start)
    
    return df_bms_ram,df_alarm_ram
#...................................................主进程...........................................................................................................
def mainprocess():
    global df_bms_ram1, df_bms_ram2, df_alarm_ram1, df_alarm_ram2, SNnums
    process = 2
    pool = multiprocessing.Pool(processes = process)

    res_list=[]
    ram_list1=[df_bms_ram1, df_bms_ram2]
    ram_list2=[df_alarm_ram1, df_alarm_ram1]
    for i in range(process):
        sn_list = SNnums[i]
        df_bms_ram=ram_list1[i]
        df_alarm_ram=ram_list2[i]
        df_res=pool.apply_async(diag_cal, (sn_list,df_bms_ram,df_alarm_ram)).get()
        res_list.append(df_res)
    
    pool.close()
    pool.join()
    df_bms_ram1=res_list[0][0]
    df_bms_ram2=res_list[1][0]
    df_alarm_ram1=res_list[0][1]
    df_alarm_ram2=res_list[1][1]


#...............................................主函数起定时作用.......................................................................................................................
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_4840, SNnums_6040 + SNnums_6060]
    # SNnums=[['MGMLXN750N2189008','PK504B10100004328'], ['PK500A20100000752','PK504B10100004387']]
    
    mylog=log.Mylog('log_diag.txt','error')
    mylog.logcfg()
    
    #参数初始化
    df_bms_ram1=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
    df_bms_ram2=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
    df_alarm_ram1=pd.DataFrame(columns=['sn','time','safetywarning1','safetywarning2'])
    df_alarm_ram2=pd.DataFrame(columns=['sn','time','safetywarning1','safetywarning2'])

    mainprocess()
    #定时任务.......................................................................................................................................................................
    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)