package handler

import (
	"cicv-data-closedloop/common/config/c_db"
	"cicv-data-closedloop/common/config/c_log"
	commonEntity "cicv-data-closedloop/common/entity"
	"cicv-data-closedloop/common/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type DeviceMonitor struct {
	Id               int       `db:"id" json:"id"`                               // 自增id
	TotalCpuUsage    string    `db:"total_cpu_usage" json:"totalCpuUsage"`       // cpu总占用
	TotalMemoryUsage string    `db:"total_memory_usage" json:"totalMemoryUsage"` // 内存总占用
	Top10Process     string    `db:"top10_process" json:"top10Process"`          // cpu占用前十的进程信息
	Top10Cpu         string    `db:"top10_cpu" json:"top10Cpu"`                  // cpu占用前十的进程信息
	Top10Mem         string    `db:"top10_mem" json:"top10Mem"`                  // 内存占用前十的进程信息
	DeviceNumber     string    `db:"device_number" json:"deviceNumber"`          // 设备编号
	SocIp            string    `db:"soc_ip" json:"socIp"`                        // 芯片IP
	ReportTime       time.Time `db:"report_time" json:"reportTime"`              // 数据上报时间
}

// 保存实车上传的监控信息
func SaveDeviceMonitor(c *gin.Context) {
	param := new(DeviceMonitor)
	// 映射到结构体
	if err := c.ShouldBindJSON(&param); err != nil {
		c_log.GlobalLogger.Error("项目启动接收请求参数报错:", err)
		c.JSON(http.StatusBadRequest, commonEntity.Response{
			Code: 500,
			Msg:  "请求体解析失败。",
		})
		return
	}
	// 插入到数据库
	sqlTemplate, _ := util.ReadFile(c_db.SqlFilesMap["insert_device_monitor.sql"])
	if err := c_db.DoTx(sqlTemplate, []any{
		param.TotalCpuUsage,
		param.TotalMemoryUsage,
		param.Top10Process,
		param.Top10Cpu,
		param.Top10Mem,
		param.DeviceNumber,
		param.SocIp,
		time.Now(),
	}); err != nil {
		c_log.GlobalLogger.Error("插入数据报错:", err)
		c.JSON(http.StatusBadRequest, commonEntity.Response{
			Code: 500,
			Msg:  "插入数据报错。",
		})
		return
	}
	c.JSON(http.StatusOK, commonEntity.Response{
		Code: 200,
		Msg:  "插入数据成功。",
	})
}