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
}

// AddSysSession 新增用户登录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
}

// GetSysSessionByToken 根据token获取session
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
}

// ExpiredSysSessionByAdminId 过期掉用户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
}

// UnBindAdminRecordByUserId 根据系统用户id解除绑定用户关系
func UnBindAdminRecordByUserId(userId int) (err error) {
	o := orm.NewOrm()
	msql := ` UPDATE admin_record SET user_id = 0 WHERE user_id = ? `
	_, err = o.Raw(msql, userId).Exec()
	return
}
