package com.storlead.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.system.pojo.dto.QuickMenuDTO;
import com.storlead.system.pojo.entity.MenuEntity;
import com.storlead.system.pojo.entity.QuickMenuEntity;
import com.storlead.system.pojo.vo.UserMenuVO;
import com.storlead.system.service.IMenuService;
import com.storlead.system.service.IUserRoleService;
import com.storlead.system.service.QuickMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-08 17:14
 */
@Api(tags = "平台中心 - 系统: 快捷菜单设置")
@RestController
@RequestMapping("/sys/quick/menu")
public class QuickMenuApiController {

    @Resource
    private QuickMenuService quickMenuService;

    @Resource
    private IMenuService menuService;

    @Resource
    private IUserRoleService userRoleService;

    @ApiOperation("保存角色")
    @PostMapping("/save")
    public Result create(@RequestBody QuickMenuDTO dto) {

        if (CollectionUtils.isEmpty(dto.getMenuIdls())) {
            return Result.error("参数错误");
        }
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        quickMenuService.removeByMap(Map.of("user_id",currentUserId));
        List<QuickMenuEntity> quickMenuls = new ArrayList<>();
        dto.getMenuIdls().forEach(mId -> {
            QuickMenuEntity quickMenu = new QuickMenuEntity();
            quickMenu.setMenuId(mId);
            quickMenu.setUserId(currentUserId);
            quickMenu.setRangeType(dto.getRangeType());
            quickMenuls.add(quickMenu);
        });
        quickMenuService.saveBatch(quickMenuls);
        return Result.ok();
    }

    @ApiOperation("获取权限资源")
    @PostMapping("/listMenus")
    public Result listMenus() {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        List<MenuEntity> userMenuList = menuService.getUserMenuList(currentUserId,Arrays.asList(0,1), Arrays.asList(1,2));

        LambdaQueryWrapper<MenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(MenuEntity::getMenuCode,"KJCD");
        List<MenuEntity> args = menuService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(args)) {
            userMenuList.addAll(args);
        }
        List<UserMenuVO> menuls = new ArrayList();
        userMenuList.forEach(menu -> {
            UserMenuVO menuVo = new UserMenuVO();
            BeanUtils.copyProperties(menu,menuVo);
            menuls.add(menuVo);
        });
        List<UserMenuVO>  menuRes = createTreeMenus(Long.valueOf(0),menuls);
        return Result.result(menuRes);
    }

    private List<UserMenuVO> createTreeMenus(Long pid, List<UserMenuVO> menus) {
        List<UserMenuVO> treeMenu = new ArrayList<>();
        for (UserMenuVO menu : menus) {
            if (pid.equals(menu.getPid())) {
                treeMenu.add(menu);
                List<UserMenuVO> childs =  createTreeMenus(menu.getId(), menus);
                if (childs != null && childs.size() > 0) {
                    menu.setChildren(childs);
                }
            }
        }
        return treeMenu;
    }

    @ApiOperation("查询快捷方式")
    @PostMapping("/quickMenus")
    public Result quickMenus() {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        /**
         * 根据用户id查询出当前用户的快捷菜单,并且转换成List对象集合
         */
        List<Long> alertMenuList;
        LambdaQueryWrapper<MenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(MenuEntity::getMenuCode,"KJCD");
        List<MenuEntity> args = menuService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(args)) {
            alertMenuList = args.stream().map(MenuEntity::getId).collect(Collectors.toList());
        } else {
            alertMenuList = new ArrayList<>();
        }

        List<MenuEntity> allMenuList = menuService.list();
        Map<Long, String> menuPathMap = allMenuList.stream()
                .collect(Collectors.toMap(MenuEntity::getId, MenuEntity::getPath));

        Map<Long, Long> menuPidMap = allMenuList.stream()
                .collect(Collectors.toMap(MenuEntity::getId, MenuEntity::getPid));

        List<QuickMenuEntity> quickMenuls = quickMenuService.list(new LambdaQueryWrapper<QuickMenuEntity>().eq(QuickMenuEntity::getUserId,currentUserId));
        if(!CollectionUtils.isEmpty(quickMenuls)) {
            List<Long> menuIds = quickMenuls.stream().map(QuickMenuEntity::getMenuId).collect(Collectors.toList());
            List<MenuEntity> userMenuList = menuService.list(new LambdaQueryWrapper<MenuEntity>().in(MenuEntity::getId,menuIds));
            if (!CollectionUtils.isEmpty(userMenuList)) {
                List<UserMenuVO> menuls = new ArrayList();
                List<Long> finalAlertMenuList = alertMenuList;
                userMenuList.forEach(menu -> {
                    UserMenuVO menuVo = new UserMenuVO();
                    if (finalAlertMenuList.contains(menu.getId())) {
                        menuVo.setOpenType(1);
                    } else {
                        menuVo.setOpenType(0);
                    }
                    BeanUtils.copyProperties(menu,menuVo);
                    appendMenuPath(menuVo,menuPathMap,menu.getPid(),menuPidMap);
                    menuls.add(menuVo);
                });
                return Result.result(menuls);
            }
        }
        return Result.result(null);
    }

    public void appendMenuPath(UserMenuVO menuVO,Map<Long,String> menuPathMap,Long pid,Map<Long,Long> menuPidMap) {
        if (Objects.nonNull(menuPidMap.get(pid))) {
            String appendPath = menuPathMap.get(pid);
            pid = menuPidMap.get(pid);
            String path = appendPath+"/"+menuVO.getPath();
            path = path.replaceAll("//", "/");
            menuVO.setPath(path);
            appendMenuPath(menuVO,menuPathMap,pid,menuPidMap);
        }
    }
}
