package models

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

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

func GetCygxSessionMobile(token string) (item *CygxSessionMobile, err error) {
	sql := `SELECT * FROM cygx_session_mobile 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 GetSessionMobileCountByToken(token string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_session_mobile 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 AddCygxSessionMobile(item *CygxSessionMobile) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(item)
	return
}

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