package com.usky.system.controller.web;


import com.usky.common.core.util.ServletUtils;
import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.service.TokenService;
import com.usky.common.security.utils.SecurityUtils;
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.StringUtils;
import com.usky.system.domain.SysMenu;
import com.usky.system.domain.SysTenantMenu;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.model.LoginUser;
import com.usky.system.service.ISysMenuService;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.SysMenuCascadeService;
import com.usky.system.service.vo.MenuBindingsResult;
import com.usky.system.service.vo.MenuUnbindRequest;
import com.usky.system.service.vo.MenuUnbindResult;
import com.usky.system.service.vo.PlatformRouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysMenuCascadeService sysMenuCascadeService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public ApiResult list(SysMenu menu)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUserid();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return ApiResult.success(menus);
    }

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

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public ApiResult treeselect()
    {
        return ApiResult.success(menuService.selectRolePlatformMenu());
    }

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

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect1/{roleId}")
    public ApiResult roleMenuTreeselect1(@PathVariable("roleId") Long roleId)
    {
//        Long userId = SecurityUtils.getUserId();
        SysMenu menu = new SysMenu();
        List<SysMenu> menus = menuService.selectMenuListTwo(menu);
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.selectRolePlatformMenu());
        return ApiResult.success(ajax);
    }

    /**
     * 新增菜单
     */
    @Log(title = "新增-菜单", businessType = BusinessType.INSERT)
    @PostMapping
    public ApiResult add(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuPathUnique(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(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @Log(title = "修改-菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    public ApiResult edit(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuPathUnique(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 (menu.getMenuId().equals(menu.getParentId()))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @Log(title = "删除-菜单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public ApiResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }


    /**
     * 获取路由信息（应用级改造）
     *
     * @return 路由信息
     */
    @GetMapping("getRouters1")
    public ApiResult getRouters1()
    {
        List<PlatformRouterVo> list = menuService.buildPlatformMenus();
        return ApiResult.success(list);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public ApiResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();

//        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(SysUser::getDelFlag, 0).eq(SysUser::getStatus,0);
//        List<SysUser> sysUserList = userService.list(queryWrapper);
//        if (sysUserList.size()<=0){
//            throw new BusinessException("用户相关配置未完成配置，请联系管理员");
//        }
        SysUser sysUser = userService.selectUserByIdOne(userId);
        List<SysMenu> menus = new ArrayList<>();
        if ("01".equals(sysUser.getUserType())){
            menus = menuService.selectMenuTreeByUserIdOne(SecurityUtils.getTenantId());
        }else {
            menus = menuService.selectMenuTreeByUserId(userId);
        }
        return ApiResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取租户菜单关联信息列表
     */
    @GetMapping("/getTenantMenuList")
    public ApiResult getTenantMenuList()
    {
        List<SysTenantMenu> menus = menuService.selectTenantMenuList(SecurityUtils.getTenantId());

        return ApiResult.success(menus);
    }

    /**
     * 修改菜单昵称
     * @param tenantMenu
     * @return
     */
    @Log(title = "修改-菜单昵称", businessType = BusinessType.UPDATE)
    @PutMapping("/updateTenantMenu")
    public ApiResult<Void> updateTenantMenu(@RequestBody SysTenantMenu tenantMenu)
    {
        menuService.updateTenantMenu(tenantMenu);
        return ApiResult.success();
    }

    /**
     * 查询菜单关联绑定（子菜单、角色、租户、平台、帮助中心栏目）
     * <p>示例：GET /menu/bindings/1607</p>
     */
    @GetMapping("/bindings/{menuId}")
    public ApiResult<MenuBindingsResult> getBindings(@PathVariable("menuId") Long menuId)
    {
        return ApiResult.success(sysMenuCascadeService.getMenuBindings(menuId));
    }

    /**
     * 精确解绑菜单关联（不删除菜单本身）
     * <p>顺序：角色 → 租户 → 应用(平台)；必须指定要解绑的ID，禁止整菜单全量清空</p>
     * <p>示例：POST /menu/unbind</p>
     */
    @Log(title = "解绑-菜单关联", businessType = BusinessType.DELETE)
    @PostMapping("/unbind")
    public ApiResult<MenuUnbindResult> unbind(@RequestBody MenuUnbindRequest request)
    {
        return ApiResult.success(sysMenuCascadeService.unbindMenu(request));
    }
}