package subscribes

import (
	"encoding/json"
	"gadmin/config"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"github.com/nats-io/nats.go"
	"github.com/sirupsen/logrus"
	"time"
)

// AdminLog 后台日志订阅
var AdminLog = new(sAdminLog)

type sAdminLog struct{}

func (s *sAdminLog) Handle(m *nats.Msg) (err error) {
	var data model.AdminLog
	if err = json.Unmarshal(m.Data, &data); err != nil {
		return err
	}

	if data.GetData == "" {
		data.GetData = "{}"
	}
	if data.PostData == "" {
		data.PostData = "{}"
	}
	if data.HeaderData == "" {
		data.HeaderData = "{}"
	}
	if data.Data == "" {
		data.Data = "{}"
	}

	//// 压缩节省存储空间
	//d, err := compress.MarshalJsonAndGzip(data.Data)
	//if err != nil {
	//	return err
	//}
	//data.Data = base64.StdEncoding.EncodeToString(d)

	data.CreatedAt = time.Now()
	if err = query.Use(config.DB).AdminLog.Create(&data); err != nil {
		logrus.Warnf("AdminLog Create err:%+v, data.Data.len:%v", err, len(data.Data))
	}

	return nil
}
