# encoding: utf-8
# @Time    : 2021/12/20 18:14
# @Author  : yk
# @Site    :
# @File    : jira_message_by_ding.py

from jira import JIRA
import json
import requests
import datetime
import urllib.parse


class JiraObj:
    def __init__(self, user, pwd, jira_addr):
        if not hasattr(JiraObj, 'jira'):
            JiraObj.jira_obj(user, pwd, jira_addr)

    @staticmethod
    def jira_obj(user, pwd, jira_addr):
        JiraObj.jira = JIRA(auth=(user, pwd), options={'server': jira_addr})

    @staticmethod
    def search_by_jql(jql, fields=None):
        return JiraObj.jira.search_issues(jql, fields=fields, maxResults=-1, json_result='true')



def get_delay_sub_task_creator(jira_obj, now_date):
    name_list="chengpu,fengtian,dengzhenbo,guosongchao,handongtang,huanghaifeng,lidaijun,wanglushun,wangyujie02,yangwenlei01,yangwenlei01,zhanghaodong,zhengxin01,zhuzipeng"
    # name_list="zhanghaodong"
    jql = 'issuetype = 缺陷  and createdDate  < \'{} 18:00\' AND status not in (QA测试,SIM验证,Done,关闭,待测试) and assignee in ({})'.format(
        now_date,name_list)
    fields = 'assignee'
    print(jql)
    issue_list = jira_obj.search_by_jql(jql, fields).get('issues')
    print(issue_list)
    if issue_list:
        return list(map(lambda x: x.get('fields').get('assignee').get('name'), issue_list))
    else:
        return None
def send_message_by_feishu(name, message):
        data={"list":[name]}
        a=requests.post(url="http://sqe.qc.huohua.cn:8082/feishu/getUserIds",data=data)
        print(a.text)
        open_id=a.text.split("open_id")[1].split('"')[2].split("\\")[0]

        data={
        "app_id": "cli_a2d926427f39900d",
        "app_secret": "CvETCGh3rHu6CtcnxzaWK7rMnVgcSLED"
    }
        a=requests.post(url="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",json=data)

        tenant_access_token=eval(a.text)["tenant_access_token"]
        data ={"msg_type": "text","content": { "text": "{}".format(message) }, "open_ids": [open_id]}

        header={"Authorization":"Bearer {}".format(tenant_access_token),"Content-Type":"application/json; charset=utf-8"}

        a=requests.post(url="https://open.feishu.cn/open-apis/message/v4/batch_send/", json=data,headers=header)

        print(a.text)
if __name__ == '__main__':

    now_date = datetime.datetime.now().strftime('%Y-%m-%d')

    jira_obj = JiraObj('yaokun', 'Cyjayk1314', 'https://jira.bg.huohua.cn')
    creator = get_delay_sub_task_creator(jira_obj, now_date)

    if creator:
        creator=list(set(creator))
        message="你还有未解决的bug，请及时解决，若已解决请及时更新jira状态"
        for i in creator:
            jql = 'issuetype = 缺陷  and createdDate  < \'{} 18:00\' AND status not in (QA测试,SIM验证,Done,关闭,待测试) and assignee in ({})'.format(
                now_date, i)
            print(jql)
            i=i+"@sparkedu.com"

            a=jira_obj.search_by_jql(jql, "assignee").get('issues')
            for j in a:
                print(j["key"])
                send_message_by_feishu(i,"你有未修复的bug请及时修复https://jira.bg.huohua.cn/browse/{}".format(j["key"]))
    # send_message_by_feishu("yaokun@sparkedu.com","https://jira.bg.huohua.cn/browse/HHC-50790")
#     data={"list":["yaokun@sparkedu.com"]}
#     a=requests.post(url="http://sqe.qc.huohua.cn:8082/feishu/getUserIds",data=data)
#
#     print(a.text.split("open_id")[1].split('"')[2].split("\\")[0])
#     open_id="ou_95feb664191332a7916bb3b0d886f553"
#     print(a.text)
#     data={
#     "app_id": "cli_a2d926427f39900d",
#     "app_secret": "CvETCGh3rHu6CtcnxzaWK7rMnVgcSLED"
# }
#     a=requests.post(url="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",json=data)
#     print(a.text)
#
#     data ={"msg_type": "text","content": { "text": "https://jira.bg.huohua.cn/browse/HHC-50790" }, "open_ids": [open_id]}
#
#     header={"Authorization":"Bearer t-719d260f474e6a1a6b4a5d990a6bccec6fc3b17f","Content-Type":"application/json; charset=utf-8"}
#     print(data)
#     a = requests.post(url="https://open.feishu.cn/open-apis/message/v4/batch_send/", json=data,headers=header)
#     print(a.text)