"""
@autor:Yue
@date::10:13
@file:dingdingtalk.py
@project:autoInterface

"""
from urllib3 import encode_multipart_formdata
import dingtalkchatbot.chatbot as cb
import requests ,os,sys
aa=os.path.abspath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(aa)))
from requests_toolbelt import MultipartEncoder
class dingRobot():

    def __init__(self,resportfile=None):
        self.url="https://oapi.dingtalk.com/robot/send?access_token=fefce0782f64a04c81deceaf2ac42ee8cedd488f57ee069dff41a084658aac18"
        self.urlfile = "https://oapi.dingtalk.com/media/upload?access_token=fefce0782f64a04c81deceaf2ac42ee8cedd488f57ee069dff41a084658aac18&type=file"
        self.path = resportfile

    ###发送附件，不过需要管理员的身份
    def uploadfile(self):
        filename,filepath=self.path.split(os.sep)[-1],os.sep.join(self.path.split(os.sep)[:-1])
        #print(filename,filepath)
        data={"media":(filename,open(self.path,"rb"))}
        m=MultipartEncoder(data)
        headers={}
        headers['Content-Type'] = m.content_type
        #print(m,headers,headers)
        
        t=requests.post(self.urlfile, headers=headers,data=m)
        print("上传文件到钉钉群的响应信息：",t.text)

    ##发送text类型消息
    def sendMes(self,path,mes=None,newfile=None,type=None):
        ##带有link类型的消息

        if 'MainStream' in type:
            t = '主流程'
        elif 'MoreOrder' in type:
            t = '多订单'
        elif 'hetong' in type:
            t = '合同'
        else:
            t = '其他'

        if newfile:
            url='http://192.168.4.96:8002/{0}/'.format(path)+newfile

        if mes:
            data={"msgtype":"link","link":{"messageUrl": "{0}".format(url),"title":"测试报告","text":"{0}".format(url,mes)}}
        ##带有text类型的消息
        else:
            #data={"msgtype": "text", "text": {"content": "测试报告链接地址[{0}]：{1}".format(type,url)},"at":[],'isAtAll':True}

            data={"msgtype":"link","link":{"messageUrl": "{0}".format(url),"title":"测试报告结果[{0}]".format(t),"text":"{0}[:错误数:{1}]".format(type.split("_")[-2],type.split("_")[-1])}}

        header={"Content-Type":"application/json"}
        #print(data)
        t=requests.post(self.url,json=data,headers=header)
        print("上传message到钉钉群的响应信息：",t.text)


if __name__ == '__main__':
    newfile=sys.argv[1]
    ##表示测试报告类型
    type=sys.argv[2]

    if 'MainStream' in type:
        path='MainStream'
    elif 'MoreOrder' in type:
        path='MoreOrder'
    elif 'hetong' in type:
        path='hetong'
    else:
        path='report'
    #resportfile="/Users/dm/Desktop/python_script/autoInterface/static/reports/测试/ces.html"
    t=dingRobot()
    t.sendMes(path=path,newfile=newfile,type=type)
    #t.uploadfile()
