#coding=utf-8
import os
import datetime
import pandas as pd
from LIB.BACKEND import DBManager, Log
from LIB.MIDDLE import SignalMonitor
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import time, datetime
import traceback

from urllib import parse

dbManager = DBManager.DBManager()
if __name__ == "__main__":
    # 读取sn列表
    df_sn = pd.read_csv('sn_list.csv')
    df_sn = df_sn.reset_index(drop=True)
    df_sn['StartTime'] = pd.to_datetime(df_sn['StartTime'])
    df_sn['EndTime'] = pd.to_datetime(df_sn['EndTime'])
    df_sn['ExitTime'] = pd.to_datetime(df_sn['ExitTime'])
    signalMonitor = SignalMonitor.SignalMonitor()
    
    cal_period = 24    # 计算间隔，单位h
    for i in range(0, len(df_sn['sn'])):    # 遍历SN号
        sn = [df_sn.loc[i,'sn']]
        if not (sn[0][0:2] == 'PK' or sn[0][0:2] == 'MG' or sn[0][0:2] == 'UD'):
            continue
        st = df_sn.loc[i, 'StartTime']
        if df_sn.loc[i, 'Service'] == 0:
            if pd.isnull(df_sn.loc[i, 'EndTime']) and pd.isnull(df_sn.loc[i, 'ExitTime']):
                continue
            elif pd.isnull(df_sn.loc[i, 'ExitTime']):
                et = df_sn.loc[i, 'EndTime']
            else:
                et = df_sn.loc[i, 'ExitTime']
        elif pd.isnull(df_sn.loc[i, 'EndTime']):
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
            et = pd.to_datetime(otherStyleTime)
        else:
            et = df_sn.loc[i, 'EndTime']
        df_last_state = pd.DataFrame(
            columns=['sn', 'current', 'Timestamp', 'PackState', 'LineState'])    # 每日最后BMS数据
        df_last_state_gps = pd.DataFrame(
            columns=['sn', 'Timestamp', 'PackState', 'LineState', 'latitude', 'longitude'])    # 每日最后GPS数据
        df_res = pd.DataFrame(columns=[
                                'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime'])    # 初始化BMS信号统计数据
        df_res_gps = pd.DataFrame(columns=[
                                    'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime', 'latitude', 'longitude'])    # 初始化GPS信号统计数据
        while st < et:

            df_res, df_state, df_last_state = signalMonitor.get_bms_offline_stat(
                sn, st, et, df_res, df_last_state, cal_period)    # 计算每日BMS信号统计数据
            df_res_gps, df_last_state_gps = signalMonitor.get_gps_offline_stat(
                sn, st, et, df_state, df_res_gps, df_last_state_gps, cal_period)    # 计算每日GPS信号统计数据
            # 数据入库
            st = st + datetime.timedelta(hours=cal_period)
        SignalMonitor._file_write(r'D:\result_04.xls', df_res)    # BMS信号统计数据入库
        SignalMonitor._file_write(r'D:\result_05.xls', df_res_gps)    # GPS信号统计数据入库

        SignalMonitor._file_write(r'D:\result_06.xls', df_last_state)
        SignalMonitor._file_write(r'D:\result_07.xls', df_last_state_gps)

    # 数据入库
