package Device

import (
	"ColdVerify_local/conf"
	"ColdVerify_local/lib"
	"ColdVerify_local/logs"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/cache"
	_ "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"
	"strings"
	"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_terminal       int    `orm:"size(2);default(1)"` // 1-测点 2-终端
	T_failure_time   string `orm:"size(256);null"`     // 失效时间
	T_pdf            string `orm:"size(256);null"`     // pdf链接
	T_Certificate_sn string `orm:"size(256);null"`     // 证书编号
	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).One(&r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return r, false
	}
	return r, true
}

func Read_DeviceClassList_T_class_T_id(T_class int, T_id string) (r DeviceClassList, is bool) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceClassList))
	err := qs.Filter("T_id", T_id).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 {
		logs.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 {
		logs.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, T_id, T_remark 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 + "%\""
	}
	if len(T_id) > 1 {
		sqlWhere += " AND T_id like \"%" + T_id + "%\""
	}
	if len(T_remark) > 0 {
		sqlWhere += " AND t_remark like \"%" + T_remark + "%\""
	}

	sql := "SELECT COUNT(ID) FROM device_class_list WHERE " + sqlWhere
	logs.Println(sql)
	_, err := o.Raw(sql).ValuesList(&maps_z)
	if err != nil {
		return r, 0
	}
	if len(maps_z) == 0 {
		return r, 0
	}
	//logs.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)
	}

	logs.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
}

// 排除终端
func Read_DeviceClassList_List_id_By_Terminal(T_class_Id int, T_Terminal bool) (r []DeviceClassList) {

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

	sqlWhere := "t_class = " + strconv.Itoa(T_class_Id) + " AND t__state = 1"
	if T_Terminal == true {
		sqlWhere += " AND t_terminal = 2"
	} else {
		sqlWhere += " AND t_terminal <= 1"
	}

	sql := "SELECT *  FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "

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

	return r

}

// 获取列表
func Read_DeviceClassList_List_id_T_remark(T_class_Id int, T_remark string) (r []DeviceClassList) {

	o := orm.NewOrm()

	T_remark_s := strings.Split(T_remark, "|")

	sqlWhere := "t_class = " + strconv.Itoa(T_class_Id) + " AND t__state = 1 AND t_terminal <= 1"

	var conditions []string
	for _, v := range T_remark_s {
		if v == "" {
			continue
		}
		conditions = append(conditions, fmt.Sprintf("t_remark LIKE '%%%s%%'", v))
	}
	if len(conditions) > 0 {
		sqlWhere += " AND (" + strings.Join(conditions, " OR ") + ")"
	}

	sql := "SELECT *  FROM device_class_list WHERE " + sqlWhere + " ORDER BY t_id+0 "

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

	return r
}

// 获取列表
func Read_DeviceClassList_List_id_T_sn(T_class_Id int, T_sn string) (r []DeviceClassList) {

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

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

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

	return r
}

// 删除重复设备列表
func Del_DeviceClassList_Duplication(T_class int) error {

	o := orm.NewOrm()

	// 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
	sql := "DELETE FROM device_class_list WHERE ID NOT IN (" +
		"SELECT * FROM (SELECT MIN(ID) FROM device_class_list WHERE t__state = 1 AND t_class = " + strconv.Itoa(T_class) +
		" GROUP BY t_class, t_id, t_sn) AS keep_ids) " +
		" AND t__state = 1 AND t_class = " + strconv.Itoa(T_class)

	//  这里有时间优化  用于一次 prepare 多次 exec，以提高批量执行的速度
	logs.Debug(sql)
	res, err := o.Raw(sql).Exec()
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return err
	}
	num, _ := res.RowsAffected()

	logs.Debug("删除重复设备列表: ", num)
	return nil
}

func DeduplicateById(devices []DeviceClassList) []DeviceClassList {
	unique := make(map[int]DeviceClassList)
	for _, device := range devices {
		if _, exists := unique[device.Id]; !exists {
			unique[device.Id] = device
		}
	}

	result := make([]DeviceClassList, 0, len(unique))
	for _, device := range unique {
		result = append(result, device)
	}
	return result
}
func ExcludeDevicesById(devices []DeviceClassList, excludeDevices []DeviceClassList) []DeviceClassList {
	filteredList := make([]DeviceClassList, 0)
	for _, device := range devices {
		exclude := false
		for _, excludeDevice := range excludeDevices {
			if device.T_id == excludeDevice.T_id {
				exclude = true
				break
			}
		}
		if !exclude {
			filteredList = append(filteredList, device)
		}
	}
	return filteredList
}

func JoinDeviceClassListSnToString(devices []DeviceClassList) string {
	var builder strings.Builder

	for _, device := range devices {
		builder.WriteString(device.T_sn)
		builder.WriteString("|")
	}

	return builder.String()
}
