package com.sysu.admin.support.system.menu;

import com.google.common.collect.Lists;
import com.sysu.admin.support.tree.MenuTree;
import com.sysu.admin.support.tree.NavigTree;
import com.sysu.admin.support.system.menu.SMenuResBO.MenuBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;

/**
 * @title MenuService
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:03:38
 */
@Service
public class SMenuService {

    @Autowired
    SMenuRepository mMenuRepository;

    /**
     * 查询MenuList
     *
     * @return
     */
    public List<MenuBO> getMenuList() {
        List<MenuBO> menus = Lists.newArrayList();
        List<SMenu> lists = mMenuRepository.getMenuList();
        for (SMenu menu : lists) {
            menus.add(
                    MenuBO.builder().id(menu.getId())
                        .name(menu.getName())
                        .menuIcon(menu.getIcon())
                        .menuUrl(menu.getHref())
                        .authority(menu.getPermission())
                        .orderNumber(menu.getSort())
                        .parent(menu.getParent())
                        .checked(0)
                        .isMenu(menu.getIsMenu())
                        .open(menu.getIsOpen() == 1).build()
            );
        }
        return menus;
    }

    /**
     * 查询MenuTree
     *
     * @return
     */
    public List<MenuTree> getMenuTree() {
        List<SMenu> list = mMenuRepository.getMenuList();
        List<MenuTree> trees = Lists.newArrayList();
        for (SMenu p : list) {
            trees.add(
                    MenuTree.builder().id(p.getId())
                    .name(p.getName())
                    .value(String.valueOf(p.getId()))
                    .disabled(false)
                    .selected(false)
                    .parent(p.getParent())
                    .sort(p.getSort())
                    .build()
            );
        }
        return SMenuTreeHelper.getMenuTree(trees);
    }

    /**
     * 查询NavigTree
     *
     * @return
     */
    public List<NavigTree> getNavigTree(String[] permissions) {
        Arrays.sort(permissions);
        List<SMenu> list = mMenuRepository.getNavigList();
        List<NavigTree> trees = Lists.newArrayList();
        for (SMenu p : list) {
            int index = Arrays.binarySearch(permissions, p.getPermission());
            if (index > -1) {
                trees.add(NavigTree.builder().id(p.getId())
                        .title(p.getName())
                        .icon(p.getIcon())
                        .href(p.getHref())
                        .spread(p.getIsOpen() == 1)
                        .parent(p.getParent())
                        .sort(p.getSort()).build());
            }
        }
        return SMenuTreeHelper.getNavigTree(trees);
    }
}
