# coding: utf-8
from base_framework.public_tools.selenium_api import SeleniumWebUI
import time


class JenkinsAPI(SeleniumWebUI):
    def __init__(self):
        SeleniumWebUI.__init__(self)
        self.project_info = {}

    def jenkins_login(self, u_name=None, u_pwd=None):
        """ 登陆jenkins """
        if not u_name:
            u_name = "admin"
            u_pwd = "admin"
        login_url = "http://39.170.26.156:8256/jenkins/login?from=%2Fjenkins%2F"
        self.web_open_url(url=login_url)
        self.web_send_keys(locator="//*[@id=\"j_username\"]", text=u_name)
        self.web_send_keys(locator="//*[@name=\"j_password\"]", text=u_pwd)
        self.web_click_element(locator="//*[@name=\"Submit\"]")
        time.sleep(1)  # 切换到构建墙
        self.web_click_element(locator="//*[text()='1-用户产品组']")
        time.sleep(1)  # 显示用例数量
        self.web_click_element(locator="//*[@title=\"Configure Build Monitor Settings\"]")
        time.sleep(1)
        self.web_click_checkbox(locator="//*[@id=\"settings-show-test-result\"]")
        self.web_click_checkbox(locator="//button[text()=\"Done\"]")

    def jenkins_find_all_case_number(self):
        """ 从构建墙上读取用例数量 """
        elements = self.web_find_elements(locator="//li[@ng-repeat=\"project in jobs track by project.hashCode\"]")
        for element in elements:
            item = element.text.split('\n')
            case_number = item[1].split('/')
            self.project_info[item[0]] = case_number[1]

    def jenkins_edit_project_config(self, **kwargs):
        """ 编辑工程配置信息 """
        for jp in self.project_info:
            case_number = int(self.project_info[jp])
            if jp == "TO-IT":
                jp = "TO-IT-TEST"
            elif jp == "TO-SMOKING":
                jp = "TO-SMOKING_NEW"
            project_url = "http://10.250.200.1:8080/jenkins/view/1-%E7%94%A8%E6%88%B7%E4%BA%A7%E5%93%81%E7%BB%84/" \
                          "job/{}/configure".format(jp)
            if "SMOKING" in jp or "-ST" in jp:
                threshold = 99.999999  # 冒烟和ST用例需全部构建成功
            else:
                threshold = round((1-5.5/case_number)*100, 4)  # 阈值
            self.web_open_url(url=project_url)  # 进入设置页面
            self.web_send_keys(locator="//input[@name=\"_.unstableThreshold\"]", text=str(threshold))
            self.web_click_checkbox(locator="//button[text()=\"保存\"]")
            print("{}设置阈值{}完毕....".format(jp, threshold))
            time.sleep(1)


if __name__ == '__main__':
    ja = JenkinsAPI()
    ja.jenkins_login()
    time.sleep(3)
    ja.jenkins_find_all_case_number()
    ja.jenkins_edit_project_config()
    time.sleep(3)
    ja.web_close_browser()



