package NatsServer

import (
	"Cold_GoodsOrder/lib"
	"Cold_GoodsOrder/models/Device"
	"errors"
	"fmt"
	"github.com/vmihailenco/msgpack/v5"
	"time"
)

func ReadDeviceByT_sn(T_sn string) (d Device.Device, err error) {
	msg, err := lib.Nats.Request("Cold_ReadDeviceByT_sn", []byte(T_sn), 3*time.Second)
	if err != nil {
		return d, err
	}
	fmt.Printf("Cold_ReadDeviceSensorALLByT_sn: %s\n", string(msg.Data))
	type T_R struct {
		Code int16         `xml:"Code"`
		Msg  string        `xml:"Msg"`
		Data Device.Device `xml:"Data"` // 泛型
	}
	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil {
		return d, err
	}
	if t_R.Code != 200 {
		return d, errors.New(t_R.Msg)
	}

	return t_R.Data, nil
}

func ReadDeviceSensorALLByT_sn(T_sn string) (d []Device.DeviceSensor) {
	msg, err := lib.Nats.Request("Cold_ReadDeviceSensorALLByT_sn", []byte(T_sn), 3*time.Second)
	if err != nil {
		return d
	}
	fmt.Printf("Cold_ReadDeviceSensorALLByT_sn: %s\n", string(msg.Data))
	type T_R struct {
		Code int16                 `xml:"Code"`
		Msg  string                `xml:"Msg"`
		Data []Device.DeviceSensor `xml:"Data"` // 泛型
	}
	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil {
		return d
	}

	return t_R.Data
}

func ReadDeviceDataListBy_T_snid(T_snid string, Time_start string, Time_end string, page int, page_z int) (r []Device.DeviceData_R, cnt int64) {
	type T_Req struct {
		T_snid     string `xml:"T_snid"`
		Time_start string `xml:"Time_start"`
		Time_end   string `xml:"Time_end"`
		Page       int    `xml:"Page"`
		Page_z     int    `xml:"Page_z"`
	}
	t_Req := T_Req{
		T_snid:     T_snid,
		Time_start: Time_start,
		Time_end:   Time_end,
		Page:       page,
		Page_z:     page_z,
	}
	b, _ := msgpack.Marshal(&t_Req)

	// 请求-响应， 向 verification 发布一个 `ToKey` 请求数据，设置超时间3秒，如果有多个响应，只接收第一个收到的消息
	msg, err := lib.Nats.Request("Cold_ReadDeviceDataListBy_T_snid", b, 3*time.Second)
	fmt.Printf("Cold_ReadDeviceDataListBy_T_snid : %s\n", string(msg.Data))

	if err != nil {
		return r, cnt
	}

	type T_R struct {
		Code  int16                 `xml:"Code"`
		Msg   string                `xml:"Msg"`
		Count int64                 `xml:"Count"`
		Data  []Device.DeviceData_R `xml:"Data"` // 泛型
	}

	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil {
		return r, cnt
	}

	return t_R.Data, t_R.Count

}
