import time
import requests
import json
import socket

from src.framework.common import file_abspath


hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)

file_path = file_abspath() + "report\\output\\widgets\\suites.json"


def alert():
    with open(file_path) as f:
        file_context = json.loads(f.read())
        result = file_context['items'][0]['statistic']
    # 获取当前日期
    tile = time.strftime("%Y-%m-%d %H:%M:%S")
    url = "https://oapi.dingtalk.com/robot/send"
    querystring = {"access_token": "8f7f39c8872c67f25ddadcfd95f86a69593a1e060cf69dc92b5981827d401383"}  # 钉钉机器人url里面的token值
    data = {

        "msgtype": "markdown",  # 发送类型：text/markdown
        "markdown": {
            "title": "uitest报告",    # 需要和机器人设置的关键字相对于 否则不会推送到消息
    "text": "### 代码质量检测报告 \n\n **项目名称：**UI自动化 \n\n **项目地址：**[点击跳转详情](http://{}:63342/index.html) \n\n **检测分支：** master \n\n **bug数量：**{} \n\n **相关人员：**@测试 \n\n **播报时间:** {}".format(ip, result, tile),
    "at": {
        "atMobiles": [
            ""  # 如果需要@某人，这里写他的手机号　　这块暂时没有触发 还在研究
        ],
        "isAtAll": 0  # 如果需要@所有人，这些写1
    }
    }

    }

    json_str = json.dumps(data)     # 需要将类型转换为json类型

    headers = {
        'content-type': "application/json"
    }
    if result['skipped'] + result['passed'] != result['total']:
        response = requests.request("POST", url, data=json_str, headers=headers, params=querystring)

        print(response)
        print(response.text)


if __name__ == '__main__':
    alert()

"https://oapi.dingtalk.com/robot/send?access_token=8f7f39c8872c67f25ddadcfd95f86a69593a1e060cf69dc92b5981827d401383"

