package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type SysSession struct {
	SysSessionId    int `orm:"pk"`
	SysUserId       int
	UserName        string
	AccessToken     string
	ExpiredTime     time.Time
	CreatedTime     time.Time
	LastUpdatedTime time.Time
}

func (s *SysSession) AddSysSession() (err error) {
	o := orm.NewOrm()
	insertId, err := o.Insert(s)
	s.SysSessionId = int(insertId)
	return
}

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

// ExpiredSysSessionBySysUserId 过期掉用户token
func ExpiredSysSessionBySysUserId(sysUserId int) (err error) {
	sql := `UPDATE sys_session SET expired_time = NOW()  WHERE sys_user_id=? AND expired_time > NOW()`
	o := orm.NewOrm()
	_, err = o.Raw(sql, sysUserId).Exec()
	return
}
