package system

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

type SysSession struct {
	Id              int `orm:"column(id);pk"`
	SysUserId       int
	UserName        string
	AccessToken     string
	IsRemember      int `description:"是否属于受信设备"`
	ExpiredTime     time.Time
	CreatedTime     time.Time
	LastUpdatedTime time.Time
}

// 新增用户登录session信息
func AddSysSession(item *SysSession) (err error) {
	o := orm.NewOrm()
	lastId, err := o.Insert(item)
	if err != nil {
		return
	}
	item.Id = int(lastId)
	return
}

func GetSysSessionBySysUserId(sysUserId int) (item *SysSession, err error) {
	sql := `SELECT * FROM sys_session WHERE sys_user_id=? AND expired_time> NOW() ORDER BY expired_time DESC LIMIT 1 `
	o := orm.NewOrm()
	err = o.Raw(sql, sysUserId).QueryRow(&item)
	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
}

// 过期掉用户token
func ExpiredSysSessionByAdminId(adminId int) (err error) {
	sql := `update sys_session set expired_time = NOW()  WHERE sys_user_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, adminId).Exec()
	return
}
