package com.microservices.mon.k8s.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.html.EscapeUtil;
import com.microservices.common.httpClient.constant.GitLinkConstants;
import com.microservices.common.httpClient.domain.GitLinkRequestUrl;
import com.microservices.common.httpClient.service.HttpAPIService;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.common.redis.service.RedisService;
import com.microservices.mon.k8s.domain.K8SEvent;
import com.microservices.system.api.RemoteGatewayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author otto
 */
@Component
public class SyncK8SEventJob {
    private static final Logger log = LoggerFactory.getLogger(SyncK8SEventJob.class);
    @Autowired
    private RemoteGatewayService remoteGatewayService;

    @Value("${elasticsearch.k8sEventIndex}")
    public String esK8sEventIndex;
    @Value("${k8sAlarm.k8sAlarmPath}")
    private String k8sAlarmPath;
    @Autowired
    private GitLinkRequestHelper gitLinkRequestHelper;

    /**
     * 每隔10秒钟从ES读取最近20秒的K8S事件，对没有发送过通知的事件补充站内信发送
     */
    @Scheduled(fixedDelay = 10, timeUnit = TimeUnit.SECONDS)
    public void sendK8SEventJob() {
        sendK8SEvent();
    }

    // 发送K8S事件
    private void sendK8SEvent() {
        JSONObject waringUserIdsRes = gitLinkRequestHelper.doGet(MonGitLinkRequestUrl.GET_WARNING_USER_IDS());
        if (waringUserIdsRes == null || waringUserIdsRes.getInteger("status") != 0 || waringUserIdsRes.getJSONArray("data") == null || waringUserIdsRes.getJSONArray("data").isEmpty()) {
            log.error("获取告警通知的用户id失败，失败信息为：{}", waringUserIdsRes);
            return;
        }
        JSONArray receiversJsonArr = waringUserIdsRes.getJSONArray("data");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < receiversJsonArr.size(); i++) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(receiversJsonArr.getString(i));
        }

        JSONObject alarmEventListQueryBody = ESQueryUtils.buildAlarmEventListQueryBody();
        JSONObject esQueryRes = remoteGatewayService.executeElasticsearchQuery(esK8sEventIndex, alarmEventListQueryBody);
        List<K8SEvent> k8SEventList = K8SEvent.toK8SEventList(esQueryRes);
        if (!k8SEventList.isEmpty()) {
            log.info("ES query result:{}", esQueryRes);
        }

        for (K8SEvent k8SEvent : k8SEventList) {
            JSONObject gnsVo = new JSONObject();
            gnsVo.put("sender", "1");
            gnsVo.put("receivers", sb.toString());
            String message = "";
            if (StringUtils.isNotEmpty(k8SEvent.getMessage())) {
                message = k8SEvent.getMessage();
                if (StringUtils.length(message) > 300) {
                    message = StringUtils.substring(message, 0, 300) + "......";
                }
                message = ",详细信息为：" + message;
            }
            gnsVo.put("content", String.format("系统检测到异常事件，请及时处理：发生对象为<b>%s</b>，异常原因为<b>%s</b>%s",
                    k8SEvent.getObject(), k8SEvent.getReason(), message));
            gnsVo.put("type", 1);
            gnsVo.put("notification_url", EscapeUtil.removeExtraSlashOfUrl(gitLinkRequestHelper.gitLinkUrl + "/" + k8sAlarmPath));

            try {
                JSONObject result = remoteGatewayService.sendNotification(gnsVo);
                log.info("result:{}", result);
            } catch (Exception e) {
                log.error("给用户发送告警失败，发送内容：{}，异常信息：{}", gnsVo, e.getMessage());
            }
            JSONObject updateEsBody = new JSONObject();
            updateEsBody.put("script", "ctx._source.sendNotification = true");
            JSONObject updateK8SEventResult = remoteGatewayService.executeElasticsearchUpdate(esK8sEventIndex, k8SEvent.getDocId(), updateEsBody);
            log.info("updateK8SEventResult:{}", updateK8SEventResult);
        }
    }
}
