package model

import (
	model2 "cold-delivery/common/model"
	"encoding/json"
	"errors"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
)

type SysRoleMenu struct {
	model2.Model
	RoleKey string `json:"roleKey" gorm:"size:128;comment:角色编码"` // 角色编码
	MenuId  int    `json:"menuId" gorm:"size:128;comment:菜单id"`  // 菜单id
	model2.ControlBy
	model2.ModelTime
}

func (SysRoleMenu) TableName() string {
	return "sys_role_menu"
}

func (e *SysRoleMenu) Generate() model2.ActiveRecord {
	o := *e
	return &o
}

func (e *SysRoleMenu) GetId() interface{} {
	return e.Id
}

func GetRoleMenuCacheKey(roleKey string) string {
	return "role_menu-" + roleKey
}

// 添加、修改、删除菜单时删除角色菜单缓存
func DeleteAllRoleMenuCache() error {
	//准备db
	db := sdk.Runtime.GetDbByKey(config.ApplicationConfig.Host)
	if db == nil {
		return errors.New("db not exist")
	}
	var list []SysRole
	err := db.Model(SysRole{}).Find(&list).Error
	if err != nil {
		return err
	}
	for _, role := range list {
		_ = sdk.Runtime.GetCacheAdapter().Del(GetRoleMenuCacheKey(role.RoleKey) + "-0")
		_ = sdk.Runtime.GetCacheAdapter().Del(GetRoleMenuCacheKey(role.RoleKey) + "-1")
	}
	return nil
}

func DeleteRoleMenuCache(roleKey string) error {
	err := sdk.Runtime.GetCacheAdapter().Del(GetRoleMenuCacheKey(roleKey) + "-0")
	err = sdk.Runtime.GetCacheAdapter().Del(GetRoleMenuCacheKey(roleKey) + "-1")
	return err
}

func SetRoleMenuCache(roleKey string, menuList []SysMenu) error {
	s, err := json.Marshal(menuList)
	err = sdk.Runtime.GetCacheAdapter().Set(GetRoleMenuCacheKey(roleKey), s, 24*60*60)
	return err
}

func GetRoleMenuCache(roleKey string, menuList *[]SysMenu) error {
	s, err := sdk.Runtime.GetCacheAdapter().Get(GetRoleMenuCacheKey(roleKey))
	if err != nil {
		return err
	}
	err = json.Unmarshal([]byte(s), &menuList)
	return err
}
