# -*- coding: UTF-8 -*-

from dsite import settings
import utils
from utils import const

import hashlib
import base64
import hmac
import json
import requests
from django.utils.timezone import now


def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()

    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')

    return sign


def request(content, msg_type=const.LARK_WEBHOOK_MSG_TYPE_TEXT):
    """content: {'text': 'xxxxx}"""
    timestamp = utils.timestamp_of(now())
    data = {
        "timestamp": timestamp,
        "sign": gen_sign(timestamp, settings.LARK_WEBHOOK_SECRET),
        "msg_type": msg_type,
        "content": content,
    }
    resp = requests.post(settings.LARK_WEBHOOK_URL, data=json.dumps(data))
    if resp.status_code == 200 and resp.json().get('StatusCode') == 0:
        return True
    return False
