package com.lemon.utils;


import com.alibaba.fastjson.JSONObject;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.Job;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.BasicResponseHandler;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-11-14 13:54
 **/
public class Robot {

    /**
     * 根据Jenkins构建状态，发送企业微信推送消息
     *
     * @return
     * @throws Exception
     */
    public static String sendRobotMessage() throws Exception {
        // Jenkins的url， http://192.168.92.13:8080/job/Lemon/lastBuild/buildNumber
        URI uri = new URI("http://192.168.92.13:8080");
        //Jenkins请求的账号和密码
        JenkinsHttpClient client = new JenkinsHttpClient(uri, "admin", "782fc581e22146388643bb2a252dcd85");
        //Jenkins的服务
        JenkinsServer jenkinsServer = new JenkinsServer(client);
        // 获取所有job
        Map<String, Job> jobs = jenkinsServer.getJobs();
        System.out.println("获取所有jobs：" + jobs);
        // 获取最后一次构建结果，结果为BuiledResult枚举类型
        Integer LastBuild = (jenkinsServer.getJob("Lemon").getLastBuild()).getNumber();
        System.out.println("最后一次构建次数为：" + LastBuild);
        // 构建状态 成功SUCCESS 失败FAILURE
        String BuildStatus = String.valueOf(jenkinsServer.getJob("Lemon").getLastBuild().details().getResult());
        System.out.println("最后一次构建状态为：" + BuildStatus);
        // 获取最后一次构建的Allure报告
        String LastBuildAllureUrl = String.format("http://192.168.92.13:8080/job/Lemon/%d/allure/", LastBuild);
        System.out.println(LastBuildAllureUrl);

        // 通过最后一次的状态做判断
        if (BuildStatus == "FAILURE" ||BuildStatus ==  "UNSTABLE") {
            // 将失败的结果推送到企微群聊
            String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fc6f4a8e-b208-47ab-9ceb-e9c7e47564c7";
            JSONObject object = new JSONObject();
            JSONObject markdown = new JSONObject();
            String content = String.format("【Lemon自动化测试项目】运行有失败的用例，<font color=\"warning\">第 %d 次构建失败</font>，请相关同事注意。\n" +
                    " >项目名称:<font color=\\\"comment\\\">Lemon自动化测试</font>\n" +
                    " >所属模块:<font color=\\\"comment\\\">RAYS支付</font>\n" +
                    " >报告结果:<font color=\\\"comment\\\"> [报告结果](%s) </font>", LastBuild, LastBuildAllureUrl);
            markdown.put("content", content);
            object.put("msgtype", "markdown");
            object.put("markdown", markdown);
            String body = WechatWebHook(url, object.toJSONString());
            return body;
        } else {
            System.out.println("构建正确，无需告警");
        }
        return BuildStatus;
    }

    /**
     * 获取Jenkins最后一次构建的状态和次数
     *
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    public String getLastBuildInfo() throws IOException, URISyntaxException {
        // Jenkins的url
        URI uri = new URI("http://192.168.92.13:8080");
        //Jenkins请求的账号和密码
        JenkinsHttpClient client = new JenkinsHttpClient(uri, "admin", "782fc581e22146388643bb2a252dcd85");
        //Jenkins的服务
        JenkinsServer jenkinsServer = new JenkinsServer(client);
        // 获取所有job
        Map<String, Job> jobs = jenkinsServer.getJobs();
        // 脚本触发Jenkins构建
        // jenkinsServer.getJob("Lemon").build();
        // 获取最后一次构建次数
        Integer LastBuild = (jenkinsServer.getJob("Lemon").getLastBuild()).getNumber();
        System.out.println("最后一次构建次数为：" + LastBuild);
        // 最后一次构建状态,结果，结果为BuiledResult枚举类型
        String BuildStatus = String.valueOf(jenkinsServer.getJob("Lemon").getLastBuild().details().getResult());
        System.out.println("最后一次构建状态为：" + BuildStatus);
        // 获取最后一次构建的Allure报告
        String LastBuildAllureUrl = String.format("http://192.168.92.13:8080/job/Lemon/%d/allure/", LastBuild);
        System.out.println("最后一次的Allure报告" + LastBuildAllureUrl);
        return LastBuildAllureUrl;
//        // 获取最后一次构建的结果
//        String LastBuildStatus = String.format("http://192.168.92.13:8080/job/Lemon/%d/api/xml", LastBuild);
//        System.out.println(LastBuildStatus);
//        // 获取Jenkins控制台输出
//        String LastBuildConsole = String.format("http://192.168.92.13:8080/job/Lemon/%d/console", LastBuild);
//        System.out.println(LastBuildConsole);
    }

    /**
     * 使用企业微信群聊机器人
     *
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String WechatWebHook(String url, String json) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(json, "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getAllHeaders();
        String body = EntityUtils.toString(entity);
        return body;
    }


    public static String httpClientGet(String url, String jsonData) {
        String result = "";
        //创建post方式请求对象
        HttpGet httpGet = new HttpGet(url);
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            BasicResponseHandler handler = new BasicResponseHandler();
            //设置请求格式
            StringEntity entity = new StringEntity(jsonData, "utf-8"); //解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            //执行POST请求
            result = httpClient.execute(httpGet, handler);
            return result;
        } catch (Exception e) {

        } finally {
            //释放连接
            try {
                httpClient.close();
            } catch (Exception e) {
            }
        }
        return result;
    }


    public static void main(String[] args) throws Exception {
        sendRobotMessage();
    }

}
