package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class FeiShuTextJobAlarm implements JobAlarm {

    private static Logger logger = LoggerFactory.getLogger(FeiShuTextJobAlarm.class);
    private static final String FEISHU_WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/6eb334d1-ec36-46a2-a276-b9b5edb49071";


    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;


        XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(info.getJobGroup());
        String title = I18nUtil.getString("jobconf_monitor");

        StringBuilder textBuilder = new StringBuilder();
        textBuilder.append(title).append("\n");
        textBuilder.append("任务组: ").append(group != null ? group.getTitle() : "null").append("\n");
        textBuilder.append("任务ID: ").append(info.getId()).append("\n");
        textBuilder.append("任务描述: ").append(info.getJobDesc()).append("\n");
        textBuilder.append("告警详情:\n");
        textBuilder.append("  LogId: ").append(jobLog.getId()).append("\n");

        if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
            textBuilder.append("  TriggerMsg:\n").append(jobLog.getTriggerMsg()).append("\n");
        }
        if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
            textBuilder.append("  HandleMsg:\n").append(jobLog.getHandleMsg()).append("\n");
        }

        String text = textBuilder.toString();


        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msg_type", "text");
        Map<String, String> content = new HashMap<>();
        content.put("text", text);
        requestBody.put("content", content);

        try {
            RestTemplate restTemplate = new RestTemplate();


            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");


            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);


            ResponseEntity<String> response = restTemplate.exchange(
                    FEISHU_WEBHOOK_URL,
                    HttpMethod.POST,
                    entity,
                    String.class
            );


            if (response.getStatusCode().is2xxSuccessful()) {
                logger.info("Feishu alarm sent successfully. Response: {}", response.getBody());
            } else {
                logger.error("Feishu alarm failed. Status code: {}, Response: {}", response.getStatusCodeValue(), response.getBody());
                alarmResult = false;
            }

        } catch (Exception e) {
            logger.error(">>>>>>>>>>> xxl-job, job fail alarm feishu send error, JobLogId:{}", jobLog.getId(), e);
            alarmResult = false;
        }

        return alarmResult;
    }

}
