package eta

import (
	"eta_gn/eta_bridge/global"
	"time"
)

type SysSession struct {
	Id              int       `gorm:"primaryKey;column:id;type:bigint(20);not null" json:"id"`
	SysUserId       int       `gorm:"column:sys_user_id;type:bigint(20)" json:"sys_user_id"`
	UserName        string    `gorm:"column:user_name;type:varchar(32)" json:"user_name"`
	AccessToken     string    `gorm:"index:access_token;column:access_token;type:varchar(255)" json:"access_token"`
	IsRemember      int       `gorm:"column:is_remember;type:tinyint(9) unsigned;default:0" json:"is_remember"` // 是否记住密码,属于受信设备
	ExpiredTime     time.Time `gorm:"column:expired_time;type:datetime" json:"expired_time"`
	CreatedTime     time.Time `gorm:"index:created_time;column:created_time;type:datetime;default:CURRENT_TIMESTAMP" json:"created_time"` // 创建时间
	LastUpdatedTime time.Time `gorm:"index:last_updated_time;column:last_updated_time;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"last_updated_time"`
}

func (m *SysSession) TableName() string {
	return "sys_session"
}

// AddSysSession 新增session
func AddSysSession(item *SysSession) (err error) {
	err = global.MYSQL["hz_eta"].Create(item).Error
	return
}

// GetSysSessionByToken 根据Token获取session
func GetSysSessionByToken(token string) (item *SysSession, err error) {
	err = global.MYSQL["hz_eta"].Where("access_token = ? AND expired_time > NOW()", token).Order("expired_time DESC").First(&item).Error
	return
}

// GetUserUnexpiredSysSession 获取用户未过期的Token
func GetUserUnexpiredSysSession(userName, expiredTime string) (item *SysSession, err error) {
	err = global.MYSQL["hz_eta"].Where("user_name = ? AND expired_time > ?", userName, expiredTime).Order("expired_time DESC").First(&item).Error
	return
}