package com.chushang.system.controller;

import com.chushang.common.core.constant.Constants;
import com.chushang.common.core.util.StringUtils;
import com.chushang.common.core.web.AjaxResult;
import com.chushang.common.log.annotation.SysLog;
import com.chushang.common.log.enums.BusinessType;
import com.chushang.datascope.entity.DataScopeEntity;
import com.chushang.security.annotation.RequiresPermissions;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.dto.ListMenuDTO;
import com.chushang.system.entity.po.SysMenu;
import com.chushang.system.entity.po.SysUser;
import com.chushang.security.entity.vo.LoginUser;
import com.chushang.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author by zhaowenyuan create 2022/8/22 14:38
 * 菜单控制器
 */
@RestController
@RequestMapping(value = "/menu")
public class MenuController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @RequiresPermissions("system:menu:list")
    @GetMapping("/list")
    public AjaxResult list(ListMenuDTO listMenu)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(listMenu, userId);
        return AjaxResult.success(menus);
    }

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

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/tree/select")
    public AjaxResult treeSelect()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(new ListMenuDTO(), userId);

        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenu/tree/select/{roleId}")
    public AjaxResult roleMenuTreeSelect(@PathVariable("roleId") Long roleId)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        return AjaxResult.success()
                .add("checkedKeys", menuService.selectMenuListByRoleId(roleId))
                .add("menus", menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 新增菜单
     */
    @RequiresPermissions("system:menu:add")
    @SysLog(value = "菜单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenu menu)
    {
        if (menuService.checkMenuNameUnique(menu))
        {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        // 外链
        else if (!menu.getFrame() && ! StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());

        menuService.save(menu);

        return AjaxResult.success();
    }

    /**
     * 修改菜单
     */
    @RequiresPermissions("system:menu:edit")
    @SysLog(value = "修改菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenu menu)
    {
        if (menuService.checkMenuNameUnique(menu))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        // 外链
        else if (!menu.getFrame() && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());

        menuService.updateById(menu);
        return AjaxResult.success();
    }


    /**
     * 删除菜单
     */
    @RequiresPermissions("system:menu:remove")
    @SysLog(value = "菜单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return AjaxResult.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return AjaxResult.error("菜单已分配,不允许删除");
        }

        menuService.removeById(menuId);

        return AjaxResult.success();
    }
    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        LoginUser<SysUser, DataScopeEntity> loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(sysUser);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
