package com.bonus.system.basic.controller;

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.log.annotation.Log;
import com.bonus.common.log.enums.BusinessType;
import com.bonus.common.security.annotation.InnerAuth;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.basic.domain.SysMenu;
import com.bonus.system.basic.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 菜单信息
 * 
 * @author bonus
 */
@RestController
@RequestMapping("/menu")
@Slf4j
public class SysMenuController extends BaseController
{
    @Resource(name = "sysMenuService")
    private SysMenuService sysMenuService;

    /**
     * 获取菜单列表
     */
    @RequiresPermissions("system:menu:list")
    @GetMapping("/list")
    @Log(title = "系统管理->菜单管理", businessType = BusinessType.QUERY)
    public AjaxResult list(SysMenu menu) {
        try{
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            List<SysMenu> menus = sysMenuService.selectMenuList(menu, userId);
            return success(menus);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

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

    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu) {
        try{
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            List<SysMenu> menus = sysMenuService.selectMenuList(menu, userId);
            return success(sysMenuService.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.getLoginUser().getSysUser().getUserId();
            List<SysMenu> menus = sysMenuService.selectMenuList(userId);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("checkedKeys", sysMenuService.selectMenuListByRoleId(roleId));
            ajax.put("menus", sysMenuService.buildMenuTreeSelect(menus));
            return ajax;
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");


    }

    /**
     * 新增菜单
     */
    @RequiresPermissions("system:menu:add")
    @PostMapping
    @Log(title = "系统管理->菜单管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        try{
            if (!sysMenuService.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.getLoginUser().getSysUser().getUserName());
            return toAjax(sysMenuService.insertMenu(menu));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 修改菜单
     */
    @RequiresPermissions("system:menu:edit")
    @PutMapping
    @Log(title = "系统管理->菜单管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        try{
            if (!sysMenuService.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.getLoginUser().getSysUser().getUserName());
            return toAjax(sysMenuService.updateMenu(menu));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 删除菜单
     */
    @RequiresPermissions("system:menu:remove")
    @DeleteMapping("/{menuId}")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        try{
            if (sysMenuService.hasChildByMenuId(menuId)) {
                return warn("存在子菜单,不允许删除");
            }
            if (sysMenuService.checkMenuExistRole(menuId)) {
                return warn("菜单已分配,不允许删除");
            }
            return toAjax(sysMenuService.deleteMenuById(menuId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        try{
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
            // 去除app菜单
            menus.removeIf(menu -> Objects.equals(menu.getMenuName(),UserConstants.APP_NAME));
            return success(sysMenuService.buildMenus(menus));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取App路由信息
     *
     * @return 路由信息
     */
    @PostMapping("getAppRouters")
    @InnerAuth
    public AjaxResult getAppRouters(@RequestBody Long userId) {
        try{
            List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
            // 去除后台菜单
            menus.removeIf(menu -> !Objects.equals(menu.getMenuName(),UserConstants.APP_NAME));
            return success(sysMenuService.buildMenus(menus));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }
}