package com.docus.server.common;

import com.alibaba.fastjson.JSONObject;
import com.docus.server.api.scheduling.management.SchVirtualLogApi;
import com.docus.server.common.utils.SystemInfoUtils;
import com.docus.server.dto.scheduling.management.schvirtuallog.AddSchVirtualLogDTO;
import com.xxl.job.core.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@Slf4j
public class SchVirtualLogTask {

    @Resource
    private SchVirtualLogApi schVirtualLogApi;

    //定时任务
    // 5 * * * * ? 在每分钟的5秒执行
    @Scheduled(cron = "${docus.vm-task-cron}")
    public void runTask() {
        try {
            log.info("收集虚拟机信息定时任务： 开始执行");

            JSONObject info = SystemInfoUtils.getInfo();

            AddSchVirtualLogDTO addSchVirtualLogDTO = new AddSchVirtualLogDTO();
            addSchVirtualLogDTO.setCpuUtilization((String) ((JSONObject) info.get("cpuInfo")).get("cSys"));
            addSchVirtualLogDTO.setMemoryTotal((String) ((JSONObject) info.get("memInfo")).get("total"));
            addSchVirtualLogDTO.setMemoryAllowance((String) ((JSONObject) info.get("memInfo")).get("free"));
            addSchVirtualLogDTO.setUplinkRate((String) ((JSONObject) info.get("networkInfo")).get("txPercent"));
            addSchVirtualLogDTO.setDescendingRate((String) ((JSONObject) info.get("networkInfo")).get("rxPercent"));
            addSchVirtualLogDTO.setIp(IpUtil.getIp());
            addSchVirtualLogDTO.setClientTime(new Date());
            addSchVirtualLogDTO.setDiskJson(info.get("sysFileInfo").toString());
            schVirtualLogApi.add(addSchVirtualLogDTO);
            System.out.println(info);

            log.info("收集虚拟机信息定时任务： 执行完毕");
        } catch (Exception e) {
            log.error("收集虚拟机信息定时任务执行出错", e);
        }

    }


}

