package account

import (
	"fmt"
	"strconv"
	"time"

	sysMenuService "nms_nbi/features/sys_menu/service"
	sysRoleService "nms_nbi/features/sys_role/service"
	"nms_nbi/lib/core/cache"
	"nms_nbi/lib/core/vo"
	"nms_nbi/lib/dborm"
	srcConfig "nms_nbi/src/framework/config"
)

// 登录缓存用户信息
func CacheLoginUser(user *dborm.User) {
	// 过期时间
	expiresStr, err := dborm.XormGetConfigValue("Security", "sessionExpires")
	if err != nil {
		expiresStr = "18000"
	}
	expiresValue, _ := strconv.Atoi(expiresStr)
	expireTime := time.Duration(expiresValue) * time.Second

	nowTime := time.Now().UnixMilli()

	// 登录用户
	loginUser := vo.LoginUser{
		UserID:     fmt.Sprint(user.Id),
		UserName:   user.Name,
		ExpireTime: nowTime + expireTime.Milliseconds(),
		LoginTime:  nowTime,
		User:       *user,
	}

	// 是否管理员
	if srcConfig.IsAdmin(loginUser.UserID) {
		loginUser.Permissions = []string{"*:*:*"}
	} else {
		// 获取权限标识
		loginUser.Permissions = sysMenuService.NewRepoSysMenu.SelectMenuPermsByUserId(loginUser.UserID)
		// 获取角色信息
		loginUser.User.Roles = sysRoleService.NewRepoSysRole.SelectRoleListByUserId(loginUser.UserID)
	}

	// 缓存时间
	cache.SetLocalTTL(user.AccountId, loginUser, time.Duration(expireTime))
}

// 清除缓存用户信息
func ClearLoginUser(accountId string) {
	cache.DeleteLocalTTL(accountId)
}
