package ink.wgink.login.base.controller.route;

import ink.wgink.common.component.SecurityComponent;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.interfaces.menu.IMenuBaseService;
import ink.wgink.interfaces.role.IRoleMenuBaseService;
import ink.wgink.login.base.consts.IUserCenterConst;
import ink.wgink.login.base.manager.ConfigManager;
import ink.wgink.login.base.util.MenuUtil;
import ink.wgink.pojo.bos.UserInfoBO;
import ink.wgink.pojo.dtos.menu.MenuDTO;
import ink.wgink.pojo.dtos.role.RoleSimpleDTO;
import ink.wgink.properties.ServerProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: IndexRouteController
 * @Description: index
 * @Author: wanggeng
 * @Date: 2021/2/27 3:38 下午
 * @Version: 1.0
 */
@Controller
public class IndexRouteController {
    private static final String SYSTEM_HOME_SPLIT = "__";

    @Autowired
    private SecurityComponent securityComponent;
    @Autowired
    private ServerProperties serverProperties;
    @Autowired(required = false)
    private IMenuBaseService menuBaseService;
    @Autowired(required = false)
    private IRoleMenuBaseService roleMenuBaseService;

    @GetMapping("index")
    public ModelAndView goIndex() {
        if (!StringUtils.isBlank(serverProperties.getDefaultIndexPage())) {
            return new ModelAndView("forward:/" + serverProperties.getDefaultIndexPage());
        }
        return new ModelAndView("forward:/default-main");
    }

    /**
     * 默认主页
     *
     * @return
     */
    @GetMapping("default-main")
    public ModelAndView defaultMain() {
        return defaultMain(IMenuBaseService.MENU_UNIFIED_USER + SYSTEM_HOME_SPLIT + "default-home");
    }


    @GetMapping("default-main/{menuIdAndDefaultHome}")
    public ModelAndView defaultMain(@PathVariable("menuIdAndDefaultHome") String menuIdAndDefaultHome) {
        ModelAndView mv = new ModelAndView("default-main");
        UserInfoBO userInfoBO = securityComponent.getCurrentUser();
        mv.addObject("userName", userInfoBO.getUserName());
        Map<String, String> config = ConfigManager.getInstance().getConfig();
        // 先加载系统短标题，没有加载主标题，没有加载配置文件系统标题
        if (!StringUtils.isBlank(config.get(IUserCenterConst.SYSTEM_SHORT_TITLE))) {
            mv.addObject(IUserCenterConst.SYSTEM_SHORT_TITLE, config.get(IUserCenterConst.SYSTEM_SHORT_TITLE));
        } else if (!StringUtils.isBlank(config.get(IUserCenterConst.SYSTEM_TITLE))) {
            mv.addObject(IUserCenterConst.SYSTEM_SHORT_TITLE, config.get(IUserCenterConst.SYSTEM_TITLE));
        } else {
            mv.addObject(IUserCenterConst.SYSTEM_SHORT_TITLE, serverProperties.getSystemTitle());
        }
        // 系统短LOGO
        if (!StringUtils.isBlank(config.get(IUserCenterConst.SYSTEM_SHORT_LOGO))) {
            mv.addObject(IUserCenterConst.SYSTEM_SHORT_LOGO, config.get(IUserCenterConst.SYSTEM_SHORT_LOGO));
        } else {
            mv.addObject(IUserCenterConst.SYSTEM_SHORT_LOGO, "");
        }
        mv.addObject("ws", serverProperties.getWs());
        // 菜单模式
        if (!StringUtils.isBlank(config.get(IUserCenterConst.MENU_MODE))) {
            mv.addObject(IUserCenterConst.MENU_MODE, config.get(IUserCenterConst.MENU_MODE));
        }

        // 得到根节点菜单ID与默认home页面
        String[] menuIdAndDefaultHomeArray = menuIdAndDefaultHome.split(SYSTEM_HOME_SPLIT);
        String rootMenuId = menuIdAndDefaultHomeArray[0];

        // 处理系统菜单
        if (menuBaseService != null) {
            // 查询所有系统菜单
            List<MenuDTO> systemsRootMenus = menuBaseService.listByParentId("0");
            List<MenuDTO> menus;
            if (securityComponent.isAdmin()) {
                // 管理员
                List<String> menuIds = roleMenuBaseService.listMenuId(ISystemConstant.ADMIN);
                if (menuIds.isEmpty()) {
                    menus = menuBaseService.listSystemMenu(rootMenuId);
                    // 移除菜单中的第一个斜杠，保证跳转正常
                    systemsRootMenus = MenuUtil.listSystems(systemsRootMenus);
                } else {
                    menus = menuBaseService.listSystemMenu(rootMenuId, menuIds);
                    systemsRootMenus = MenuUtil.listSystems(systemsRootMenus, menuIds);
                }
            } else {
                // 普通用户
                List<RoleSimpleDTO> roleSimpleDTOs = securityComponent.getCurrentUser().getRoles();
                if (roleSimpleDTOs.isEmpty()) {
                    menus = new ArrayList<>();
                } else {
                    List<String> roleIds = new ArrayList<>();
                    for (RoleSimpleDTO roleSimpleDTO : roleSimpleDTOs) {
                        roleIds.add(roleSimpleDTO.getRoleId());
                    }
                    List<String> menuIds = roleMenuBaseService.listMenuId(roleIds);
                    menus = menuBaseService.listSystemMenu(rootMenuId, menuIds);
                    // 去除多余的系统
                    systemsRootMenus = MenuUtil.listSystems(systemsRootMenus, menuIds);
                }
            }
            mv.addObject("menus", menus);
            mv.addObject("systems", systemsRootMenus.isEmpty() ? null : systemsRootMenus);
        }

        // 默认home页面
        String defaultHome = "default-home";
        // 含有系统首页分隔符，并且有内容
        if (menuIdAndDefaultHomeArray.length > 1) {
            String systemHomeUrl = menuIdAndDefaultHomeArray[1];
            if (!StringUtils.isBlank(systemHomeUrl)) {
                defaultHome = systemHomeUrl;
            }
        }
        mv.addObject("defaultHome", defaultHome);
        return mv;
    }

    /**
     * 默认导航首页
     *
     * @return
     */
    @GetMapping("default-home")
    public ModelAndView defaultHome() {
        ModelAndView mv;
        if (!StringUtils.isBlank(serverProperties.getDefaultHomePage())) {
            mv = new ModelAndView("forward:/" + serverProperties.getDefaultHomePage());
        } else {
            mv = new ModelAndView("default-home");
        }
        return mv;
    }

}
