package com.skr.mdm.api.index.controller;

import com.skr.mdm.bean.vo.index.SysStatusInfoVO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ServerSystemUtil;
import com.sun.management.OperatingSystemMXBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @author nfq
 * @date 2023-03-13 11:05
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "系统监控")
public class SystemMonitorController {

    @Value("${mdm.system.dir}")
    private String diskPath;

    private static final OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    @GetMapping("monitor")
    @ApiOperation(value = "系统监控", response = SysStatusInfoVO.class)
    @PreAuthorize("hasAnyAuthority('sys:index')")
    public ResponseResult systemMonitor() throws Exception {
        // 获取cpu使用率
        String sysCpuUsed = new DecimalFormat("0.00%").format(osmxb.getSystemCpuLoad());
        // 获取内存使用率
        Double mem;
        long totalVirtualMemory = osmxb.getTotalPhysicalMemorySize();
        if (ServerSystemUtil.osName().contains("win")) {
            long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
            BigDecimal divide = new BigDecimal(freePhysicalMemorySize).divide(new BigDecimal(totalVirtualMemory), 2, RoundingMode.HALF_UP);
            mem = 1 - divide.doubleValue();
        } else {
            long memUsed = ServerSystemUtil.getMemUsed();
            memUsed = memUsed * 1024;
            mem = Double.parseDouble(String.valueOf(memUsed)) / Double.parseDouble(String.valueOf(totalVirtualMemory));
        }
        String sysMemoryUsed = new DecimalFormat("0.00%").format(mem);
        SysStatusInfoVO sysStatusInfoVO = ServerSystemUtil.diskInfo(diskPath);
        sysStatusInfoVO.setCpuUsageRate(sysCpuUsed);
        sysStatusInfoVO.setMemUsageRate(sysMemoryUsed);
        return ResponseResult.success(sysStatusInfoVO);
    }

}
