# -*- encoding=utf8 -*-

import time
import json
import pymysql
import requests
import pandas as pd
from DBUtils.PooledDB import PooledDB


URL = 'http://47.95.217.180:9999/monitoring/xiaomi'

#创建数据库连接池
def createPool(db_config):
   spool = PooledDB(pymysql, 5, **db_config) 
   return spool


def saveData():
  timestamp = time.time()
  str_time = time.strftime('%H:%M',time.localtime(timestamp))
  str_time_int = int(str(str_time).split(':')[-1])
  print(str(str_time).split(':')[-1])
  ins_sql = """ INSERT  INTO balance_monitoring VALUES(0,%s,%s,1,%s)  """
  
  res = requests.get(url = URL)
  #print(response.status_code)
  #print(response.text)
  data_json = json.loads(res.text)
  df = pd.DataFrame(list(data_json))
  df.columns = ['used_time']
  df['used_time'] = df['used_time'].str.replace(r'\n','').astype(float)
  #print(df)  
  
  total_count = len(df)
  count_1 = len(df[df['used_time'] <= 0.1])
  count_2 = len(df[(df['used_time'] > 0.1) & (df['used_time'] <= 0.2)]) 
  count_3 = len(df[(df['used_time'] > 0.2) & (df['used_time'] <= 0.3)]) 
  count_4 = len(df[(df['used_time'] > 0.3) & (df['used_time'] <= 0.4)]) 
  count_5 = len(df[(df['used_time'] > 0.4) & (df['used_time'] <= 0.5)]) 
  count_6 = len(df[(df['used_time'] > 0.5) & (df['used_time'] <= 1)]) 
  count_7 = len(df[df['used_time'] > 1]) 
  #print(total_count)
  #print(count_1)
  count_list = []
  for i in range(7):
      temp_count =locals()["count_{}".format(i+1)]
      
      #print(temp_count)
      temp_percent = "%.2f%%"%(temp_count/total_count * 100)
      #print(temp_percent)
      count_list.append([temp_count,temp_percent])
   
  msg = '''小米下单时间统计:\n 0-0.1秒 订单数量为：{},百分比为：{};\n 0.1-0.2秒 订单数量为：{}, 百分比为：{};\n 0.2-0.3秒 
           订单数量为：{} ,百分比为：{} ;\n 0.3-0.4秒 订单数量为：{},百分比为：{};\n 0.4-0.5秒订 单数量为：{},百分比为：{};\n
           0.5-1秒 订单数量为：{},百分比为：{};\n 1秒以上 订单数量为：{},百分比为：{}。'''.format(count_list[0][0],
                count_list[0][1],count_list[1][0],count_list[1][1],count_list[2][0],count_list[2][1],count_list[3][0],count_list[3][1],
                count_list[4][0],count_list[4][1],count_list[5][0],count_list[5][1],count_list[6][0],count_list[6][1])
  
  #print(msg)      
  cursor = conn.cursor()
  try:
      #print(3333)
      cursor = conn.cursor()        
      cursor.execute(ins_sql, (msg,'小米下单时间监控群',int(timestamp)))

  except:
     conn.rollback()
     print('数据回滚')

  cursor.close()
  conn.close()
if __name__ == '__main__':
  #监控消息数据库连接信息
  db_config = {
          'host' : '127.0.0.1',
          'port' : 9001,
          'user' : 'root',
          'password' : 'nibuzhidaowozhidao',
          'db' : 'monitoring',
          'charset' : 'utf8',
          'autocommit' : 1
  }

  conn =  createPool(db_config).connection()
  saveData()

