package com.priusis;

import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.oshi.OshiUtil;
import com.priusis.vo.MqttRpcDataMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;
import oshi.hardware.NetworkIF;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Map;

@Slf4j
@EnableScheduling
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class})
public class ApqInfoApplication {

    @Autowired
    private RestTemplate restTemplate;

    private int runningIndex = 0;

    public static void main(String[] args) {
        SpringApplication.run(ApqInfoApplication.class, args);
    }

    // 30秒一次上报
    @Scheduled(fixedDelay = 30000L)
    protected void controlProgramTask() {
        log.info("设备实时数据采集上报=================");
        runningIndex++;
        boolean isNoneEven = runningIndex % 2 == 0;

        // 获取采集配置，数据上报频率 params == data
        ResponseEntity<MqttRpcDataMessage> forEntity = null;
        try {
            forEntity = restTemplate.getForEntity("http://localhost:8765/rpc_cmd/info", MqttRpcDataMessage.class);
        } catch (Exception e) {
            log.error("采集数据异常", e);
        }

        if (null != forEntity) {
            MqttRpcDataMessage body = forEntity.getBody();
            String params = body.getParams();

            if (StrUtil.isNotBlank(params)) {
                String operatingSystem = "operatingSystem";
                String mac = "mac";
                String baseboard = "baseboard";
                String ip = "ip";
                String cpuModel = "cpuModel";
                String cpuTemp = "cpuTemp";
                String memoryCap = "memoryCap";
                String diskModel = "diskModel";
                String diskCap = "diskCap";

                try {
                    Map<String, Integer> mapParams = JSONUtil.toBean(params, Map.class);
                    // 上报PC实时信息
                    InetAddress inetAddress = InetAddress.getLocalHost();
                    NetworkIF networkIF = new NetworkIF();
                    networkIF.setNetworkInterface(NetworkInterface.getByInetAddress(inetAddress));
                    Map<String, Object> data = MapUtil.<String, Object>builder()
                            .put(isNeedCollection(isNoneEven, operatingSystem, mapParams), operatingSystem, OshiUtil.getOs().toString())
                            .put(isNeedCollection(isNoneEven, mac, mapParams), mac, networkIF.getMacaddr())

                            .put(isNeedCollection(isNoneEven, baseboard, mapParams), baseboard, OshiUtil.getSystem().getBaseboard().getManufacturer() + " " + OshiUtil.getSystem().getBaseboard().getVersion())
                            .put(isNeedCollection(isNoneEven, ip, mapParams), ip, inetAddress.getHostAddress())
                            .put(isNeedCollection(isNoneEven, cpuModel, mapParams), cpuModel, OshiUtil.getCpuInfo(0).getCpuModel())
                            .put(isNeedCollection(isNoneEven, cpuTemp, mapParams), cpuTemp, OshiUtil.getSensors().getCpuTemperature())
                            .put(isNeedCollection(isNoneEven, memoryCap, mapParams), memoryCap, DataSizeUtil.format(OshiUtil.getMemory().getTotal()))
                            .put(isNeedCollection(isNoneEven, diskModel, mapParams), diskModel, OshiUtil.getHardware().getDiskStores()[0].getModel())
                            .put(isNeedCollection(isNoneEven, diskCap, mapParams), diskCap, DataSizeUtil.format(OshiUtil.getHardware().getDiskStores()[0].getSize()))
                            .build();
                    Map mapR = restTemplate.postForObject("http://localhost:8765/uplink/oc-client", data, Map.class);
                    log.info("采集数据，上报属性: mapData:{}, ret:{}", data, mapR);
                } catch (Exception e) {
                    log.error("采集数据异常", e);
                }
            } else {
                log.info("未获取到采集配置，数据上报频率");
            }
        } else {
            log.info("未获取到采集配置，数据上报频率");
        }
    }

    private boolean isNeedCollection(boolean isNoneEven, String key, Map<String, Integer> mapParams) {
        return mapParams.containsKey(key) && (!isNoneEven || mapParams.get(key) != 30);
    }
}
