import numpy as np
import pandas as pd
import datetime,time
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from urllib import parse
import pymysql

def low_soc_alarm_sta(df_sns, db_qxcas_engine, conn, db_sp_engine):
    
    cursor = conn.cursor()

    sql = "select sn, DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') as time, level from lowsoc_info where add_time >DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 00:00:00')"+ \
        " and  add_time <DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 23:59:59')"           
    df_lowsocalarm_lastday = pd.read_sql(sql, db_qxcas_engine)
    sn_lowsoc = df_lowsocalarm_lastday['sn'].tolist()

    sql = "select sn, DATE_FORMAT(add_time, '%Y-%m-%d %H:%i:%s') as time, level, last_time from offline_info where add_time >= DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 00:00:00')"+ \
        " and add_time <= DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 23:59:59')"           
    df_offlinealarm_lastday = pd.read_sql(sql, db_qxcas_engine)
    sn_offline = df_offlinealarm_lastday['sn'].tolist()

    sql = "select * from all_fault_info where end_time='{}' and code='{}'".format('0000-00-00 00:00:00', 'C307')
    df_all_alarm_info = pd.read_sql(sql, db_sp_engine)
    sn_allalarm = df_all_alarm_info['product_id'].tolist()

    # 遍历昨日报警和报警列表，如果 1：sn存在于昨日报警，但不存在与报警allinfo里，则添加一条新的报警记录到allinfo里；
    #                           2：如果sn存在于allinfo但不存在于昨日报警，也不存在于昨日离线，则记录故障为结束；
    #                           3： 如果sn在两个表中都存在，但级别不同，则更新级别（离线暂rr时不考虑级别）。
    sn_new = list(set(sn_lowsoc)-set(sn_allalarm))
    sn_close = list(set(sn_allalarm)-set(sn_lowsoc)-set(sn_offline))
    # sn_cross = list(set(sn_lowsoc) & set(sn_allalarm))
    # 新增
    df_new = pd.DataFrame(columns=['add_time', 'product_id', 'start_time', 'end_time', 'code', 'level', 'info'])
    now = datetime.datetime.now()
    for sn in sn_new:
        df = df_lowsocalarm_lastday[df_lowsocalarm_lastday['sn']==sn]
        factory = df_sns[df_sns['sn']==sn]['factory'].values[0]
        df_new = df_new.append({'add_time':now, 'product_id':sn, 'factory':factory, 'start_time':df['time'].values[0], 'end_time':'0000-00-00 00:00:00', 'info':"低电量报警", 'code':'C307', 'level':3}, ignore_index=True)
    if not df_new.empty:
        df_new.to_sql('all_fault_info', db_sp_engine, if_exists='append', index=False)

    # 修改
    now = datetime.datetime.now()
    for sn in sn_close:
        df = df_lowsocalarm_lastday[df_lowsocalarm_lastday['sn']==sn]
        df1 = df_all_alarm_info[df_all_alarm_info['product_id']==sn]
        sql = ''' update all_fault_info set update_time='{}', end_time='{}' where product_id = '{}' and start_time = '{}' and code = {}'''.format \
                    (now, datetime.datetime.strftime(now,"%Y-%m-%d %H:%M:%S"), sn, pd.to_datetime(df1['start_time'].values[0]), df1['code'].values[0])
        cursor.execute(sql)
        conn.commit()