package com.usky.system.controller.web;


import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.constants.CommonConst;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.common.core.util.ServletUtils;
import com.usky.common.core.util.StringUtils;
import com.usky.common.security.service.TokenService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.*;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.model.LoginUser;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.SysMobileMenuService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 * 移动端_菜单权限表 前端控制器
 * </p>
 *
 * @author JCB
 * @since 2022-08-11
 */
@RestController
@RequestMapping("/sysMobileMenu")
public class SysMobileMenuController  extends BaseController {

    @Autowired
    private SysMobileMenuService sysMobileMenuService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("getRouters")
    public ApiResult getRouters()
    {
        List<SysMobileMenu> menus = sysMobileMenuService.moveRoute();
        return ApiResult.success(menus);
    }

    @GetMapping("getAppRouters")
    public ApiResult getAppRouters()
    {
        long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserByIdOne(userId);

        List<SysMobileMenu> menus = new ArrayList<>();
        Integer i = SecurityUtils.getTenantId();
        if("01".equals(sysUser.getUserType())){
            menus = sysMobileMenuService.selectMenuTreeByUserIdOne(SecurityUtils.getTenantId());
        }else{
            menus = sysMobileMenuService.selectMenuTreeByUserId(userId);
        }

        return ApiResult.success(sysMobileMenuService.buildMenus(menus));
    }

    /**
     * 获取移动端租户菜单关联信息列表
     */
    @GetMapping("/getMobileTenantMenuList")
    public ApiResult getMobileTenantMenuList()
    {
        List<SysMobileTenantMenu> menus = sysMobileMenuService.getMobileTenantMenuList(SecurityUtils.getTenantId());

        return ApiResult.success(menus);
    }

    /**
     * 修改移动端菜单昵称
     * @param mobileTenantMenu
     * @return
     */
    @PutMapping("/updateMobileTenantMenu")
    public ApiResult<Void> updateMobileTenantMenu(@RequestBody SysMobileTenantMenu mobileTenantMenu)
    {
        sysMobileMenuService.updateMobileTenantMenu(mobileTenantMenu);
        return ApiResult.success();
    }

    /**
     * 移动端系统管理-菜单管理-列表展示
     */
    @GetMapping("/list")
    public ApiResult list(SysMobileMenu menu)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserid();
        List<SysMobileMenu> menus = sysMobileMenuService.selectMobileMenuList(menu, userId);
        return ApiResult.success(menus);
    }

    /**
     * 移动端系统管理-菜单管理-根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public ApiResult getInfo(@PathVariable Long menuId)
    {
        return ApiResult.success(sysMobileMenuService.selectMenuById(menuId));
    }

    /**
     * 移动端-角色管理-添加角色获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public ApiResult treeselect()
    {
        List<SysMobileMenu> menus = sysMobileMenuService.selectMenuListTwo();
        return ApiResult.success(sysMobileMenuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public ApiResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysMobileMenu> menus = sysMobileMenuService.selectMenuListTwo();
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", sysMobileMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", sysMobileMenuService.buildMenuTreeSelect(menus));
        return ApiResult.success(ajax);
    }


    /**
     * 移动端系统管理-菜单管理-新增菜单
     */
    @PostMapping
    public ApiResult add(@Validated @RequestBody SysMobileMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysMobileMenuService.checkMenuNameUnique(menu)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), CommonConst.HTTP_PREFIX, CommonConst.HTTPS_PREFIX))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysMobileMenuService.insertMobileMenu(menu));
    }

    /**
     * 移动端系统管理-菜单管理-修改菜单
     */
    @PutMapping
    public ApiResult edit(@Validated @RequestBody SysMobileMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysMobileMenuService.checkMenuNameUnique(menu)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), CommonConst.HTTP_PREFIX, CommonConst.HTTPS_PREFIX))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (Objects.equals(menu.getMenuId(), menu.getParentId()))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysMobileMenuService.updateMenu(menu));
    }

    /**
     * 移动端系统管理-菜单管理-删除菜单
     */
    @DeleteMapping("/{menuId}")
    public ApiResult remove(@PathVariable("menuId") Long menuId)
    {
        if (sysMobileMenuService.hasChildByMenuId(menuId))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "存在子菜单,不允许删除");
        }
        if (sysMobileMenuService.checkMenuExistRole(menuId))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "菜单已分配,不允许删除");
        }
        return toAjax(sysMobileMenuService.deleteMenuById(menuId));
    }

}

