package models

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type CygxSession struct {
	SessionId       int `orm:"column(session_id);pk"`
	UnionId         string
	UserId          int
	OpenId          string
	AccessToken     string
	ExpireTime      time.Time
	CreatedTime     time.Time
	LastUpdatedTime time.Time
}

func GetSessionByToken(token string) (item *CygxSession, err error) {
	sql := `SELECT * FROM cygx_session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
	o := orm.NewOrm()
	err = o.Raw(sql, token).QueryRow(&item)
	return
}

func GetSessionCountByToken(token string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
	o := orm.NewOrm()
	err = o.Raw(sql, token).QueryRow(&count)
	return
}

//添加用户session信息
func AddSession(item *CygxSession) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(item)
	return
}

func GetTokenByUid(uid int) (item *CygxSession, err error) {
	sql := `SELECT * FROM cygx_session WHERE user_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
	o := orm.NewOrm()
	err = o.Raw(sql, uid).QueryRow(&item)
	return
}

//根据用户id获取token
func GetTokenByOpenId(openId string) (item *CygxSession, err error) {
	sql := `SELECT * FROM cygx_session WHERE open_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
	o := orm.NewOrm()
	err = o.Raw(sql, openId).QueryRow(&item)
	return
}
