package yangtz.cs.liu.campus.controller.common;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.domain.menuFunction.MenuFunction;
import yangtz.cs.liu.campus.service.menuFunction.IMenuFunctionService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页功能菜单
 */
@RestController
@RequestMapping("/menu/function")
public class MenuFunctionController extends BaseController {

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private IMenuFunctionService menuFunctionService;


    /**
     * 拿到用户对应的菜单列表，只查菜单
     *
     * @return
     */
    @GetMapping("/getMenuList")
    public TableDataInfo getMenuList() {
        List<SysMenu> menus = sysMenuService.selectMenuList(getUserId());  //查出用户所拥有的功能菜单（未构建树形）
        List<TreeSelect> treeSelectList = sysMenuService.buildMenuTreeSelect(menus);
        return getDataTable(treeSelectList);
    }

    /**
     * 根据用户id获取授权菜单
     */
    @GetMapping("/authMenu")
    public AjaxResult authMenu()
    {
        AjaxResult ajax = AjaxResult.success();
        //该用户所能看到的所有可用菜单
        List<SysMenu> menus = sysMenuService.selectMenus(getUserId());
        //用户已选择展示到首页的菜单
        List<MenuFunction> userMenu = menuFunctionService.getMenuByUserId(getUserId());
        ajax.put("userMenu", userMenu);
        ajax.put("menus", menus);
        return ajax;
    }

    /**
     * 点击首页查询时出现
     */
    @GetMapping("/list")
    public AjaxResult list() {
        return AjaxResult.success(menuFunctionService.queryList());
    }

    /**
     *
     * @param menus 查询出来得菜单功能对象集合
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public AjaxResult insertMenuFunction(@RequestBody List<SysMenu> menus){
        return toAjax(menuFunctionService.insertMenuFunction(getUserId(),menus));
    }

}
