package NatsServer

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

// 验证TOKEY
func Verification(GetCookie string, GetString string) (bool, Account.User) {

	User_tokey := GetCookie
	if len(User_tokey) == 0 {
		User_tokey = GetString
	}
	if len(User_tokey) == 0 {
		return false, Account.User{}
	}
	// 请求-响应， 向 verification 发布一个 `ToKey` 请求数据，设置超时间3秒，如果有多个响应，只接收第一个收到的消息
	msg, err := lib.Nats.Request("Cold_User_verification", []byte(User_tokey), 3*time.Second)
	if err != nil {
		return false, Account.User{}
	}
	fmt.Printf("Cold_User_verification : %s\n", string(msg.Data))
	type T_R struct {
		Code int16        `xml:"Code"`
		Msg  string       `xml:"Msg"`
		Data Account.User `xml:"Data"` // 泛型
	}

	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil || t_R.Code != 200 {
		return false, Account.User{}
	}

	return true, t_R.Data

}

func CheckUserPermissions(Power_Id int, Req_Url string) bool {
	type T_Req struct {
		Power_Id int    `xml:"Power_Id"` // 权限id
		Req_Url  string `xml:"Req_Url"`  // 请求url
	}
	t_Req := T_Req{
		Power_Id: Power_Id,
		Req_Url:  Req_Url,
	}
	b, _ := msgpack.Marshal(&t_Req)

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

	if err != nil {
		return false
	}

	type T_R struct {
		Code int16  `xml:"Code"`
		Msg  string `xml:"Msg"`
		Pass bool   `xml:"Pass"` // 泛型
	}

	var t_R T_R

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

	return t_R.Pass
}
