package com.org.system.controller;

import com.org.system.annotation.Log;
import com.org.system.config.validation.Update;
import com.org.system.entity.SysMenu;
import com.org.system.enums.BusinessType;
import com.org.system.service.SysMenuService;
import com.org.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("sys/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    // 新增菜单
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('sys:menu:add')")
    @Log(title = "新增系统菜单", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated SysMenu sysMenu){
        log.info("SysMenuController - add sysMenu:{}", sysMenu);

        return toAjax(sysMenuService.add(sysMenu));
    }

    // 编辑菜单
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('sys:menu:edit')")
    @Log(title = "编辑系统菜单", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody @Validated(Update.class) SysMenu sysMenu){
        log.info("SysMenuController - edit sysMenu:{}", sysMenu);

        return toAjax(sysMenuService.edit(sysMenu));
    }

    // 删除菜单
    @PostMapping("/del")
    @PreAuthorize("@ss.hasPermi('sys:menu:del')")
    @Log(title = "删除系统菜单", businessType = BusinessType.DELETE)
    public AjaxResult del(@RequestParam Long id, @RequestParam String deleteReason){
        log.info("SysMenuController - del id:{}", id);
        log.info("SysMenuController - del deleteReason:{}", deleteReason);

        return toAjax(sysMenuService.del(id, deleteReason));
    }

    // 菜单列表
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('sys:menu:list')")
    @Log(title = "查询系统菜单", businessType = BusinessType.SELECT)
    public AjaxResult menuList(SysMenu sysMenu){
        log.info("SysMenuController - list sysMenu:{}", sysMenu);

        List<SysMenu> list = sysMenuService.queryList(sysMenu);
        // 由于children属性存在，前端菜单树会加载children，故此处不处理，前端处理树结构，如果没有子节点，会删掉children属性
//        list = sysMenuService.buildMenuTree(list, 0L);

        return AjaxResult.success(list);
    }

    @GetMapping("/tree")
    @PreAuthorize("@ss.hasPermi('sys:menu:list')")
    @Log(title = "菜单树", businessType = BusinessType.SELECT)
    public AjaxResult tree(){
        List<SysMenu> menuTree = sysMenuService.tree();
        return AjaxResult.success(menuTree);
    }

    @GetMapping("/treeForGrant")
    @PreAuthorize("@ss.hasPermi('sys:menu:list')")
    @Log(title = "角色授权菜单树", businessType = BusinessType.SELECT)
    public AjaxResult treeForGrant(){
        List<SysMenu> menuTree = sysMenuService.treeForGrant();
        return AjaxResult.success(menuTree);
    }
}
