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"
	"strconv"
	"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 "TaskLogs" // 数据库名称   // ************** 替换 FormulaList **************
}

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

}

type TaskLogs_ struct {
	T_uuid     string // 操作用户uuid
	T_name     string // 操作用户name
	T_task_id  string // 任务ID
	Logs_class string //
	Logs_Title string // 标题
	Logs_Txt   string // 详情
	CreateTime time.Time
}

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, page int, page_z int) ([]TaskLogs_, int) {

	o := orm.NewOrm()
	var offset int
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_z
	}

	var maps_z []orm2.ParamsList
	var maps []TaskLogs_

	// 获取总条数
	sql := "SELECT COUNT(ID) FROM TaskLogs WHERE  t_task_id=" + "\"" + T_task_id + "\""

	fmt.Println(sql)
	_, err := o.Raw(sql).ValuesList(&maps_z)
	if err != nil {
		return maps, 0
	}
	if len(maps_z) == 0 {
		return maps, 0
	}
	sql = "SELECT * FROM TaskLogs t " +
		"LEFT JOIN (SELECT t_uuid, t_name FROM `Admin`) c ON c.t_uuid=t.t_uuid " +
		"WHERE t.t_task_id=" + "\"" + T_task_id + "\""

	sql = sql + " ORDER BY t.create_time DESC LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z)
	fmt.Println(sql)
	_, err = o.Raw(sql).QueryRows(&maps)

	cnt, _ := strconv.Atoi(maps_z[0][0].(string))
	return maps, cnt
}
