package com.iformall.schedule;

import com.iformall.domain.po.SysMonitor;
import com.iformall.enums.EnumSysMonitorStatus;
import com.iformall.mapper.*;
import com.iformall.service.MailService;
import com.iformall.utils.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SysMonitorSchedule {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private String fmMonitorEmails;

    @Autowired
    private boolean isFmMonitor;

    @Autowired
    private MailService mailService;

    @Autowired
    private SysMonitorMapper sysMonitorMapper;

    @Scheduled(cron = "0 */5 * * * *?") // 每隔5分钟检查一下各个网址
    public void checkUrls() {
        if(isFmMonitor) {
            SysMonitor q = new SysMonitor();
            q.setEnable(EnumSysMonitorStatus.ENABLE.getCode());
            List<SysMonitor> sysMonitors = sysMonitorMapper.findList(q);

            for (SysMonitor sysMonitor : sysMonitors) {
                checkSysMonitor(sysMonitor);
            }
        }
    }

    private void checkSysMonitor(SysMonitor sysMonitor) {
        boolean isNormal = true;
        for(int i=0;i<3;i++) {
            try {
                String result = HttpUtil.doGet(sysMonitor.getUrl());
                if (StringUtils.isBlank(result)) {
                    isNormal = false;
                } else {
                    if (result.length() < 60) {
                        logger.info(result);
                    } else {
                        logger.info(result.substring(0, 50));
                    }
                }
            } catch (RuntimeException e) {
                logger.error(e.getMessage());
                isNormal = false;
            }
            if(isNormal) {
                break;
            }
        }

        if(!isNormal) {
            String[] receivers = fmMonitorEmails.split(",");

            String content = sysMonitor.getErrMsg();
            content = content.replace("{name}", sysMonitor.getName());
            content = content.replace("{url}", sysMonitor.getUrl());

            //发送邮件
            logger.error(sysMonitor.getName() + "访问异常");
            mailService.sendSimpleMail(receivers, sysMonitor.getName() + "访问异常", content);
        }
    }


}