#!/usr/bin/env python
#coding=utf-8
#阿里云余额告警接口
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkbssopenapi.request.v20171214.QueryAccountBalanceRequest import QueryAccountBalanceRequest
from aliyunsdkbssopenapi.request.v20171214.QueryAccountTransactionsRequest import QueryAccountTransactionsRequest
import locale
import time,datetime
import os,requests,hashlib
import warnings
import json
import numpy as np

#别名 = AcsClient('<access_key_id>','<access_key_secret>','cn-hangzhou')
maxbon = AcsClient('<access_key_id>','<access_key_secret>','cn-hangzhou')

#获取前n天的日期列表
def get_nday_list(n):
    import datetime
    before_n_days = []
    for i in range(1, n + 1)[::-1]:
        before_n_days.append(str(datetime.date.today() - datetime.timedelta(days=i)))
    return before_n_days

#获取账户余额
def get_response(account,min_quota):
    request = QueryAccountBalanceRequest()
    request.set_accept_format('json')
    response = account.do_action_with_exception(request)
#print(response)
        AvailableAmount = response.split('"')[5]
        locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
    int_AvailableAmount = int(locale.atof(AvailableAmount))
        if int_AvailableAmount < int(min_quota):
                return int_AvailableAmount
        else:
                return 0

#获取指定日期内流水
def get_Transactions(account,start_date,end_date,PageSize):
    request = QueryAccountTransactionsRequest()
    request.set_accept_format('json')
    request.set_PageSize(PageSize)
    request.set_CreateTimeStart(start_date+"T00:00:00Z")
    request.set_CreateTimeEnd(end_date+"T00:00:00Z")
    response = account.do_action_with_exception(request)
    json_response = json.loads(response)
    lenth = len(json_response["Data"]["AccountTransactionsList"]["AccountTransactionsList"])
#    print(start_date,end_date)
#    print lenth
    #求和
    Amounts = []
    for i in range(lenth):
        Amounts.append(json_response["Data"]["AccountTransactionsList"]["AccountTransactionsList"][i]["Amount"])
    sum_Transactions=sum([float(each_e) for each_e in Amounts])
    return sum_Transactions

#前n-1日平均流水查询
def get_nday_Transactions(account,nday,PageSize=300):
    global Transactions_list
    dates = get_nday_list(nday)
    Transactions_array = []
    i = 0;x = i + 1
    while x < len(dates):
        Transactions_array.append(round(get_Transactions(account,dates[i],dates[x],PageSize),2))
#        time.sleep(10)
        i += 1;x = i + 1
    if len(dates) > 2:
        Transactions_list = Transactions_array
        Transactions_array.remove(max(Transactions_array)) #去掉一个最大值
    mean = round(np.mean(np.array(Transactions_array,np.float)),2) #求平均值
    return dates,mean,Transactions_list

#参数1:阿里云账户
#参数2:前面定义的别名
#参数3:余额告警最小阈值
def check_status(ali_id,account,min_quota):
        status = get_response(account,min_quota)
        message = '【告警】阿里云帐户余额低于'+str(min_quota)+',请及时充值,帐户:'+ali_id+',当前余额:'+str(status)+'元,https://account.aliyun.com/login/login.htm'
        if status != 0:
        print ali_id,status
        print message

#流水查询
#参数1:阿里云账户
#参数2:前面定义的别名
#参数3:N天内的平均流水
def check_Transactions(ali_id,account,nday):
    a = get_nday_Transactions(account,nday)
    b = get_nday_Transactions(account,2)[1]
    c = int(((b - a[1])/a[1])*100)
    message = str(a[2])+'\r\n【流水异常】账户:'+ali_id+',前5日平均流水:'+str(a[1])+',昨日流水:'+str(b)+',增长率:'+str(c)+'%'
    if c > 50:
        print(message)
    else:
        print('OK')
        print(message)

#余额查询
check_status('maxbon',maxbon,5000)

#流水查询
check_Transactions('maxbon',maxbon,6)