package com.ebo.module.task;

import com.ebo.module.utils.GetAccessToken;
import com.ebo.module.utils.SendMessageEmail;
import com.google.gson.Gson;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class CpuMonitorHandler extends IJobHandler {
    @Autowired
    private SendMessageEmail sendMessageEmail;
    private final static String apiUrl = "http://localhost:8659/monitor/server/cpu";

    @XxlJob("cpuMonitorJob")
    @Override
    public void execute() throws Exception {
        log.info("Cpu Monitor Job Start");
        String accessToken = GetAccessToken.getAccessToken();
        if (accessToken == null) {
            log.error("获取令牌失败");
            return;
        }

        URIBuilder uriBuilder = new URIBuilder(apiUrl);
        uriBuilder.addParameter("access_token", accessToken);
        String urlWithParams = uriBuilder.build().toString();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(urlWithParams);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);

                Map<String, Object> responseresult = new Gson().fromJson(result, Map.class);
                Map<String, Object> data = (Map<String, Object>) responseresult.get("data");

                double free = Double.parseDouble(data.get("free").toString());
                double threshold = 80; // 设置阈值

                if ((100-free) > threshold) {
                    sendMessageEmail.sendAlert("Cpu内存占用过高警告", "目前内存占用为: " + (100-free) + "%");
                } else {
                    log.info("Cpu内存占用正常: " + (100-free) + "%");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        log.info("Cpu Monitor Job End");
    }

}