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

import com.google.gson.Gson;
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.HttpUtil;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * job alarm by feishu
 *
 * @author supeng
 */
@Component
public class FeishuJobAlarm implements JobAlarm {
    private static Logger logger = LoggerFactory.getLogger(FeishuJobAlarm.class);

    private static final String FEISHU_BOT_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/5091de05-970c-463a-a3cf-2e02e857d969";
    private static final String MESSAGE_TEMPLATE = "personal:{0}\n title:{1}\n group:{2}\n id:{3}\n jobDesc:{4}\n message:{5}";

    /**
     * fail alarm
     *
     * @param jobLog
     */
    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;

        // send monitor feishu
        if (info != null) {

            // alarmContent
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("Alarm Job LogId=").append(jobLog.getId()).append("\n");
            if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
                stringBuffer.append("TriggerMsg=").append(jobLog.getTriggerMsg()).append("\n");
            }
            if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
                stringBuffer.append("HandleCode=").append(jobLog.getHandleMsg()).append("\n");
            }

            // email info
            XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
            String personal = I18nUtil.getString("admin_name_full");
            String title = I18nUtil.getString("jobconf_monitor");
            String message = MessageFormat.format(MESSAGE_TEMPLATE,
                    personal,
                    title,
                    group != null ? group.getTitle() : "null",
                    info.getId(),
                    info.getJobDesc(),
                    stringBuffer.toString());

            try {
                Gson gson = new Gson();
                Map<String, String> body = new HashMap<>();
                body.put("msg_type", "text");
                Map<String, String> content = new HashMap<>();
                content.put("text", message);
                body.put("content", gson.toJson(content));
                String result = HttpUtil.postJson(FEISHU_BOT_URL, gson.toJson(body));
                logger.info("feishu alarm result = {}", result);
            } catch (Exception e) {
                logger.error("feishu alarm error", e);
                alarmResult = false;
            }
        }

        return alarmResult;
    }
}
