package dao

import (
	"context"
	"encoding/json"
	"fmt"
	"server/global"
)

type DeviceRelay struct {
	ID       int    `json:"id"`
	RelayID  int    `json:"relayId" gorm:"comment:回路id"`
	DeviceSn string `json:"deviceSn" gorm:"comment:设备Sn"`
	State    bool   `json:"state" gorm:"comment:设备状态"`
}

func (DeviceRelay) TableName() string {
	return "device_relay"
}

func QueryRelayBySn(sn string) (deviceRelays []DeviceRelay, err error) {
	err = global.GVA_DB.Model(&DeviceRelay{}).Where("device_sn = ?", sn).Find(&deviceRelays).Error
	return
}

func UpdateRelayState(deviceSn string, relayId int, state bool) error {
	return global.GVA_DB.Model(&DeviceRelay{}).Where("device_sn = ? AND relay_id = ?", deviceSn, relayId).Update("state", state).Error
}

func GetCacheRelayState(sn string) (deviceRelays []DeviceRelay, err error) {
	if global.GVA_REDIS == nil {
		return
	}
	result, err := global.GVA_REDIS.Get(context.Background(), "device_relays_"+sn).Result()
	if err != nil {
		return
	}
	err = json.Unmarshal([]byte(result), &deviceRelays)
	if err != nil {
		return
	}
	return
}

// SaveCacheDeviceRelays 保存电感数据
func SaveCacheDeviceRelays(sn string, deviceRelays []DeviceRelay) (err error) {
	jsonData, err := json.Marshal(deviceRelays)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}
	if global.GVA_REDIS == nil {
		return
	}
	err = global.GVA_REDIS.Set(context.Background(), "device_relays_"+sn, jsonData, 0).Err()
	return
}
