package com.jiayue.ssi.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.entity.SysAlarm;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.entity.server.Jvm;
import com.jiayue.ssi.service.SysAlarmService;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;

/**
* 检测内存告警
*
* @author xsl
* @since 2023/04/06
*/
@Service
@EnableScheduling
@Slf4j
public class AutoScanMemory {
    @Autowired
    SysPolicyService sysPolicyService;
    @Autowired
    SysAlarmService sysAlarmService;

    /**
     * 每30分钟执行一次扫描
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void scanMemory() throws Exception{
        SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
        try {
            int memoryWarn = sysPolicy.getMemoryWarn();
            Jvm jvm = new Jvm();
            jvm.setTotal(Runtime.getRuntime().totalMemory());
            jvm.setMax(Runtime.getRuntime().maxMemory());
            jvm.setFree(Runtime.getRuntime().freeMemory());
            if ((100 - jvm.getUsage()) < memoryWarn) {
                SysAlarm sysAlarm = new SysAlarm();
                sysAlarm.setAlarmContent("当前JVM使用率:" + jvm.getUsage() + "%,低于阈值" + memoryWarn + "%");
                sysAlarm.setReadSign("0");
                // 低于策略设定值则告警
                sysAlarmService.save(sysAlarm);
            }
        }
        catch (Exception e){
            log.error("检测内存阈值出错",e);
        }
        try {
            // 检测日志存储低于阈值告警
            File file = new File(FileUtil.getLogsPath());
            // 最低阈值数值
            double percentValue = Double.parseDouble(sysPolicy.getLogSpaceWarn().toString()) / (double) 100;
            double lowValue = (file.getTotalSpace() / 1024 / 1024 / 1024) * percentValue;
            // 可用剩余空间
            double ableSpaceValue = Double.parseDouble((file.getUsableSpace() / 1024 / 1024 / 1024) + "");
            if (ableSpaceValue < lowValue) {
                SysAlarm sysAlarm = new SysAlarm();
                sysAlarm.setAlarmContent("当前剩余空间:" + ableSpaceValue + "G,低于阈值" + sysPolicy.getLogSpaceWarn() + "%");
                sysAlarm.setReadSign("0");
                // 低于策略设定值则告警
                sysAlarmService.save(sysAlarm);
            }
        }
        catch (Exception e){
            log.error("检测日志空间阈值出错",e);
        }
    }
}
