package Template

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

// 模板
type Template struct {
	Id int `orm:"column(ID);size(11);auto;pk"`

	T_name  string `orm:"size(256);null"`  // 标题
	T_class int    `orm:"size(200);null"`  // 分类
	T_img   string `orm:"size(256);null"`  // 图片
	T_int   int    `orm:"size(200);null"`  //  数量
	T_text  string `orm:"type(text);null"` // 详情

	T_Visit    int       `orm:"size(200);default(0)"`                                  // 浏览量
	T_State    int       `orm:"size(2);default(1)"`                                    // 0 删除   1 正常
	CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
	UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"`     //auto_now 每次 model 保存时都会对时间自动更新
}

type Template_R struct {
	T_name  string `orm:"size(256);null"`  // 标题
	T_class int    `orm:"size(200);null"`  // 分类
	T_img   string `orm:"size(256);null"`  // 图片
	T_int   int    `orm:"size(200);null"`  //  数量
	T_text  string `orm:"type(text);null"` // 详情
}

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

var redisCache_Template cache.Cache

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

	config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
		"redis_"+"Template", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
	logs.Println(config)
	var err error
	redisCache_Template, err = cache.NewCache("redis", config)
	if err != nil || redisCache_Template == nil {
		errMsg := "failed to init redis"
		logs.Println(errMsg, err)

	}
}

// -------------------------------------------------------------
func TemplateToTemplate_R(T Template) (T_r Template_R) {
	T_r.T_name = T.T_name

	//......
	return T_r
}

// ---------------- Redis -------------------
// Redis_Set(m.T_sn,m) // Redis 更新缓存
func Redis_Template_Set(key string, r Template) (err error) {
	//json序列化
	str, err := json.Marshal(r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return
	}
	err = redisCache_Template.Put(key, str, 24*time.Hour)
	if err != nil {
		logs.Println("set key:", key, ",value:", str, err)
	}
	return
}

// if r,is :=Redis_Get(T_sn);is{
// return r,nil
// }
func Redis_Template_Get(key string) (r Template, is bool) {
	if redisCache_Template.IsExist(key) {
		logs.Println("找到key:", key)
		v := redisCache_Template.Get(key)
		json.Unmarshal(v.([]byte), &r)
		return r, true
	}
	logs.Println("没有 找到key:", key)
	return Template{}, false
}
func Redis_Template_DelK(key string) (err error) {
	err = redisCache_Template.Delete(key)
	return
}

// ---------------- 特殊方法 -------------------

// 获取 ById
func Read_Template_ById(id int) (r Template, is bool) {
	o := orm.NewOrm()
	r = Template{Id: id}
	err := o.Read(&r) // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return r, false
	}
	return r, true
}

// 获取 By
func Read_Template(T_name string) (r Template, is bool) {
	if r, is = Redis_Template_Get(T_name); is == true {
		return r, true
	}

	o := orm.NewOrm()
	qs := o.QueryTable(new(Template))
	err := qs.Filter("T_name", T_name).One(&r)
	if err != nil {
		return r, false
	}

	Redis_Template_Set(T_name, r)
	return r, true
}

// 添加
func Add_Template(r Template) (id int64, is bool) {
	o := orm.NewOrm()

	// 生成编号
	//rand_x := 0
	//for true {
	//	r.T_Product_id = lib.GetRandstring(4, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", int64(rand_x)) // 1,336,336
	//	err := o.Read(&r, "T_Product_id") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
	//	if err != nil {
	//		break
	//	}
	//	rand_x += 1
	//}

	id, err := o.Insert(&r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return 0, false
	}

	Redis_Template_Set(r.T_name, r)
	return id, true
}

// 删除
func Delete_Template(v Template) bool {
	o := orm.NewOrm()
	if num, err := o.Delete(&v); err == nil {
		logs.Println("Number of records deleted in database:", num)
	} else {
		return false
	}

	Redis_Template_DelK(v.T_name)
	return true
}

// 删除
func Delete_Template_(v Template) bool {
	o := orm.NewOrm()
	v.T_State = 0
	if num, err := o.Update(&v, "T_State"); err == nil {
		fmt.Println("Number of records updated in database:", num)
	} else {
		return false
	}

	Redis_Template_DelK(v.T_name)
	return true
}

// 修改
func Update_Template(m Template, cols ...string) bool {
	o := orm.NewOrm()
	if num, err := o.Update(&m, cols...); err == nil {
		fmt.Println("Number of records updated in database:", num)
		Redis_Template_Set(m.T_name, m)
		return true
	}
	return false
}

// 获取列表
func Read_Template_List(T_name string, T_class int, page int, page_z int) ([]Template_R, int64) {

	o := orm.NewOrm()
	// 也可以直接使用 Model 结构体作为表名
	var r []Template
	qs := o.QueryTable(new(Template))
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * page_z)
	}
	cond := orm.NewCondition()
	cond1 := cond.And("T_name__icontains", T_name).And("T_State", 1) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)

	if T_class > 0 {
		//cond1.AndCond(cond.And("T_class", class))
		cond1 = cond.AndCond(cond1).OrCond(cond.And("T_class", T_class))
	}
	qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-Id").All(&r)
	cnt, _ := qs.SetCond((*orm2.Condition)(cond1)).Count()

	// 转换
	var Template_r []Template_R
	for _, v := range r {
		Template_r = append(Template_r, TemplateToTemplate_R(v))
	}

	return Template_r, cnt
}

// 获取列表 /时间筛选  Time_start_ Time_end_    2021-12-30，所以下面要加后缀 时间
func Read_Template_List_Time(page int, T_sn string, T_Title string, Time_start_ string, Time_end_ string) ([]Template_R, int64) {

	o := orm.NewOrm()
	// 也可以直接使用 Model 结构体作为表名
	var r []Template
	var cnt int64
	qs := o.QueryTable(new(Template))
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * conf.Page_size)
	}

	if len(Time_start_) > 1 && len(Time_end_) > 1 {
		fmt.Println(Time_start_, Time_end_)
		qs.Limit(conf.Page_size, offset).Filter("T_Ut__lte", Time_end_+" 23:59:59").Filter("T_Ut__gte", Time_start_+" 00:00:00").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).OrderBy("-Id").Filter("T_State", 1).All(&r)
		cnt, _ = qs.Filter("T_Ut__lte", Time_end_+" 23:59:59").Filter("T_Ut__gte", Time_start_+" 00:00:00").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).Filter("T_State", 1).Count()
		return []Template_R{}, cnt
	}

	if len(Time_start_) > 1 {
		qs.Limit(conf.Page_size, offset).Filter("T_Ut__gte", Time_start_+" 00:00:00").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).OrderBy("-Id").Filter("T_State", 1).All(&r)
		cnt, _ = qs.Filter("T_Ut__gte", Time_start_+" 00:00:00").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).Filter("T_State", 1).Count()
		return []Template_R{}, cnt
	} else if len(Time_end_) > 1 {
		qs.Limit(conf.Page_size, offset).Filter("T_Ut__lte", Time_end_+" 23:59:59").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).OrderBy("-Id").Filter("T_State", 1).All(&r)
		cnt, _ = qs.Filter("T_Ut__lte", Time_end_+" 23:59:59").Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).Filter("T_State", 1).Count()
		return []Template_R{}, cnt
	}

	qs.Limit(conf.Page_size, offset).Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).OrderBy("-Id").Filter("T_State", 1).All(&r)
	cnt, _ = qs.Filter("T_Title__icontains", T_Title).Filter("T_sn__icontains", T_sn).Filter("T_State", 1).Count()

	var Template_r []Template_R
	for _, v := range r {
		Template_r = append(Template_r, TemplateToTemplate_R(v))
	}

	return Template_r, cnt
}
