from tools import *
import jenkins, requests, re, os
import pandas as pd

base_url = "http://jenkins.quantgroups.cn"
# java_url="/TKE/job/tke-java/"
jk = jenkins.Jenkins(base_url, username="qiuyue.gui", password="1234567890Yue@")
header = {"Host": "jenkins.quantgroups.cn"}


def buildJob(project, branch, env,urltype ,jobname="java",prefix_job='ACK'):
    '''
    :param project:
    :param branch:
    :param env:
    :param jobname: 只支持tke的构建
    :return:
    '''
    jobname=jobname.upper()
    jobs = jk.get_all_jobs()
    #print("jobs:",jobs)
    jobnames = []
    joburls = []
    projects_branch = get_project_branch(project,urltype)
    #projects_branch={"kdsp":["master11"]}
    temp_branchs=projects_branch.get(project)
    if branch not in temp_branchs:
        raise  Exception("branch({0})项目不存在，确定一下".format(branch), temp_branchs)

    jobname = prefix_job+'-' + jobname if prefix_job not in jobname else jobname
    for kv in jobs:
        jobnames.append(kv.get('name'))
        joburls.append(kv.get('url'))
    #jobs_name_url = dict(zip(jobnames, joburls))
    if jobname not in jobnames:
        print("jobname({0})错误，需要在其中一个:{1}".format(jobname, ','.join(jobnames)))
        return 0
    # jk.get_build_info()
    # jk.build_job(jobname,branch,env)
    #job_config = jk.get_job_config(jobname)
    params = {"GIT_REPO": project, "DEPLOY": 'true', 'NAMESPACE': env, "BRANCH_NAME": branch}
    # branchs_url=requests.get("")
    t = jk.build_job(jobname, params)
    print("project({0}-{1}-{2}) build succ".format(project, branch, env), t)

def get_project_branch(project,urltype):
    """
    :param project:
    :return: 根据project获取分支信息
    """
    try:
        temp_branchs=[]
        num=1
        if urltype=='tjzm':
            git_url=tjzm_git_url
            #project_url =tjzm_git_url+'/api/v4/projects?search='+project
        else:
            git_url=lkb_git_url
        project_url =git_url+'/api/v4/projects?search='+project
        temp=requests.get(project_url,headers=git_headers)
        print(temp.text)
        project_name=jsonpath.jsonpath(temp.json(),'$[*].name')
        project_id=jsonpath.jsonpath(temp.json(),'$[*].id')
        project_info=dict(zip(project_name,project_id))
        for i in range(10):
            #brand_url=git_url+"/api/v4/projects/{project_id}/repository/branches?per_page=100".format(project_id=project_info.get(project))
            brand_url=git_url+"/api/v4/projects/{project_id}/repository/branches?per_page=100&page={num}".format(project_id=project_info.get(project),num=i)
            temp=requests.get(brand_url,headers=git_headers)
            #print(temp.json())
            brands_name=jsonpath.jsonpath(temp.json(),'$[*].name')
            if brands_name:
                temp_branchs+=brands_name
            else:
                break
        project_brands={project:temp_branchs}
        return project_brands
    except:
        print("project[{}]不存在".format(project))
        traceback.print_exc(3)


def main(project,type="",prefix_job='ACK'):
    #="nearline-recommend-parent"
    project_branch={
        "kdsp":{
            "branch":"feature-mix-test-yxm-202207201023",
            "env":'yxm',
            "jobname":"java"},

        "nearline-recommend-parent":{
            "branch":"master",
            "env":'bd',
            "jobname":"java"
        },
        "online-recommend":{
            "branch":"event_htk_20220714",
            "env":'bd',
            "jobname":"java"
        },
        "lxq-ui":{
            "branch":"master",
            "env":'yxm',
            "jobname":"ui"
        },
        "new-op-optimized-ui":{
        "branch":"feat/memberDayS3",
        "env":'yxm',
        "jobname":"ui"
    },
        "op-api":{
            "branch":"feat/no-captcha",
            "env":'yxm',
            "jobname":"node"
        },
        "xjfq-ui":{
            "branch":"feature/max",
            "env":'toc',
            "jobname":"ui",
            "urltype":"tjzm"
        },
        "xyqb":{
            "branch":"feature-maxmember2",
            "env":'toc',
            "jobname":"java",
            "urltype":"tjzm"
        }
    }
    urltype=project_branch.get(project).get('urltype')
    branch=project_branch.get(project).get('branch')
    env=project_branch.get(project).get('env')
    jobname=project_branch.get(project).get('jobname')
    if not (branch and env and jobname):
        raise Exception('项目错误，无法构建')
    buildJob(project, branch, env,urltype=urltype, jobname=jobname,prefix_job=prefix_job)


if __name__ == '__main__':
    project="kdsp"
    main(project)
