package Device

import (
	"ColdVerify_server/conf"
	"ColdVerify_server/lib"
	"ColdVerify_server/logs"
	"encoding/json"
	"fmt"
	orm2 "github.com/beego/beego/v2/client/orm"
	"strconv"

	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/beego/beego/v2/adapter/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

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

	T_class        int    `orm:"size(200);null"`  // 分类
	T_id           string `orm:"size(20);null"`   // 设备id
	T_sn           string `orm:"size(256);null"`  // 设备序列号 KF开头，环境监测主机。 YD开头，温途监测主机
	T_failure_time string `orm:"size(256);null"`  // 失效时间
	T_pdf          string `orm:"size(256);null"`  // pdf链接
	T_remark       string `orm:"size(1024);null"` // 备注

	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 保存时都会对时间自动更新
}

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

var redisCache_DeviceClassList cache.Cache

func init() {

	//注册模型
	orm.RegisterModel(new(DeviceClassList))

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

	}
}

// ---------------- Redis -------------------
// Redis_Set(m.T_sn,m) // Redis 更新缓存
func Redis_DeviceClassList_Set(key string, r DeviceClassList) (err error) {
	//json序列化
	str, err := json.Marshal(r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return
	}
	err = redisCache_DeviceClassList.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_DeviceClassList_Get(key string) (r DeviceClassList, is bool) {
	if redisCache_DeviceClassList.IsExist(key) {
		logs.Println("找到key:", key)
		v := redisCache_DeviceClassList.Get(key)
		json.Unmarshal(v.([]byte), &r)
		return r, true
	}
	logs.Println("没有 找到key:", key)
	return DeviceClassList{}, false
}
func Redis_DeviceClassList_DelK(key string) (err error) {
	err = redisCache_DeviceClassList.Delete(key)
	return
}

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

// 获取 ById
func Read_DeviceClassList_ById(id int) (r DeviceClassList, is bool) {
	o := orm.NewOrm()
	r = DeviceClassList{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_DeviceClassList(T_sn string) (r DeviceClassList, is bool) {
	if r, is = Redis_DeviceClassList_Get(T_sn); is == true {
		return r, true
	}

	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceClassList))
	err := qs.Filter("T_sn", T_sn).One(&r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return r, false
	}

	Redis_DeviceClassList_Set(T_sn, r)
	return r, true
}

// 添加
func Read_DeviceClassList_T_class_T_sn(T_class int, T_sn string) (r DeviceClassList, is bool) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceClassList))
	err := qs.Filter("T_sn", T_sn).Filter("T_class", T_class).Filter("T_State", 1).One(&r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return r, false
	}
	return r, true

}

// 添加
func Add_DeviceClassList(r DeviceClassList) (id int64, is bool) {
	o := orm.NewOrm()
	//r.T_State = 1
	//err := o.Read(&r, "T_class", "T_sn", "T_State") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
	//if err == nil {
	//	if r.Id > 0 {
	//		logs.Println("重复添加", r.T_class, r.T_sn)
	//		return 0, false
	//	}
	//}

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

	Redis_DeviceClassList_Set(r.T_sn, r)
	return id, true
}

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

	Redis_DeviceClassList_DelK(v.T_sn)
	return true
}

// 删除
func Delete_DeviceClassList_(v DeviceClassList) 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 {
		logs.Println(lib.FuncName(), err)
		return false
	}

	Redis_DeviceClassList_DelK(v.T_sn)
	return true
}

// 修改
func Update_DeviceClassList(m DeviceClassList, 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_DeviceClassList_Set(m.T_sn, m)
		return true
	} else {
		logs.Println(lib.FuncName(), err)
	}
	return false
}

// 获取列表
func Read_DeviceClassList_List(T_class int, T_sn string, page int, page_z int) (r []DeviceClassList, cnt int64) {

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

	qs := o.QueryTable(new(DeviceClassList))
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * page_z)
	}
	cond := orm.NewCondition()
	cond1 := cond.And("T_class", T_class).And("T_sn__icontains", T_sn).And("T_State", 1) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
	if page_z == 9999 {
		qs.SetCond((*orm2.Condition)(cond1)).OrderBy("T_id").All(&r)
	} else {
		qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_id").All(&r)
	}
	cnt, _ = qs.SetCond((*orm2.Condition)(cond1)).Count()
	return r, cnt
}
func Read_DeviceClassList_OrderList(T_class int, T_sn string, page int, page_z int) (r []DeviceClassList, cnt int64) {

	o := orm.NewOrm()
	var maps_z []orm2.ParamsList
	pagez := page_z

	var offset int
	if page <= 1 {
		offset = 0
	} else {
		page -= 1
		offset = page * pagez
	}

	sqlWhere := "t_class = " + strconv.Itoa(T_class) + " AND t__state = 1"

	if len(T_sn) > 1 {
		sqlWhere += " AND t_sn like \"%" + T_sn + "%\""
	}

	sql := "SELECT COUNT(ID) FROM device_class_list WHERE " + sqlWhere
	fmt.Println(sql)
	_, err := o.Raw(sql).ValuesList(&maps_z)
	if err != nil {
		return r, 0
	}
	if len(maps_z) == 0 {
		return r, 0
	}
	//fmt.Println("maps_z；",maps_z[0][0])
	sql = "SELECT *  FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "
	if page_z != 9999 {
		sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
	}

	fmt.Println(sql)
	_, err = o.Raw(sql).QueryRows(&r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return r, 0
	}

	//value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
	key, _ := strconv.Atoi(maps_z[0][0].(string))
	return r, int64(key)
}

// 获取列表
func Read_DeviceClassList_List_id(T_class_Id int) (r []DeviceClassList) {

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

	qs := o.QueryTable(new(DeviceClassList))

	qs.Filter("T_class", T_class_Id).Filter("T_State", 1).All(&r)

	return r
}
