package main

import (
	"errors"
	"strconv"
	"time"

	"github.com/sirupsen/logrus"

	"lc/common/protocol"
	"lc/common/util"
)

// 缓存最新状态到redis
func cacheState(id, strTime string, state uint8) {
	fields := make(map[string]interface{})
	if state == 0 {
		fields[ONLINE] = 1 //在线
	} else {
		fields[ONLINE] = 0 //离线
	}
	fields[TLast] = strTime
	if err := redisCltRawData.HMSet(DevStatusPrefix+id, fields).Err(); err != nil {
		logrus.Errorf("更新设备[%s]状态[state=%d]失败", id, state)
	}

}

// 取缓存最新状态
func getState(id string) (retTime time.Time, retState uint8, retErr error) {
	defer func() {
		if err1 := recover(); err1 != nil {
			logrus.Errorf("getState发生错误:%v", err1)
		}
	}()
	retTime = time.Time{}
	retState = 0
	retErr = errors.New("redis数据解析错误")
	list, err := redisCltRawData.HMGet(DevStatusPrefix+id, TLast, ONLINE).Result()
	if err == nil && list[0] != nil || list[1] != nil {
		s, err0 := strconv.Atoi(list[1].(string))
		t, err1 := util.MlParseTime(list[0].(string))
		if err0 == nil && err1 == nil {
			if s == 0 {
				s = 1
			} else {
				s = 0
			}
			retTime = t
			retState = uint8(s)
			retErr = nil
		}
	}
	return
}

// 缓存最新数据到redis
func cacheData(id string, t time.Time, mapData map[uint16]float64) {
	if len(mapData) == 0 {
		return
	}
	redisMap := make(map[string]interface{})
	redisMap[TIME] = protocol.ToBJTime(t).Format("2006-01-02 15:04:05")
	for k, v := range mapData {
		redisMap[strconv.Itoa(int(k))] = v
	}
	if err := redisCltRawData.HMSet(DevDataPrefix+id, redisMap).Err(); err != nil {
		logrus.Errorf("缓存到redis失败:%s", err.Error())
	}
}

// 缓存最新数据到redis
func cacheLedData(id string, t time.Time, mapData map[string]interface{}) {
	if len(mapData) == 0 {
		return
	}
	redisMap := make(map[string]interface{})
	redisMap[TIME] = protocol.ToBJTime(t).Format("2006-01-02 15:04:05")
	for k, v := range mapData {
		redisMap[k] = v
	}
	if err := redisCltRawData.HMSet(DevDataPrefix+id, redisMap).Err(); err != nil {
		logrus.Errorf("leddata缓存到redis失败:%s", err.Error())
	}
}
