import base64
import hashlib
import hmac
import json
import time
import urllib.parse

import requests


def dingding_alert1(phone:list,msg):
    dingding_webhook="https://oapi.dingtalk.com/robot/send?access_token=9c78c711f14ba3345d6dc492dc5ca8118c421516d611b5de46854fb8e158565f"
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC09f744f81b55c8a18f0d77a3ab60bf4e1ec3f16b85f025e6a4f75ddff00a8fd4'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    dingding_url = dingding_webhook + '&timestamp=' + timestamp + "&sign=" + sign
    if phone:
        header = {
            "Content-Type": "application/json"
        }
        data = {
            "at": {
                "atMobiles": phone,
            },
            "text": {
                "content": msg
            },
            "msgtype": "text"
        }
    else:
        header = {
            "Content-Type": "application/json"
        }
        data = {
            "at": {
                "isAtAll": True
            },
            "text": {
                "content": msg
            },
            "msgtype": "text"
        }


    res = requests.post(url=dingding_url, data=json.dumps(data), headers=header)


def dingding_alert11(phone:list,msg):
    dingding_webhook="https://oapi.dingtalk.com/robot/send?access_token=c3be52d9ae7307dd7ceb0b677f569c47de2ff81b20fe30c328c75fbd9ab81383"
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC14f583c6f735044be3f9f6fdc53edb7cf0b7d56d9b63c4b78bcafa9880814f9e'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    dingding_url = dingding_webhook + '&timestamp=' + timestamp + "&sign=" + sign
    if phone:
        header = {
            "Content-Type": "application/json"
        }
        data = {
            "at": {
                "atMobiles": phone,
            },
            "text": {
                "content": msg
            },
            "msgtype": "text"
        }
    else:
        header = {
            "Content-Type": "application/json"
        }
        data = {
            "at": {
                "isAtAll": True
            },
            "text": {
                "content": msg
            },
            "msgtype": "text"
        }

    res = requests.post(url=dingding_url, data=json.dumps(data), headers=header)