package Device

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

// 模板
type DeviceData_R struct {
	T_t    float32   // 温度
	T_rh   float32   // 湿度
	T_Site string    // GPS
	T_time time.Time // 采集时间
	T_sp   int       // 传感器参数ID
	//create_time
}
type DeviceData_old struct {
	T_t    float32
	T_rh   float32
	T_site string
	T_sp   int
}

// 模板
type DeviceData_RR struct {
	T_name    string  // 传感器名称
	T_t       float32 // 温度
	T_rh      float32 // 湿度
	T_site    string  // GPS
	T_Tlower  float32 // 温度下限
	T_Tupper  float32 // 温度上限
	T_RHlower float32 // 湿度下限
	T_RHupper float32 // 湿度上限
	T_time    string  // 采集时间
	T_ist     int     // 温度   1开启   2关闭
	T_ish     int     // 湿度   1开启   2关闭
}
type DeviceData_ struct {
	T_t    float32   // 温度
	T_rh   float32   // 湿度
	T_site string    // GPS
	T_time time.Time // 采集时间
}

var redis_DeviceData cache.Cache

func init() {

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

// ---------------- Redis -------------------
// Redis_Set(m.T_sn,m) // Redis 更新缓存
func RedisDeviceData_Set(T_sn string, T_id int, r DeviceData_R) (err error) {
	key := T_sn + "|" + strconv.Itoa(T_id)

	if redis_DeviceData.IsExist(key) {
		var t DeviceData_R
		v := redis_DeviceData.Get(key)
		json.Unmarshal(v.([]byte), &t)
		// 防止时间溢出
		if time.Now().Unix() <= r.T_time.Unix() {
			r.T_time = time.Now()
		}
		// 提前最新数据
		if t.T_time.Unix() > r.T_time.Unix() {
			// 储存的 是最新数据
			return
		}
	}

	//json序列化
	str, err := json.Marshal(r)
	if err != nil {
		logs.PrintlnError("RedisDeviceData_Set", err)
		return
	}
	err = redis_DeviceData.Put(key, str, 1*time.Hour)
	if err != nil {
		logs.Println("set key:", key, ",value:", str, err)
	}
	return
}

func RedisDeviceData_Get(key string) (r DeviceData_R, is bool) {
	if redis_DeviceData.IsExist(key) {
		v := redis_DeviceData.Get(key)
		json.Unmarshal(v.([]byte), &r)
		return r, true
	}
	return DeviceData_R{}, false
}

func Read_DeviceData_List(SN string, T_id int, Time_start_ string, Time_end_ string) (maps []DeviceData_) {
	o := orm.NewOrm()

	sql_time := ""
	if len(Time_start_) > 1 {
		sql_time += " t_time >= '" + Time_start_ + "' AND "
	}

	if len(Time_end_) > 1 {
		sql_time += " t_time <= '" + Time_end_ + "' AND "
	}

	sql := "SELECT t_t,t_rh,t_site,DATE_FORMAT(t_time,'%Y-%m-%d %H:%i:%s') AS t_time,t_time AS t_time1 FROM z_device_data_" + SN + " WHERE " + sql_time + " t_id = " + strconv.Itoa(T_id) + " ORDER BY t_time1 DESC  LIMIT 1000"
	fmt.Println(sql)
	_, err := o.Raw(sql).QueryRows(&maps)
	if err != nil {
		logs.PrintlnError(lib.FuncName(), err)
		return
	}

	return
}
