# -*- encoding=utf8 -*-

import os
import time
import json
import pymysql
import logging
import requests
from decimal import *
from flask_sqlalchemy import SQLAlchemy
from flask import request,Flask,jsonify




"""
#配置输出日志格式
LOG_FORMAT = '%(asctime)s %(filename)s[line:%(lineno)d] %(name)s %(levelname)s %(pathname)s  %(message)s'

#配置输出时间格式
DATE_FORMAT = '%Y-%m-%d %H-%M-%S %a'

logging.basicConfig(level = logging.INFO,
                    format = LOG_FORMAT,
                    datefmt = DATE_FORMAT,
                    filename = r"../logs/balance_run.log")
"""


app = Flask(__name__)


class Config(object):
    #sqlalchemy的配置参数
    
    DIALECT = 'mysql'
    DRIVER='pymysql'
    USERNAME = 'root'
    PASSWORD = 'nibuzhidaowozhidao'
    HOST = '127.0.0.1'
    PORT = 9001
    DATABASE = 'monitoring'
    
    #SQLALCHEMY_DATABASE_URI =  "mysql+ pymysql://root:nibuzhidaowozhidao@120.78.198.155:9001/monitoring?charset=utf8" 
    SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)


    #设置sqlalchemy自动跟踪数据库
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    
    
app.config.from_object(Config)
db = SQLAlchemy(app) 
#print(db)

#创建数据库模型类
class Monitor(db.Model):   
    __tablename__ = 'balance_monitoring'
    id  = db.Column(db.Integer,primary_key=True,autoincrement=True)
    msg  = db.Column(db.String(512))
    group_name  = db.Column(db.String(128))
    status  = db.Column(db.Integer)
    timestamp  = db.Column(db.BigInteger)

    
@app.route('/balance/monitoring/chanel', methods=['GET'])
def chanelBalanceMonitoring():
    #print(11)
    monitor_list = Monitor.query.filter_by(status = 1).all()
    
    result = []
    if(len(monitor_list) > 0):
        for i in range(len(monitor_list)):
            monitor = monitor_list[i]
            result.append([monitor.msg,monitor.group_name])
            monitor.status = 2
            db.session.add(monitor)
            db.session.commit()

    
    #print(result)
    return jsonify(result)
 
@app.route('/monitor/balance',methods=['POST']) 
def monitorBalance():
    param = request.json
    
    phone = param['phone']
    balance = round(param['balance'],2)
    fail_count = len(param['failList'])
    #print(phone)
    #print(balance)
    #print(fail_count)
    

    
    timestamp = time.time()
    str_time = time.strftime('%H:%M',time.localtime(timestamp))
    #str_time_int = int(str(time.strftime('%H:%M:%S',time.localtime(timestamp))).split(':')[-1])
    str_time_int = int(str(str_time).split(':')[-1])
    msg = ""
    if balance > 0:
        msg = str_time + ': {} 余额为 {}，请及时处理'.format(phone,balance)
    else :
        if(fail_count >= 7 ):
            msg = str_time + ': {} 余额为 {}，失败次数为 {}，请及时处理'.format(phone,balance,fail_count)
    
    
    #cursor = mon_conn.cursor()
    if len(msg) > 0 :
        monitor = Monitor(msg = msg, group_name = "补单余额监控群", status = 1, timestamp = timestamp)
        db.session.add(monitor)
        db.session.commit()


    return 'SUCCESS'    



if __name__ == '__main__':
   
    app.config['JSON_AS_ASCII'] = False
    #app.config['JSONIFY_MIMETYPE'] ="application/json;charset=utf-8"
      
    app.run(host="0.0.0.0", port=9888,debug=True)

