package com.jay.monitor.data.server.report.alert.notify;

import com.jay.monitor.data.server.componts.OOSInvoke;
import com.jay.monitor.data.server.costs.MdConstants;
import com.jay.monitor.data.server.enums.AlertMsgEnums;
import com.jay.monitor.data.server.models.config.AlertConfigModel;
import com.jay.monitor.data.server.models.request.dingding.MdModel;
import com.jay.monitor.data.server.store.ConfigStoreManager;
import com.jay.monitor.data.server.utils.DingDingUtils;
import com.jay.monitor.data.server.utils.MarkDownUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @Module TODO
 * @Description TODO
 * @Author liukaixiong
 * @Date 2020/12/16 13:18
 */
@Component
public class DingDingReportAlertMsgProcess implements AlertReportMsg {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ConfigStoreManager configStoreManager;

    @Autowired(required = false)
    private OOSInvoke oosInvoke;

    @Override
    public AlertMsgEnums alertType() {
        return AlertMsgEnums.DingDing;
    }

    @Override
    public boolean send(String date, String msg) {

        AlertConfigModel alertConfigModel = configStoreManager.getAlertConfigModel(AlertMsgEnums.DingDing);
        String dingDingUrl = alertConfigModel.getUrl();

        String consoleUrl = configStoreManager.getConsoleUrl();

        String filename = System.currentTimeMillis() + ".jpg";
        InputStream inputStream = MarkDownUtils.mdToImage(msg);
        // local
        // FileUtil.writeFromStream(inputStream, "C:\\Users\\Administrator\\Desktop\\md1.jpg");

        // 得到图片的url
        String url = oosInvoke.uploadFile(filename, inputStream);

        StringBuilder mdText = new StringBuilder();
        mdText.append("## 每日报表:" + date);
        mdText.append(MdConstants.newLine);
        mdText.append(">  ![screenshot](" + url + ")");
        mdText.append(MdConstants.newLine);
        mdText.append("> [点击查看](" + consoleUrl + ")");
        mdText.append(MdConstants.newLine);
        mdText.append("------ ");
        mdText.append(MdConstants.newLine);

        MdModel model = DingDingUtils.builderMdModel("监控告警每日提醒:" + date, mdText.toString(), false, null);

        boolean send = DingDingUtils.send(dingDingUrl, model);
        if (send) {
            logger.info("钉钉消息发送成功");
        } else {
            logger.warn("钉钉消息发送失败!!");
        }
        return send;
    }

}
