package api_module_service

import (
	"bwallet/models"
	"bwallet/pkg/gredis"
	"encoding/json"
)

type ApiModule struct {
	Id       int
	Path     string
	Method   string
	Module   string
	ParentId int

	Child []*ApiModule `json:"child,omitempty"`
}

func (a *ApiModule) GetAll() ([]*models.ApiModule, error) {
	var modules []*models.ApiModule

	modules, err := models.GetModules(a.getMaps())
	if err != nil {
		return nil, err
	}

	data := buildData(modules)
	result := makeTreeCore(0, data)

	return result, nil
}

func (a *ApiModule) GetMenu() []*models.Menu {
	menu_cache, _ := gredis.Get("api_menu", 1)
	if menu_cache != nil {
		var menu []*models.Menu
		err := json.Unmarshal([]byte(menu_cache), &menu)
		if err != nil {

		}
		return menu
	}
	menu := models.GetMenu(a.getMaps())
	gredis.Set("api_menu", menu, 3600, 1)
	return menu
}

func (a *ApiModule) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if a.ParentId != 0 {
		maps["id"] = a.Id
	}

	return maps
}

func buildData(list []*models.ApiModule) map[int]map[int]*models.ApiModule {
	var data = make(map[int]map[int]*models.ApiModule)
	for _, v := range list {
		id := v.ID
		fid := v.ParentId
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int]*models.ApiModule)
		}
		data[fid][id] = v
	}
	return data
}

func makeTreeCore(index int, data map[int]map[int]*models.ApiModule) []*models.ApiModule {
	tmp := make([]*models.ApiModule, 0)
	for id, item := range data[index] {
		if data[id] != nil {
			item.Child = makeTreeCore(id, data)
		}
		tmp = append(tmp, item)
	}
	return tmp
}
