package config

import (
	"cicv-data-closedloop/common/util"
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

var resourceLogger *logrus.Logger

// 保存资源占用情况
func SendResourceUsage() {
	initLog(LogDir, ResourceLogPrefix)
	for {
		time.Sleep(time.Duration(10) * time.Second)
		top10Cpu, top10Mem := util.GetTop10CpuAndMem()
		top10CpuJson, _ := json.MarshalIndent(top10Cpu, "", "    ")
		top10MemJson, _ := json.MarshalIndent(top10Mem, "", "    ")

		requestMap := map[string]string{
			"totalCpuUsage":    util.ToString(util.GetCpuPercent()),
			"totalMemoryUsage": util.ToString(util.GetMemoryPercent()),
			"top10Process":     string(top10CpuJson),
			"top10Cpu":         string(top10CpuJson),
			"top10Mem":         string(top10MemJson),
			"deviceNumber":     LocalConfig.EquipmentNo,
			"socIp":            LocalConfig.Node.Ip,
		}
		resourceLogger.Infof("监控信息为:%v", util.MapToReadableJsonString(requestMap))
		//responseString, err := util.HttpPostJsonWithHeaders(
		//	CloudConfig.Monitor.Url,
		//	map[string]string{"Authorization": "U9yKpD6kZZDDe4LFKK6myAxBUT1XRrDM"},
		//	requestMap,
		//)
		//if err != nil {
		//	c_log.GlobalLogger.Errorf("发送数据监控信息报错%v,响应信息为:%v", err, responseString)
		//}
		//c_log.GlobalLogger.Infof("发送数据监控信息成功,响应信息为:%v", responseString)
	}
}

// 初始化日志配置
func initLog(logDir string, prefix string) {
	time.Sleep(time.Duration(1) * time.Second)
	// 创建、追加、读写,777,所有权限
	logPath := logDir + prefix + "-" + time.Now().Format("2006-01-02-15-04-05") + ".log"
	err := util.CreateParentDir(logPath)
	if err != nil {
		os.Exit(-1)
	}
	f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
	if err != nil {
		os.Exit(-1)
	}
	resourceLogger = logrus.New()
	resourceLogger.SetOutput(f)
	resourceLogger.SetReportCaller(true) // 开启行号显示
	resourceLogger.SetFormatter(&logrus.JSONFormatter{
		CallerPrettyfier: func(frame *runtime.Frame) (string, string) {
			fileName := filepath.Base(frame.File)
			return "", fmt.Sprintf("%s:%d", fileName, frame.Line)
		},
	})
	resourceLogger.Info("初始化resourceLogger - 成功")

}