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
import math

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from urllib import parse
import pymysql

class BMSReportError:
    def __init__(self):
        pass
    def main(sn,bms_info,df_Diag_Ram_in,FactoryType,errorcode_map):
        newCode_total=[]
        if len(df_Diag_Ram_in):
            df_Diag_Ram_in['code']=df_Diag_Ram_in['code'].apply(str)
            df_Diag_Ram_BMS=df_Diag_Ram_in[df_Diag_Ram_in['code'].str.contains('B')].copy()
            df_Diag_Ram_Cloud=df_Diag_Ram_in[df_Diag_Ram_in['code'].str.contains('C')].copy()
        else:
            df_Diag_Ram_BMS=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
            df_Diag_Ram_Cloud=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
        if len(bms_info):
            df_bms=bms_info[['时间戳','故障等级','故障代码']]
            newCode=[]
            for i in range (0,len(df_bms)):
                #拆解故障码，PK专用
                if FactoryType ==1:
                    code=df_bms.loc[i,'故障代码']
                    newCode=[]
                    if not pd.isnull(code):
                        if code>2:
                            num=math.log(code)/math.log(2)
                            power=int(num)
                            nCode=int(math.pow(2,power))
                            newCode.append(nCode)
                            code=code-nCode
                            while(code>0):
                                num=float(math.log(code)/math.log(2))
                                power=int(num)
                                nCode=int(math.pow(2,power))
                                newCode.append(nCode)
                                code=code-nCode
                        elif code>0:
                            newCode.append(code)
                        else:
                            newCode=[]
                    else:
                        newCode=[]
                else:
                    newCode=df_bms.loc[i,'故障代码']
                    if not pd.isnull(newCode) and newCode!=0:
                        newCode=[newCode]
                    else:
                        newCode=[]                        
                        
            # 数据库配置

                if  len(newCode):
                    for j in range(0,len(newCode)):
                        # host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
                        # port=3306
                        # database='algo_dict'
                        # user='qx_algo_readonly'
                        # password='qx@123456'

                        # db_engine = create_engine("mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(user, password, host, port, database))
                        # DbSession = sessionmaker(bind=db_engine)

                        # errorcode_map = pd.read_sql("select * from faultcode_map", db_engine)
                        # if 'K50' in sn:
                        #     FactoryType=1
                        # elif 'MGMCL' in sn or 'UD' in sn:
                        #     FactoryType=2
                        # else:
                        #     FactoryType=3
                        
                             
                        code = newCode[j] # 终端故障码
                        platform_code = errorcode_map[(errorcode_map['protocol']==FactoryType)&(errorcode_map['end_errorcode']==str(code))]['platform_errorcode']                   

                        # db_engine.dispose()
                        if len(platform_code) == 0:
                            pass
                        else:                       
                            newCode_total.append(platform_code.values[0])
                            newCode[j]=platform_code.values[0]
                            if not platform_code.values[0] in df_Diag_Ram_BMS['code'].values.tolist():
                                df_Diag_Ram_BMS.loc[len(df_Diag_Ram_BMS)]=[df_bms.loc[i,'时间戳'],'0000-00-00 00:00:00',sn,platform_code.values[0],df_bms.loc[i,'故障等级'],'','']
                            else:
                                pass
        if len(df_Diag_Ram_BMS):
            df_Diag_Ram_BMS=df_Diag_Ram_BMS.reset_index(drop=True)
            for k in range(0,len(df_Diag_Ram_BMS)):
                newCode_total=list(set(newCode_total))
                if not df_Diag_Ram_BMS.loc[k,'code'] in newCode_total:
                    end_time=datetime.datetime.now()
                    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
                    df_Diag_Ram_BMS.loc[k,'end_time']=end_time
                else:
                    pass
        df_Diag_Ram=df_Diag_Ram_BMS.append(df_Diag_Ram_Cloud)
        df_Diag_Ram=df_Diag_Ram.reset_index(drop=True)
        return df_Diag_Ram
