package com.manage.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.manage.annotation.RequiresPermissions;
import com.manage.dao.Power_MenuMapper;
import com.manage.entity.Power_Menu;
import com.manage.service.cache.CacheManager;
import com.manage.service.PowerService;
import com.manage.service.Power_MenuService;
import com.manage.util.ExceptionPrintUtil;
import com.manage.util.Msg;
import com.manage.vo.Power_Sys_DictVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("menu/")
public class Power_MenuManageController {
    @Autowired
    Power_MenuService menuService;
    @Autowired
    PowerService powerService;
    @Autowired
    Power_MenuMapper powerMenuMapper;

    @RequiresPermissions(value="/menu/pageUI")
    @RequestMapping("pageUI")
    public String getinmenuListfoById(Model model){
        return "menu/menuList";
    }
    @RequestMapping(value="loadSys",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String loadSys(){
        try {
            List<Power_Sys_DictVo> dicts = powerService.selectAllSys();
            CacheManager.addExcCount("noExc");
            return JSON.toJSONString(dicts);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequiresPermissions(value="/menu/pageUI")
    @RequestMapping(value = "getMenuList",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getMenuList(){
        try {
            List<Power_Menu> menus =  new ArrayList<>();
            Power_Menu menu = new Power_Menu();
            menu.setMenuId(0);
            menu.setMenuName("菜单列表");
            menus.add(menu);
            List<Power_Menu> menus1 = menuService.selectAll(null,null,null);
            menus.addAll(menus1);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(menus);
            CacheManager.addExcCount("noExc");
            return json;
        }catch(Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "checkMenuName")
    @ResponseBody
    public Msg checkMenuName(String sysFlag,String menuName) throws Exception{
        List<Power_Menu> menus = menuService.checkMenuNameBySysId(sysFlag,menuName);
        CacheManager.addExcCount("noExc");
        if(null != menus && !menus.isEmpty()){
            return Msg.fail();
        }else{
            return Msg.success();
        }
    }

    @RequestMapping(value = "checkMethodName")
    @ResponseBody
    public Msg checkMethodName(Integer parentId,String methodName,String method) throws Exception{
        List<Power_Menu> menus = new ArrayList<>();
        if(StringUtils.isNotBlank(method)){
            menus =  menuService.checkMethodByParentId(parentId, null,method);
        }else{
            menus = menuService.checkMethodByParentId(parentId, methodName,null);
        }
        CacheManager.addExcCount("noExc");
        if(null != menus && !menus.isEmpty()){
            return Msg.fail();
        }else{
            return Msg.success();
        }
    }


    @RequiresPermissions(value="/menu/update")
    @RequestMapping(value="update",method = RequestMethod.POST)
    @ResponseBody
    public Msg addMenu(Power_Menu menu,String sysName) throws Exception{
        if(StringUtils.isNotBlank(menu.getMenuUrl())){
            if(!menu.getMenuUrl().contains("/") && !"#".equals(menu.getMenuUrl())){
                return Msg.fail("菜单地址必须包含斜杠/,建目录必须为单个字符#");
            }
        }
        List<Power_Menu> menus = new ArrayList<>();
        if(StringUtils.isNotBlank(menu.getSysFlag())){
            menus = menuService.checkMenuNameBySysId(menu.getSysFlag(), menu.getMenuName());
        }
        if(menu.getMenuId() == null){
            if(StringUtils.isNoneBlank(menu.getMethod())) {
                Integer parentId = menu.getParentId();
                Power_Menu parentMenu = powerMenuMapper.selectByPrimaryKey(parentId);
                String menuUrl = parentMenu.getMenuUrl();
                if (StringUtils.isNoneBlank(menuUrl) && menuUrl.contains("/")) {
                    String methodUrl = "";
                    // /user /user/pageUI user/pageUI ../user/pageUI
                    String str1 = "";
                    String str = menuUrl.substring(0, 1);
                    if(menuUrl.length() >= 3){
                        str1 = menuUrl.substring(0, 3);
                    }
                    if("/".equals(str)){
                        menuUrl = menuUrl.substring(1,menuUrl.length());
                        if(StringUtils.isNotBlank(menuUrl)){
                            String[] menuss = menuUrl.split("/");
                            methodUrl = "/" + menuss[0] + "/" + menu.getMethod();
                        }else{
                            methodUrl = "/"  + menu.getMethod();
                        }
                    }else if(StringUtils.isNotBlank(str1) && "../".equals(str1)){
                        menuUrl = menuUrl.substring(3,menuUrl.length());
                        if(StringUtils.isNotBlank(menuUrl)){
                            String[] menuss = menuUrl.split("/");
                            methodUrl = "../" + menuss[0] + "/" + menu.getMethod();
                        }else{
                            methodUrl = "../" + menu.getMethod();
                        }
                    }else{
                        String[] menuss = menuUrl.split("/");
                        methodUrl = menuss[0] + "/" + menu.getMethod();
                    }
                    menu.setMenuUrl(methodUrl);
                }else{
                    return Msg.fail("父级菜单url地址格式不正确,正确示例：/user或/user/pageUI!");
                }
                List<Power_Menu> checkMethodNames = menuService.checkMethodByParentId(menu.getParentId(), menu.getMenuName(),null);
                List<Power_Menu> checkMethods = menuService.checkMethodByParentId(menu.getParentId(),null,menu.getMethod());
                if(null != checkMethodNames && !checkMethodNames.isEmpty()){
                    return Msg.fail("功能名称不能重复!");
                }
                if(null != checkMethods && !checkMethods.isEmpty()){
                    return Msg.fail("功能方法已存在!");
                }
            }else{
                if(null != menus && !menus.isEmpty()){
                    return Msg.fail("菜单名不能重复!");
                }
            }
            menuService.addMenu(menu,sysName);
        }else{
            if(StringUtils.isNoneBlank(menu.getMethod())) {
                Integer parentId = menu.getParentId();
                Power_Menu parentMenu = powerMenuMapper.selectByPrimaryKey(parentId);
                String menuUrl = parentMenu.getMenuUrl();
                if (StringUtils.isNoneBlank(menuUrl) && menuUrl.contains("/")) {
                    String methodUrl = "";
                    // /user /user/pageUI user/pageUI ../user/pageUI
                    String str1 = "";
                    String str = menuUrl.substring(0, 1);
                    if(menuUrl.length() >= 3){
                        str1 = menuUrl.substring(0, 3);
                    }
                    if("/".equals(str)){
                        menuUrl = menuUrl.substring(1,menuUrl.length());
                        if(StringUtils.isNotBlank(menuUrl)){
                            String[] menuss = menuUrl.split("/");
                            methodUrl = "/" + menuss[0] + "/" + menu.getMethod();
                        }else{
                            methodUrl = "/"  + menu.getMethod();
                        }
                    }else if(StringUtils.isNotBlank(str1) && "../".equals(str1)){
                        menuUrl = menuUrl.substring(3,menuUrl.length());
                        if(StringUtils.isNotBlank(menuUrl)){
                            String[] menuss = menuUrl.split("/");
                            methodUrl = "../" + menuss[0] + "/" + menu.getMethod();
                        }else{
                            methodUrl = "../" + menu.getMethod();
                        }
                    }else{
                        String[] menuss = menuUrl.split("/");
                        methodUrl = menuss[0] + "/" + menu.getMethod();
                    }
                    menu.setMenuUrl(methodUrl);
                }else{
                    return Msg.fail("父级菜单url地址格式不正确,正确示例：/user或/user/pageUI!");
                }
                List<Power_Menu> checkMethodNames = menuService.checkMethodByParentId(menu.getParentId(), menu.getMenuName(),null);
                List<Power_Menu> checkMethods = menuService.checkMethodByParentId(menu.getParentId(),null,menu.getMethod());
                if(null != checkMethodNames && !checkMethodNames.isEmpty() && !checkMethodNames.get(0).getMenuId().equals(menu.getMenuId())){
                    return Msg.fail("方法名不能重复!");
                }
                if(null != checkMethods && !checkMethods.isEmpty() && !checkMethods.get(0).getMenuId().equals(menu.getMenuId())){
                    return Msg.fail("功能方法已存在!");
                }
            }else{
                if(null != menus && !menus.isEmpty() && !menus.get(0).getMenuId().equals(menu.getMenuId())){
                    return Msg.fail("菜单名不能重复!");
                }
            }
            menuService.updateMenu(menu,sysName);
        }
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }

    @RequiresPermissions(value="/menu/delete")
    @RequestMapping("delete/{menuId}")
    @ResponseBody
    public Msg delMenu(@PathVariable("menuId")Integer menuId) throws Exception{
        menuService.deleteMenuByMenuId(menuId);
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }
}
