package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.kit.PropKit;
import com.model.Menu;
import com.model.RoleMenu;
import com.model.User;
import com.model.UserMenu;
import com.service.MenuService;
import com.tools.JwtUtils;

import java.util.*;

@ControllerInterface(path="/menu")
public class MenuController extends BaseController {

    MenuService service = MenuService.me;

    public void index() {
        render("/view/userrole/menu.html");
    }


    public void menurole() {
        render("/view/userrole/menurole.html");
    }

    public void findMenuByRole(){
        int roleid =getParaToInt("roleid");
        success(service.findMenuByRole(roleid));
    }

    public void findMenuByUser(){
        int userid =getParaToInt("userid");
        List<Menu> menuList=service.findMenuByUser(userid);
        List<Map<String,Object>> resutList =new ArrayList<Map<String,Object>>();
        for (Menu menu: menuList) {
            if (menu.getPid().equals(0)){
                Map<String,Object> menuMap=new LinkedHashMap<String, Object>();
                menuMap.put("id",menu.getId().toString());
                menuMap.put("pid",menu.getPid().toString());
                menuMap.put("url",menu.getUrl());
                menuMap.put("imgurl",menu.getImgurl());
                menuMap.put("menuname",menu.getMenuname());
                menuMap.put("orderno",menu.getOrderno());
                menuMap.put("submenu",buildSubMenu(menuList,menu.getId()));
                resutList.add(menuMap);
            }
        }
        success(resutList);
    }

    private List<Map<String,Object>>  buildSubMenu(List<Menu> menuList,Integer id){
        List<Map<String,Object>> submenuList = new ArrayList<Map<String,Object>>();
        for (Menu menu: menuList) {
            if (menu.getPid().equals(id)){
                if(PropKit.get("banben").equals("blue.txt") && PropKit.use("/channel/blue.txt").get("grepmenuidstr").indexOf(menu.getId()+",") > -1) {
                    continue;
                }
                Map<String,Object> menuMap=new LinkedHashMap<String, Object>();
                menuMap.put("id",menu.getId().toString());
                menuMap.put("pid",menu.getPid().toString());
                menuMap.put("url",menu.getUrl());
                menuMap.put("imgurl",menu.getImgurl());
                menuMap.put("menuname",menu.getMenuname());
                menuMap.put("menuname",menu.getMenuname());
                menuMap.put("submenu",buildSubMenu(menuList,menu.getId()));
                submenuList.add(menuMap);
            }
        }
        return submenuList;
    }

    public void findMenuByLoginUser(){
        User user= getSessionAttr("userInfo");
        int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
        if(operatorid == 0) {
            fail(3,"token错误");
            return;
        }
        success(service.findMenuByUser(user.getId()));
    }

    public void findMenuByUserID(){
        User user= getSessionAttr("userInfo");
        int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int userid =getParaToInt("userid");
        success(service.findMenuByUser(userid));
    }

    public void findMenuNoRole(){
        int roleid =getParaToInt("roleid");
        success(service.findMenuNoRole(roleid));
    }

    public void findMenu(){
        int roleid =1;
        success(service.findMenu());
    }

    public void addOrUpdate(){
        Menu bean = getBean(Menu.class,"bean");
        try {
            Menu menu=service.addOrUpdate(bean);
            success(menu);
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }

    public void deleteMenu() {
        try {
            int operatorid = 0;
            int menuid = getParaToInt("menuid");
            List<Menu> subMenuList =service.findSubMenu(menuid);
            if(subMenuList.size() >0) {
                    throw new Exception("需要先删除子菜单！");
            }
            service.delete(menuid);
            success();
        }catch(Exception e){
            fail(0,e.getMessage());
        }
    }

    public void saveUserMenu(){
        try{

            User user= getSessionAttr("userInfo");
            int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }

            int userid = getParaToInt("userid");
            String rolejson = getPara("menu");
            List<Menu> menuList=  JSON.parseArray(rolejson, Menu.class);
            List<UserMenu> userMenuList = new ArrayList<UserMenu>();
            List<Integer> menuidList = new ArrayList<Integer>();
            for (Menu menu : menuList){
                if (menuidList.contains(menu.getId())){
                    continue;
                }
                menuidList.add(menu.getId());
                //授权子菜单，将父菜单也授权
                if (!menu.getPid().equals(0) && !menuidList.contains(menu.getPid())){
                    UserMenu userMenu  =new UserMenu();
                    userMenu.setUserid(userid);
                    userMenu.setMenuid(menu.getPid());
                    userMenu.setOperatorid(operatorid);
                    userMenu.setCreatetime(new Date());
                    userMenuList.add(userMenu);
                    menuidList.add(menu.getPid());
                }
                UserMenu userMenu  =new UserMenu();
                userMenu.setUserid(userid);
                userMenu.setMenuid(menu.getId());
                userMenu.setOperatorid(operatorid);
                userMenuList.add(userMenu);
            }
            service.delUserMenu(userid);
            service.saveUserMenu(userMenuList);
            success();
        }catch (Exception e){
            e.printStackTrace();
            fail();
        }
    }

    public void saveRoleMenu(){
        try{

            User user= getSessionAttr("userInfo");
            int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }

            int roleid = getParaToInt("roleid");
            String rolejson = getPara("menu");
            List<Menu> menuList=  JSON.parseArray(rolejson, Menu.class);
            List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
            for (Menu menu : menuList){
                //授权子菜单，将父菜单也授权
                if (!menu.getPid().equals(0) &&  null ==  service.findParentMenuByRole(menu.getPid(),roleid)){
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setRoleid(roleid);
                    roleMenu.setMenuid(menu.getPid());
                    roleMenu.setOperatorid(operatorid);
                    roleMenu.setCreatetime(new Date());
                    roleMenu.save();
                }
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleid(roleid);
                roleMenu.setMenuid(menu.getId());
                roleMenu.setOperatorid(operatorid);
                roleMenuList.add(roleMenu);
            }
            service.saveRoleMenu(roleMenuList);
            success();
        }catch (Exception e){
            fail();
        }
    }

    public void deleteRoleMenu(){
        try{
            int roleid = getParaToInt("roleid");
            String rolejson = getPara("menu");
            List<Menu> menuList=  JSON.parseArray(rolejson, Menu.class);
            List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
            for (Menu menu : menuList){
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleid(roleid);
                roleMenu.setMenuid(menu.getId());
                roleMenuList.add(roleMenu);

                //删除父菜单，把子菜单一起删除
                List<Menu> subMenuList= service.findSubMenu(menu.getId());
                for (Menu subMenu : subMenuList){
                    roleMenu = new RoleMenu();
                    roleMenu.setRoleid(roleid);
                    roleMenu.setMenuid(subMenu.getId());
                    roleMenuList.add(roleMenu);
                }
            }
            service.delRoleMenu(roleMenuList);

            success();
        }catch (Exception e){
            fail();
        }

    }


    public void hasAuth(){
        String token=getPara("token");
        String url =getPara("url");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        if (!service.userHasMenuAuth(operatorid,url)){
            fail(4,"没有此功能权限！");
            return;
        }
        success();
    }


}
