package com.bonus.system.controller;

import java.util.List;

import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.InnerAuth;
import com.bonus.common.security.annotation.RequiresPermissionsOrInnerAuth;
import com.bonus.system.api.domain.SysDept;
import com.bonus.system.api.domain.SysMenu;
import com.bonus.system.domain.UserMenuParams;
import com.bonus.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bonus.common.core.constant.UserConstants;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.service.ISysMenuService;

/**
 * 菜单信息
 * 
 * @author bonus
 */
@RestController
@RequestMapping("/menu")
@Slf4j
public class SysMenuController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取当前用户的菜单列表
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:menu:list"))
    @GetMapping("/list")
    @SysLog(title = "菜单管理", businessType = OperaType.QUERY,logType = 0,module = "系统管理->菜单管理")
    public AjaxResult list(SysMenu menu) {
        try{
            Long userId = SecurityUtils.getUserId();
            List<SysMenu> menus = menuService.selectMenuList(menu, userId);
            return success(menus);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:menu:query"))
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        try{
            return success(menuService.selectMenuById(menuId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");

    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu) {
        try{
            Long userId = SecurityUtils.getUserId();
            List<SysMenu> menus = menuService.selectMenuList(menu, userId);
            return success(menuService.buildMenuTreeSelect(menus));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");


    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        try{
            Long userId = SecurityUtils.getUserId();
            List<SysMenu> menus = menuService.selectMenuList(userId);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
            ajax.put("menus", menuService.buildMenuTreeSelect(menus));
            return ajax;
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");


    }

    /**
     * 新增菜单
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:menu:add"))
    @PostMapping
    @SysLog(title = "菜单管理", businessType = OperaType.INSERT,logType = 0,module = "系统管理->菜单管理")
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        try{
            if (!menuService.checkMenuNameUnique(menu)) {
                return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
            } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
                return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
            }
            menu.setCreateBy(SecurityUtils.getUsername());
            return toAjax(menuService.insertMenu(menu));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 修改菜单
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:menu:edit"))
   @PostMapping("/edit")
    @SysLog(title = "菜单管理", businessType = OperaType.UPDATE,logType = 0,module = "系统管理->菜单管理")
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        try{
            if (!menuService.checkMenuNameUnique(menu)) {
                return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
            } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
                return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
            } else if (menu.getMenuId().equals(menu.getParentId())) {
                return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
            }
            menu.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(menuService.updateMenu(menu));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 删除菜单
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:menu:remove"))
    @PostMapping("/delete/{menuId}")
    @SysLog(title = "菜单管理", businessType = OperaType.DELETE,logType = 0,module = "系统管理->菜单管理")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        try{
            if (menuService.hasChildByMenuId(menuId)) {
                return warn("存在子菜单,不允许删除");
            }
            if (menuService.checkMenuExistRole(menuId)) {
                return warn("菜单已分配,不允许删除");
            }
            return toAjax(menuService.deleteMenuById(menuId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 查询当前登录用户的菜单树信息
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        try{
            Long userId = SecurityUtils.getUserId();
            List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
            return success(menuService.buildMenus(menus));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 查询当前登录用户 指定系统类型（大屏，后台或APP）的 菜单树信息
     * @return 路由信息
     */
    @GetMapping("getRouters/{systemType}")
    public AjaxResult getRoutersBySystemType(@PathVariable("systemType")Long systemType) {
        try{

            Long userId = SecurityUtils.getUserId();
            SysDept sysDept = deptService.selectDeptById(SecurityUtils.getLoginUser().getSysUser().getDeptId());
            UserMenuParams userMenuParams = new UserMenuParams(userId, systemType, sysDept.getMenuTemplateId());
            List<SysMenu> menus = menuService.selectMenuTreeByUserIdAndSystemType(userMenuParams);
            return success(menuService.buildMenus(menus));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }
}