package Task

import (
	"encoding/json"
	"fmt"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

type TaskLogs struct {
	Id         int    `orm:"column(ID);size(11);auto;pk"`
	T_uuid     string `orm:"size(256);null"`  // 操作用户uuid
	T_task_id  string `orm:"size(256);null"`  // 任务ID
	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 *TaskLogs) TableName() string {
	return "task_logs" // 数据库名称   // ************** 替换 FormulaList **************
}

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

}

type TaskLogs_R struct {
	T_uuid     string // 操作用户uuid
	T_name     string // 操作用户name
	T_task_id  string // 任务ID
	Logs_class string // 分类
	Logs_Title string // 标题
	Logs_Txt   string // 详情
	CreateTime string
}

func TaskLogsToTaskLogs_R(T TaskLogs, adminMap map[string]string) (T_r TaskLogs_R) {
	T_r.T_uuid = T.T_uuid
	T_r.T_name = adminMap[T.T_uuid]
	T_r.T_task_id = T.T_task_id
	T_r.Logs_class = T.Logs_class
	T_r.Logs_Title = T.Logs_Title
	T_r.Logs_Txt = T.Logs_Txt
	T_r.CreateTime = T.CreateTime.Format("2006-01-02 15:04:05")
	return T_r
}

func Add_TaskLogs_T(T_uuid string, T_task_id string, Logs_class string, Logs_Title string, Logs_Txt_T interface{}) {
	o := orm.NewOrm()
	jsonStu, err := json.Marshal(Logs_Txt_T)
	if err != nil {
		fmt.Println("Add_TaskLogs_T JSON ,err=", err)
	}
	m := TaskLogs{T_uuid: T_uuid, T_task_id: T_task_id, Logs_class: Logs_class, Logs_Title: Logs_Title, Logs_Txt: string(jsonStu)}
	o.Insert(&m)
}

// 获取列表
func Read_TaskLogs_List(T_task_id string, adminMap map[string]string, page int, page_z int) ([]TaskLogs_R, int) {

	o := orm.NewOrm()
	var offset int
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_z
	}
	qs := o.QueryTable(new(TaskLogs))
	var r []TaskLogs
	cond := orm.NewCondition()
	cond1 := cond.And("T_task_id", T_task_id)

	qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-CreateTime").All(&r)
	cnt, _ := qs.SetCond((*orm2.Condition)(cond1)).Count()

	// 转换
	var TaskLogsList []TaskLogs_R
	for _, v := range r {
		TaskLogsList = append(TaskLogsList, TaskLogsToTaskLogs_R(v, adminMap))
	}

	return TaskLogsList, int(cnt)
}
