package router

import (
	"app.yhyue.com/moapp/jybase/redis"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/url"
)

const JY_SESSIONNAME = "SESSIONID"

// JySession 剑鱼程序SESSION获取
type JySession struct {
	UserId string // 上下文用户信息
	Data   g.Map  // 当前Session管理对象
}

// GetJySession 获取剑鱼程序session内容
func GetJySession(ctx context.Context) (jSession *JySession) {
	jSession = &JySession{}
	value := ctx.Value(JY_SESSIONNAME)
	if value == nil {
		return
	}
	if localCtx, ok := value.(*JySession); ok {
		jSession = localCtx
	}
	return
}

// InitJySessionContext 获取用户session
func InitJySessionContext(r *ghttp.Request) (jSession *JySession, err error) {
	jSession = &JySession{}
	cookie, err := r.Request.Cookie(JY_SESSIONNAME)
	if err != nil {
		return
	}
	if cookie.Value == "" {
		err = fmt.Errorf("cookie 内容为空")
		return
	}
	findKey, _ := url.QueryUnescape(cookie.Value)
	bs, err := redis.GetBytes("session", findKey)
	if err != nil {
		return
	}
	var data map[string]interface{}
	err = json.Unmarshal(*bs, &data)

	jSession.UserId, _ = data["userId"].(string)
	jSession.Data = data
	return
}
