package admin_menu

import (
	"context"
	"encoding/json"

	"znc-server/app/main/api/internal/svc"
	"znc-server/app/main/api/internal/types"
	"znc-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMenuListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuListLogic {
	return &GetMenuListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetMenuListLogic) GetMenuList(req *types.GetMenuListReq) (resp []types.MenuListItem, err error) {
	// 构建查询条件
	builder := l.svcCtx.AdminMenuModel.SelectBuilder()

	// 添加筛选条件
	if len(req.Name) > 0 {
		builder = builder.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if len(req.Path) > 0 {
		builder = builder.Where("path LIKE ?", "%"+req.Path+"%")
	}
	if req.Status != -1 {
		builder = builder.Where("status = ?", req.Status)
	}
	if req.Type != "" {
		builder = builder.Where("type = ?", req.Type)
	}

	// 排序但不分页，获取所有符合条件的菜单
	builder = builder.OrderBy("sort ASC")

	// 获取所有菜单
	menus, err := l.svcCtx.AdminMenuModel.FindAll(l.ctx, builder, "id ASC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, err: %v", err)
	}

	// 将菜单按ID存入map
	menuMap := make(map[int64]types.MenuListItem)
	for _, menu := range menus {
		var meta map[string]interface{}
		err := json.Unmarshal([]byte(menu.Meta), &meta)
		if err != nil {
			logx.Errorf("解析Meta字段失败: %v", err)
			meta = make(map[string]interface{})
		}
		menuType, err := l.svcCtx.DictService.GetDictLabel(l.ctx, "admin_menu_type", menu.Type)
		if err != nil {
			logx.Errorf("获取菜单类型失败: %v", err)
			menuType = ""
		}
		item := types.MenuListItem{
			Id:         menu.Id,
			Pid:        menu.Pid,
			Name:       menu.Name,
			Path:       menu.Path,
			Component:  menu.Component,
			Redirect:   menu.Redirect.String,
			Meta:       meta,
			Status:     menu.Status,
			Type:       menuType,
			Sort:       menu.Sort,
			CreateTime: menu.CreateTime.Format("2006-01-02 15:04:05"),
			Children:   make([]types.MenuListItem, 0),
		}
		menuMap[menu.Id] = item
	}

	// 构建父子关系
	for _, menu := range menus {
		if menu.Pid > 0 {
			// 找到父菜单
			if parent, exists := menuMap[menu.Pid]; exists {
				// 添加当前菜单到父菜单的子菜单列表
				children := append(parent.Children, menuMap[menu.Id])
				parent.Children = children
				menuMap[menu.Pid] = parent
			}
		}
	}

	// 提取顶级菜单（ParentId为0）到响应列表
	result := make([]types.MenuListItem, 0)
	for _, menu := range menus {
		if menu.Pid == 0 {
			result = append(result, menuMap[menu.Id])
		}
	}

	return result, nil
}
