package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
	"reflect"
)

type ApiModule struct {
	Model

	Path     string `json:"path,omitempty"`
	Method   string `json:"method,omitempty"`
	Module   string `json:"module"`
	ParentId int    `json:"parent_id,omitempty"`

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

type Menu struct {
	Model

	Path     string `json:"path,omitempty"`
	Method   string `json:"method,omitempty"`
	Module   string `json:"module"`
	ParentId int    `json:"parent_id,omitempty"`

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

func (a ApiModule) TableName() string {
	return setting.DatabaseSetting.Name_Manage + ".gli_api_module"
}

func GetModules(maps interface{}) ([]*ApiModule, error) {
	var modules []*ApiModule
	err := db.Where(maps).Find(&modules).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return modules, nil
}

func GetMenu(maps interface{}) []*Menu {
	var menus []*Menu

	var res []*Menu
	db.Table(setting.DatabaseSetting.Name_Manage+".gli_api_module").Where("parent_id = ?", 0).Order("id").Find(&menus)

	if reflect.ValueOf(menus).IsValid() {
		res = tree(menus)
	}

	return res
}

func tree(menus []*Menu) []*Menu {
	var nodes []*Menu
	if reflect.ValueOf(menus).IsValid() {
		for k, v := range menus {
			db.Table(setting.DatabaseSetting.Name_Manage+".gli_api_module").Where("parent_id= ?", v.ID).Order("id").Find(&nodes)
			for kk, _ := range nodes {
				menus[k].Child = append(menus[k].Child, nodes[kk])
			}
			tree(nodes)
		}
	}
	return menus
}
