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 MemoryMonitorHandler extends IJobHandler {
    @Autowired
    private SendMessageEmail sendMessageEmail;

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

        String apiUrl = "http://localhost:8659/monitor/server/mem";

        // 构建带有查询参数的 URL
        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 usage = Double.parseDouble(data.get("usage").toString());
                double threshold = 80.0; // 设置阈值

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

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

}