package com.yunfeiyun.agmp.common.web.system.controller;

import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.web.service.ISysMenuService;
import com.yunfeiyun.agmp.common.web.system.service.ISysMenuConfigService;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.entity.SysMenu;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseMenu;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.framework.manager.RbacDictManager;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
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;

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

    @Autowired
    private ISysMenuConfigService menuConfigService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public AjaxResult list(SysMenu menu)
    {
        List<IBaseMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(String menuId)
    {
        return success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/tree")
    public AjaxResult treeselect(SysMenu menu)
    {
        List<IBaseMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/rolemenu/tree")
    public AjaxResult roleMenuTreeselect(@RequestParam("roleId") String roleId)
    {
        List<IBaseMenu> menus = menuService.selectMenuList(getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysMenu menu)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            //throw new BizException(ErrorCode.ADD_MENU_NAME_ERROR.getCode(),ErrorCode.ADD_MENU_NAME_ERROR.getMessage());
        }
        else if (UserConstants.YES_FRAME.equals(menu.getMenuOpentype()) && !StringUtils.ishttp(menu.getMenuPath()))
        {
            throw new BizException(ErrorCode.ADD_MENU_OPENTYPE_ERROR.getCode(),ErrorCode.ADD_MENU_OPENTYPE_ERROR.getMessage());
        }
        menu.setMenuVisiblestatus( UserConstants.TYPE_BUTTON.equals(menu.getMenuType()) ? UserConstants.NORMAL : menu.getMenuVisiblestatus()   );
        menu.setMenuApistatus( !UserConstants.TYPE_BUTTON.equals(menu.getMenuType()) ? UserConstants.NORMAL : menu.getMenuApistatus()   );
        menu.setMenuCreator(getUserId());
        menu.setMenuCreateddate(DateUtils.dateTimeNow());
        menu.setMenuModifier(getUserId());
        menu.setMenuModifieddate(DateUtils.dateTimeNow());
        RbacDictManager.refreshMenuCache();
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResult edit(@Validated @RequestBody SysMenu menu)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            //throw new BizException(ErrorCode.ADD_MENU_NAME_ERROR.getCode(),ErrorCode.ADD_MENU_NAME_ERROR.getMessage());
        }
        else if (UserConstants.YES_FRAME.equals(menu.getMenuOpentype()) && !StringUtils.ishttp(menu.getMenuPath()))
        {
            throw new BizException(ErrorCode.ADD_MENU_OPENTYPE_ERROR.getCode(),ErrorCode.ADD_MENU_OPENTYPE_ERROR.getMessage());
        }
        else if (menu.getMenuId().equals(menu.getMenuParentid()))
        {
            throw new BizException(ErrorCode.ADD_MENU_PARENT_ERROR.getCode(),ErrorCode.ADD_MENU_PARENT_ERROR.getMessage());
        }
        menu.setMenuModifier(getUserId());
        menu.setMenuModifieddate(DateUtils.dateTimeNow());
        RbacDictManager.refreshMenuCache();
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") String menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            throw new BizException(ErrorCode.ADD_MENU_HAVCHILD_ERROR.getCode(),ErrorCode.ADD_MENU_HAVCHILD_ERROR.getMessage());
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            throw new BizException(ErrorCode.ADD_MENU_HAVGIVE_ERROR.getCode(),ErrorCode.ADD_MENU_HAVGIVE_ERROR.getMessage());
        }
        RbacDictManager.refreshMenuCache();
        return toAjax(menuService.deleteMenuById(menuId));
    }
}