package System

import (
	"ColdVerify_server/logs"
	"encoding/json"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	"time"
)

type UserLogs struct {
	Id         int    `orm:"column(ID);size(11);auto;pk"`
	Logs_uuid  string `orm:"size(256);null"`  //
	Logs_class string `orm:"size(256);null"`  //
	Logs_Title string `orm:"size(256);null"`  // 标题
	Logs_Txt   string `orm:"type(text);null"` // 详情

	CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now 每次 model 保存时都会对时间自动更新
	UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"`     //auto_now_add 第一次保存时才设置时间
}

func (t *UserLogs) TableName() string {
	return "user_logs" // 数据库名称   // ************** 替换 FormulaList **************
}

func init() {
	//注册模型
	orm.RegisterModel(new(UserLogs))

}

// 添加  System.Add_UserLogs(user_r.T_user,"登陆", "管理员登陆", "")
func Add_UserLogs(Logs_uuid string, Logs_class string, Logs_Title string, Logs_Txt string) {
	o := orm.NewOrm()
	m := UserLogs{Logs_uuid: Logs_uuid, Logs_class: Logs_class, Logs_Title: Logs_Title, Logs_Txt: Logs_Txt}
	o.Insert(&m)
}
func Add_UserLogs_T(Logs_uuid string, Logs_class string, Logs_Title string, Logs_Txt_T interface{}) {
	o := orm.NewOrm()
	jsonStu, err := json.Marshal(Logs_Txt_T)
	if err != nil {
		logs.Println("Add_UserLogs_T JSON ,err=", err)
	}
	m := UserLogs{Logs_uuid: Logs_uuid, Logs_class: Logs_class, Logs_Title: Logs_Title, Logs_Txt: string(jsonStu)}
	o.Insert(&m)
}

// 获取列表
func Read_UserLogs_ALL(page, page_z int, Logs_class string) (r []UserLogs, cnt int64) {

	o := orm.NewOrm()
	// 也可以直接使用 Model 结构体作为表名

	qs := o.QueryTable(new(UserLogs))
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * page_z)
	}

	qs.Limit(page_z, offset).Filter("Logs_class__icontains", Logs_class).OrderBy("-Id").All(&r)
	cnt, _ = qs.Filter("Logs_class__icontains", Logs_class).Count()

	return r, cnt
}

// 获取列表
func Read_UserLogs_Class() (lists orm2.ParamsList) {
	o := orm.NewOrm()
	var pl_lists orm2.ParamsList
	num, err := o.Raw("SELECT DISTINCT logs_class FROM UserLogs LIMIT 0,1000").ValuesFlat(&pl_lists)
	if err == nil {
		logs.Println("user nums: ", num)
	}
	return pl_lists
}
