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"
)

// SysPostMenu 岗位-菜单权限关联表
type SysPostMenu struct {
	model2.Model
	PostId int `json:"postId" gorm:"index;comment:岗位ID"`
	MenuId int `json:"menuId" gorm:"index;comment:菜单ID"`
	model2.ControlBy
	model2.ModelTime
}

func (SysPostMenu) TableName() string {
	return "sys_post_menu"
}

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

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

// GetPostMenuCacheKey 获取岗位菜单缓存key
func GetPostMenuCacheKey(postId int) string {
	return "post_menu-" + string(rune(postId))
}

// DeleteAllPostMenuCache 菜单变更时删除所有岗位菜单缓存
func DeleteAllPostMenuCache() error {
	db := sdk.Runtime.GetDbByKey(config.ApplicationConfig.Host)
	if db == nil {
		return errors.New("db not exist")
	}
	var list []SysPost
	err := db.Model(SysPost{}).Find(&list).Error
	if err != nil {
		return err
	}
	for _, post := range list {
		_ = sdk.Runtime.GetCacheAdapter().Del(GetPostMenuCacheKey(post.Id))
	}
	return nil
}

// DeletePostMenuCache 删除单个岗位菜单缓存
func DeletePostMenuCache(postId int) error {
	return sdk.Runtime.GetCacheAdapter().Del(GetPostMenuCacheKey(postId))
}

// SetPostMenuCache 设置岗位菜单缓存
func SetPostMenuCache(postId int, menuList []SysMenu) error {
	s, err := json.Marshal(menuList)
	if err != nil {
		return err
	}
	return sdk.Runtime.GetCacheAdapter().Set(GetPostMenuCacheKey(postId), s, 24*60*60)
}

// GetPostMenuCache 获取岗位菜单缓存
func GetPostMenuCache(postId int, menuList *[]SysMenu) error {
	s, err := sdk.Runtime.GetCacheAdapter().Get(GetPostMenuCacheKey(postId))
	if err != nil {
		return err
	}
	return json.Unmarshal([]byte(s), &menuList)
}
