import CBMSBatDiag
import pymysql
import datetime
import pandas as pd
from LIB.BACKEND import DBManager
from sqlalchemy import create_engine
from urllib import parse
import datetime, time
from apscheduler.schedulers.blocking import BlockingScheduler
from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log

#...................................电池包电芯安全诊断函数......................................................................................................................
def diag_cal():
    global SNnums, df_bms_ram

    start=time.time()
    now_time=datetime.datetime.now()
    start_time=now_time-datetime.timedelta(seconds=310)
    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
    db='safety_platform'
    user='qx_read'
    password='Qx@123456'

    #读取故障结果库中当前故障......................................................
    param='start_time,end_time,product_id,code,level,info,advice'
    tablename='all_fault_info_copy'
    mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
    cursor = mysql.cursor()
    sql =  "select %s from %s where 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(','))
    

    db_res_engine = create_engine(
        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
            user, parse.quote_plus(password), host, port, db
        ))

    mylog=log.Mylog('log_diag.txt','error')
    mylog.logcfg()

    for sn in SNnums:
        try:
            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' in sn) 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']

            #读取结果数据库数据........................................................................................................................................................
            db='qx_cas'
            mode=1
            tablename1='cellstateestimation_soh'
            tablename2='cellstateestimation_uniform_socvoltdiff'
            # tablename3='cellstateestimation_soc'
            DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
            with DBRead as DBRead:
                df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename=tablename1, sn=sn, timename='time_sp', st=start_time, sp=end_time)
                df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellmin_num,cellmax_num', tablename=tablename2, sn=sn, timename='time', st=start_time, sp=end_time)
                # df_soc=DBRead.getdata('time','sn','packsoc', tablename=tablename3, sn=sn)

            #电池诊断................................................................................................................................................................
            if not df_bms.empty:
                df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
                df_diag_ram_sn.reset_index(inplace=True,drop=True)
                df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
                df_bms_ram_sn.reset_index(inplace=True,drop=True)
                
                df_bms=df_bms.dropna(axis=0,subset=['总电流[A]','SOH[%]','SOC[%]','总电压[V]']) #去除有空值的行
                df_bms.reset_index(inplace=True,drop=True)     #重置索引

                batquality=CBMSBatDiag.BatDiag(sn,celltype,df_bms,df_diag_ram_sn,df_bms_ram_sn,df_soh,df_uniform)
                df_diag_res, df_bms_res=batquality.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)

                #历史故障筛选并更改数据库故障结束时间.........................................................
                if not df_diag_res.empty:
                    df_diag_new = pd.concat([df_diag_res,df_diag_ram_sn,df_diag_ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
                    df_diag_new.reset_index(inplace=True,drop=True)  #重置索引
                    df_diag_end=pd.concat([df_diag_res,df_diag_new,df_diag_new]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
                    df_diag_end=df_diag_end[df_diag_end['end_time'] != '0000-00-00 00:00:00']
                    df_diag_end.reset_index(inplace=True,drop=True)  #重置索引

                    if not df_diag_end.empty:   #变为历史故障更改数据库
                        for j in range(len(df_diag_end)):
                            cursor.execute('''
                                        update all_fault_info_copy set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and end_time='0000-00-00 00:00:00' and code='{}'
                                        '''.format(datetime.datetime.now(), df_diag_end.loc[j,'end_time'], 1 ,sn, df_diag_end.loc[j,'code']))
                            mysql.commit()

                    #新增故障筛选并存入数据库.....................................................................
                    if not df_diag_new.empty:  #新增写入数据库
                        df_diag_new.to_sql("all_fault_info_copy",con=db_res_engine, if_exists="append",index=False)

            end=time.time()
            print(end-start)  
            
        except Exception as e:
            print(repr(e))
            mylog.logopt(e)

    cursor.close()
    mysql.close()

#...............................................主函数起定时作用.......................................................................................................................
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
    
    mylog=log.Mylog('log_diag.txt','error')
    mylog.logcfg()

    #参数初始化
    df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])

    diag_cal()
    #定时任务.......................................................................................................................................................................
    scheduler = BlockingScheduler()
    scheduler.add_job(diag_cal, 'interval', seconds=300)

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