package com.unis.crk.basic.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unis.crk.basic.entity.*;
import com.unis.crk.basic.entity.vo.RoleButtonVo;
import com.unis.crk.basic.entity.vo.RoleFuncVo;
import com.unis.crk.basic.entity.vo.UserInfoVo;
import com.unis.crk.basic.service.IFuncInfoService;
import com.unis.crk.basic.service.IRoleButtonService;
import com.unis.crk.basic.service.IRoleFuncService;
import com.unis.crk.basic.service.IUserRoleService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unis.crk.utils.ResultUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 角色权限表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Api(value = "角色权限表",tags = {"角色权限表"})
@RestController
@RequestMapping("roleFunc")
@CrossOrigin
public class RoleFuncController {

    private final static Logger LOGGER = LoggerFactory.getLogger(RoleFuncController.class);
    @Autowired
    private IRoleButtonService roleButtonService;
    @Autowired
    private IFuncInfoService funcInfoService;
    @Autowired
    private IRoleFuncService roleFuncService;
    @Autowired
    private IUserRoleService userRoleService;
    /**
     * 获取当前用户所有功能权限
     * @param userId
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="根据登录用户ID获取角色下功能菜单")
    @GetMapping("getFuncByUserId/{UserId}")
    public List<FuncInfo> getFuncByUserId(@PathVariable("UserId") String userId) {
        List<FuncInfo> funclist1 = new ArrayList<>();
        //根节点
        List<FuncInfo> rootMenu = new ArrayList<FuncInfo>();
//                if (UserId != null) {
                if (StrUtil.isNotBlank(userId)) {
                   /* List<UserRole> urList = userRoleService.getUserRole(userId);
                    if (urList.size() > 0) {
                        for (UserRole userRole : urList) {
                            List<FuncInfo> funcInfoByRoleId = funcInfoService.getFuncInfoByRoleId(userRole.getRoleId());
                            funclist1.addAll(funcInfoByRoleId);
                        }

                    }*/
                    List<FuncInfo> funcInfoByRoleId = funcInfoService.getFuncInfoByUserId(userId,"0");
                    funclist1.addAll(funcInfoByRoleId);
                }else{
                    funclist1 =funcInfoService.list();
                }

        List<FuncInfo> funclist = new ArrayList<>(new HashSet<>(funclist1));//多次保存去重
        for(Iterator<FuncInfo> it=funclist.iterator(); it.hasNext();){
            FuncInfo nav = it.next();
            if(nav !=null){
                if (StringUtils.isEmpty(nav.getParentId())||nav.getParentId().equals("0")) {//父节点是0的，为根节点。
                    rootMenu.add(nav);
                }
            }else{
                it.remove();
            }
        }
            /* 根据Menu类的order排序 */
            Collections.sort(rootMenu, order());
            for (FuncInfo nav : rootMenu) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<FuncInfo> childList = getChild(nav.getFuncId(), funclist);
                nav.setChildren(childList);//给根节点设置子节点
            }

        return rootMenu;

    }
    /**
     * 获取当前用户所有功能权限
     * @param userId
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="根据登录用户ID获取角色下功能菜单")
    @GetMapping("getAppFuncByUserId/{UserId}")
    public List<FuncInfo> getAppFuncByUserId(@PathVariable("UserId") String userId) {
        //根节点
        List<FuncInfo> rootMenu = new ArrayList<>();
                if (StrUtil.isNotBlank(userId)) {
                    rootMenu = funcInfoService.getFuncInfoByUserId(userId,"1");
                }

        return rootMenu;

    }
    /**
     * 获取所有功能
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="获取所有功能列表")
    @GetMapping("getAllFunc")
    public List<FuncInfo> getAllFunc() {
        List<FuncInfo> funclist1 = new ArrayList<>();
        //根节点
        List<FuncInfo> rootMenu = new ArrayList<FuncInfo>();
            funclist1 =funcInfoService.getAllFuncInfo();
        for(Iterator<FuncInfo> it=funclist1.iterator(); it.hasNext();){
            FuncInfo nav = it.next();
            if(nav !=null){
//                if (nav.getParentId()==0) {//父节点是0的，为根节点。
                //父节点是0的，为根节点。
                if (StringUtils.isEmpty(nav.getParentId())|| nav.getParentId().equals("0")) {
                    rootMenu.add(nav);
                }
            }else{
                it.remove();
            }
        }

        /* 根据Menu类的order排序 */
        Collections.sort(rootMenu, order());
        for (FuncInfo nav : rootMenu) {
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<FuncInfo> childList = getChild(nav.getFuncId(), funclist1);
            nav.setChildren(childList);//给根节点设置子节点
        }

        return rootMenu;

    }


    /**
     * 获取子节点
     *
     * @param id      父节点id
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    public List<FuncInfo> getChild(String id, List<FuncInfo> allMenu) {
        //子菜单
        List<FuncInfo> childList = new ArrayList<FuncInfo>();
        for (FuncInfo nav : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                childList.add(nav);
            }
        }
        //递归
        for (FuncInfo nav : childList) {
            nav.setChildren(getChild(nav.getFuncId(), allMenu));
        }
        Collections.sort(childList, order());//排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<FuncInfo>();
        }
        return childList;
    }

    /*
     * 排序,根据order排序
     */
    public Comparator<FuncInfo> order() {
        Comparator<FuncInfo> comparator = new Comparator<FuncInfo>() {
            @Override
            public int compare(FuncInfo o1, FuncInfo o2) {
                if(o1.getFuncSort() != null && o2.getFuncSort() !=null){
                if (o1.getFuncSort() != o2.getFuncSort()) {
                    return o1.getFuncSort() - o2.getFuncSort();
                }
                }
                return 0;
            }
        };
        return comparator;
    }

    /**
     * 保存角色功能权限
     * @param roleFuncVo	角色编号
     * @return
     */
    @ApiOperation(value="保存", notes="传入角色ID和功能编号(功能编号以逗号隔开)")
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public Map<String, Object> saveRoleAndFunc(@RequestBody RoleFuncVo roleFuncVo) {
       String funcIds= roleFuncVo.getFuncIds();
        String[] funcIdList = funcIds.split(",");
        roleFuncService.saveRoleAndFunc(roleFuncVo.getRoleId(), funcIdList);
        return new HashMap<String, Object>();
    }

    /**
     * 保存角色功能按钮权限
     * @param roleFuncVo	角色编号
     * @return
     */
    @ApiOperation(value="保存", notes="传入角色ID和功能编号(功能编号以逗号隔开)和按钮编号(按钮编号以逗号隔开)")
    @RequestMapping(value="/saveRoleAndFuncAndButton", method = RequestMethod.POST)
    public ResultUtil saveRoleAndFuncAndButton(@RequestBody RoleFuncVo roleFuncVo) {
        ResultUtil<Boolean> data = new ResultUtil<>();
        String funcIds= roleFuncVo.getFuncIds();
        String[] funcIdList = funcIds.split(",");
        Boolean aBoolean = roleFuncService.saveRoleAndFunc(roleFuncVo.getRoleId(), funcIdList);
        String btnIds = roleFuncVo.getBtnIds();
        String[] btnIdList = btnIds.split(",");
        Boolean aBoolean1 = roleButtonService.saveButton(roleFuncVo.getRoleId(), btnIdList);
        if(aBoolean && aBoolean1){
            return  data.success(true);
        }else{
            return  data.failed();
        }

    }

    /**
     * 获取角色菜单列表
     * @return	List<FuncInfo>	菜单
     */
    @ApiOperation(value="获取角色按钮权限列表", notes="获取角色按钮权限列表")
    @GetMapping("getRoleFunc/{roleId}")
    public List<RoleFunc> getRoleFunc(@PathVariable("roleId") String roleId) {
        QueryWrapper<RoleFunc> objectQueryWrapper = new QueryWrapper<>();

        objectQueryWrapper.eq("role_id",roleId);
        List<RoleFunc> list = roleFuncService.list(objectQueryWrapper);

        return list;
    }

}

