package com.manage.service.ipml;

import com.manage.dao.*;
import com.manage.entity.*;
import com.manage.service.PowerService;
import com.manage.vo.PowerTree;
import com.manage.vo.Power_Sys_DictVo;
import com.manage.vo.Power_UserAndRoleTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName: power
 * @Package: com.manage.service.ipml
 * @ClassName: Power_Sys_DictServiceImpl
 * @Description: java类作用描述
 * @Author: 曾文和
 * @CreateDate: 2019/4/16 15:11
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/4/16 15:11
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
@Transactional
public class PowerServiceImpl implements PowerService  {
    @Autowired
    private Power_Sys_DictMapper sysDictMapper;
    @Autowired
    private Power_UserMapper userMapper;
    @Autowired
    private Power_MenuMapper menuMapper;
    @Autowired
    private Power_Role_MenuMapper roleMenuMapper;
    @Autowired
    private Power_User_MenuMapper userMenuMapper;
    @Autowired
    private PowerMapper powerMapper;

    @Override
    public List<Power_Sys_DictVo> selectAllSys() {
        return sysDictMapper.selectAllSys();
    }

    @Override
    public List<Power_Menu> getMethodByMenuIdPowerTree(Integer menuId) {
        return menuMapper.selectMethodByMenuIdPowerTree(menuId);
    }

    /**
      * @ProjectName:    getRolePowerTree
      * @Description:    角色树1.医院；2.系统；3.角色
      * @Param           无
      * @Return          PowerTree
      * @Author:         曾文和
      * @CreateDate:     2019/4/21 10:02
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/21 10:02
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public List<Power_UserAndRoleTree> getRolePowerTree(String key) {
        //roleId为0为系统管理员，系统管理员全查，其余按医院查
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Power_UserAndRoleTree> treeList = new ArrayList<>();
        List<Power_UserAndRoleTree> userTree = new ArrayList<>();
        if(user.getRoleId().equals(0)){
            userTree = powerMapper.getRoleTree(null,null,key);
        }else{
            userTree = powerMapper.getRoleTree(user.getUserId(),user.getRoleId(),key);
        }
        //1级医院
        List<Power_UserAndRoleTree> hosList = new ArrayList<>();
        //2级权限系统
        List<Power_UserAndRoleTree> powerList = new ArrayList<>();
        //3级科室
        List<Power_UserAndRoleTree> deptList = new ArrayList<>();
        //4级系统
        List<Power_UserAndRoleTree> sysList = new ArrayList<>();
        //5级用户
        List<Power_UserAndRoleTree> roleList = new ArrayList<>();
        if(null != userTree && !userTree.isEmpty()){
            for(Power_UserAndRoleTree tree:userTree){
                if(tree.getLevel().equals(1)){
                    hosList.add(tree);
                }
                if(tree.getLevel().equals(2)){
                    powerList.add(tree);
                }
                if(tree.getLevel().equals(3)){
                    deptList.add(tree);
                }
                if(tree.getLevel().equals(4)){
                    sysList.add(tree);
                }
                if(tree.getLevel().equals(5)){
                    roleList.add(tree);
                }
            }
        }
        if(!hosList.isEmpty()){
            //组织树
            int id = 1;
            int oneLevelId = 0;
            int twoLevelId = 0;
            for(Power_UserAndRoleTree hos : hosList){
                //第一级医院
                Power_UserAndRoleTree tree1 = new Power_UserAndRoleTree();
                BeanUtils.copyProperties(hos,tree1);
                tree1.setId(id);
                oneLevelId = id;
                tree1.setSelfId(null);
                treeList.add(tree1);
                id++;
                //获取该医院不重复角色
                Map<Integer,Power_UserAndRoleTree> roleListByHosId = new HashMap<>();
                if(!roleList.isEmpty()) {
                    //属于该医院的权限系统下有有该角色
                    for (Power_UserAndRoleTree powerRole : roleList) {
                        if (null != powerRole.getParentId() && powerRole.getParentId().equals(hos.getSelfId())) {
                            roleListByHosId.put(powerRole.getSelfId(),powerRole);
                        }
                    }
                }
                //第二级权限系统
                if(!powerList.isEmpty()){
                    for(Power_UserAndRoleTree powerSys : powerList){
                        if(powerSys.getParentId().equals(hos.getSelfId())){
                            Power_UserAndRoleTree tree2 = new Power_UserAndRoleTree();
                            BeanUtils.copyProperties(powerSys,tree2);
                            tree2.setId(id);
                            twoLevelId = id;
                            tree2.setParentId(oneLevelId);
                            tree2.setSelfId(null);
                            treeList.add(tree2);
                            id++;
                            //第三级角色
                            if(!roleListByHosId.isEmpty()){
                                //属于该医院的权限系统下有有该角色
                                for (Map.Entry<Integer, Power_UserAndRoleTree> entry : roleListByHosId.entrySet()) {
                                    if(entry.getValue().getParentId().equals(hos.getSelfId())){
                                        Power_UserAndRoleTree tree3 = new Power_UserAndRoleTree();
                                        BeanUtils.copyProperties(entry.getValue(),tree3);
                                        tree3.setId(id);
                                        tree3.setParentId(twoLevelId);
                                        tree3.setSysFlag("power");
                                        treeList.add(tree3);
                                        id++;
                                    }
                                }
                            }
                        }
                    }
                }
                //取系统和角色
                Map<String,Power_UserAndRoleTree> sysListByHosDeptId = new HashMap<>();
                List<Power_UserAndRoleTree> tempRoleList = new ArrayList<>();
                if(!deptList.isEmpty()) {
                    for (Power_UserAndRoleTree dept : deptList) {
                        if (dept.getParentId().equals(hos.getSelfId())) {
                            Set<String> sysFlagSet = new TreeSet<>();
                            //获取该科室不重复系统
                            if (!sysList.isEmpty()) {
                                for (Power_UserAndRoleTree sys : sysList) {
                                    if (null != sys.getParentId() && sys.getDeptId().equals(dept.getDeptId())) {
                                        sysListByHosDeptId.put(sys.getSysFlag(),sys);
                                        sysFlagSet.add(sys.getSysFlag());
                                    }
                                }
                            }
                            //给角色设置系统权限
                            if (!roleList.isEmpty()) {
                                for (Power_UserAndRoleTree role : roleList) {
                                    StringBuilder sysFlagStr = new StringBuilder();
                                    String deptId = role.getDeptId();
                                    if(StringUtils.isNotBlank(deptId)){
                                        //单一科室
                                        if (!deptId.contains(",")) {
                                            if (deptId.equals(dept.getDeptId())) {
                                                if(!sysFlagSet.isEmpty()){
                                                    for(String sysFlag:sysFlagSet){
                                                        sysFlagStr.append(sysFlag).append(",");
                                                    }
                                                }
                                                if(StringUtils.isNotBlank(sysFlagStr.toString())){
                                                    Power_UserAndRoleTree tempRole = new Power_UserAndRoleTree();
                                                    BeanUtils.copyProperties(role,tempRole);
                                                    tempRole.setSysFlag(sysFlagStr.toString());
                                                    tempRoleList.add(tempRole);
                                                }
                                            }
                                        } else {
                                            //逗号隔开多科室
                                            String[] deptIds = deptId.split(",");
                                            for (String deptStr : deptIds) {
                                                if (StringUtils.isNotBlank(deptStr) && deptStr.equals(dept.getDeptId())) {
                                                    if(!sysFlagSet.isEmpty()){
                                                        for(String sysFlag:sysFlagSet){
                                                            sysFlagStr.append(sysFlag).append(",");
                                                        }
                                                    }
                                                    if(StringUtils.isNotBlank(sysFlagStr.toString())){
                                                        Power_UserAndRoleTree tempRole = new Power_UserAndRoleTree();
                                                        BeanUtils.copyProperties(role,tempRole);
                                                        tempRole.setSysFlag(sysFlagStr.toString());
                                                        tempRoleList.add(tempRole);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //第三级系统
                    if (!sysListByHosDeptId.isEmpty()) {
                        for (Map.Entry<String,Power_UserAndRoleTree> sys : sysListByHosDeptId.entrySet()) {
                            if(sys.getValue().getParentId().equals(hos.getSelfId())){
                                Power_UserAndRoleTree tree5 = new Power_UserAndRoleTree();
                                BeanUtils.copyProperties(sys.getValue(), tree5);
                                tree5.setId(id);
                                tree5.setParentId(oneLevelId);
                                tree5.setSelfId(null);
                                treeList.add(tree5);
                                twoLevelId = id;
                                id++;
                                //第四级角色
                                Map<Integer,Power_UserAndRoleTree> roleListBySys = new HashMap<>();
                                if (!roleList.isEmpty()) {
                                    for (Power_UserAndRoleTree role : tempRoleList) {
                                        String sysFlag = role.getSysFlag();
                                        if(StringUtils.isNotBlank(sysFlag)){
                                            //逗号隔开多系统
                                            String[] sysFlags = sysFlag.split(",");
                                            for (String sysFlagStr : sysFlags) {
                                                if (StringUtils.isNotBlank(sysFlagStr) && sysFlagStr.equals(sys.getValue().getSysFlag())) {
                                                    roleListBySys.put(role.getSelfId(),role);
                                                }
                                            }
                                        }
                                    }
                                }
                                if(!roleListBySys.isEmpty()){
                                    for (Map.Entry<Integer,Power_UserAndRoleTree> roleBySys:roleListBySys.entrySet()) {
                                        Power_UserAndRoleTree tree6 = new Power_UserAndRoleTree();
                                        BeanUtils.copyProperties(roleBySys.getValue(), tree6);
                                        tree6.setId(id);
                                        tree6.setParentId(twoLevelId);
                                        tree6.setSysFlag(sys.getValue().getSysFlag());
                                        treeList.add(tree6);
                                        id++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return treeList;
    }
    /**
      * @ProjectName:    getMenuBySysIdAndRoleIdPowerTree
      * @Description:    通过系统id和角色id获取该系统菜单权限树
      * @Param           Integer dictId：系统id,Integer roleId:角色id
      * @Return          List<Power_Menu>
      * @Author:         曾文和
      * @CreateDate:     2019/4/22 15:11
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/22 15:11
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public List<Power_Menu> getMenuBySysIdAndRoleIdPowerTree(String sysFlag,Integer roleId) {
        List<Power_Menu> menus = menuMapper.selectAll(sysFlag, 1,roleId);
        //roleId为-100医院管理员，菜单功能全选中
        if(null != roleId && roleId == -100){
            if(null != menus && !menus.isEmpty()){
                for (int i = 0; i < menus.size(); i++) {
                    menus.get(i).setChecked("true");
                }
            }
        }else{
            //否则按角色菜单表该角色的权限选中
            List<Power_Role_Menu> roleMenus = roleMenuMapper.selectRoleMenuByRoleId(roleId);
            if(null != menus && !menus.isEmpty() && null != roleMenus && !roleMenus.isEmpty()){
                for (Power_Menu menu : menus) {
                    for (Power_Role_Menu roleMenu : roleMenus) {
                        if (menu.getMenuId().equals(roleMenu.getMenuId())) {
                            menu.setChecked("true");
                            break;
                        }
                    }
                }
            }
        }
        return menus;
    }

    /**
      * @ProjectName:    addRoleMenu
      * @Description:    保存角色菜单表
      * @Param           roleId：角色id,dictId:系统id,menus:菜单id集合
      * @Return          无
      * @Author:         曾文和
      * @CreateDate:     2019/4/22 9:54
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/22 9:54
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public void addRoleMenu(Integer roleId,String sysFlag,String menus) {
        //查询该角色对应系统已有的权限，先删除后新增
        roleMenuMapper.deleteRoleMenuByRoleAndSysFlag(sysFlag,roleId);
        if(StringUtils.isNotBlank(menus)){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String userName = user.getUserName();
            String[] menu = menus.split(",");
            List<Power_Role_Menu> list = new ArrayList<>();
            for(String m :  menu){
                if(StringUtils.isNotBlank(m)){
                    Power_Role_Menu roleMenu = new Power_Role_Menu();
                    roleMenu.setCreater(userName);
                    roleMenu.setUpdater(userName);
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                    roleMenu.setCreateDate(fmt.format(new Date()));
                    roleMenu.setUpdateDate(fmt.format(new Date()));
                    roleMenu.setRoleId(roleId);
                    roleMenu.setMenuId(Integer.valueOf(m));
                    list.add(roleMenu);
                }
            }
            roleMenuMapper.simpleInsertRoleMenu(list);
        }
    }
/**********************************************用户菜单权限操作********************************************************/
/**
      * @ProjectName:    getUserPowerTree
      * @Description:    用户树1.医院；2.科室；3.科室；4用户
      * @Param           List<PowerTree>
      * @Return          返回
      * @Author:         曾文和
      * @CreateDate:     2019/4/22 15:12
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/22 15:12
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public List<Power_UserAndRoleTree> getUserPowerTree(String key) {
        //roleId为0为系统管理员，系统管理员全查，其余按医院查
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Power_UserAndRoleTree> treeList = new ArrayList<>();
        List<Power_UserAndRoleTree> userTree = new ArrayList<>();
        if(user.getRoleId().equals(0)){
            userTree = powerMapper.getUserTree(null,key);
        }else{
            userTree = powerMapper.getUserTree(user.getUserId(),key);
        }
        //1级医院
        List<Power_UserAndRoleTree> hosList = new ArrayList<>();
        //2级权限系统
        List<Power_UserAndRoleTree> powerList = new ArrayList<>();
        //3级科室
        List<Power_UserAndRoleTree> deptList = new ArrayList<>();
        //4级系统
        List<Power_UserAndRoleTree> sysList = new ArrayList<>();
        //5级用户
        List<Power_UserAndRoleTree> userList = new ArrayList<>();
        if(null != userTree && !userTree.isEmpty()){
            for(Power_UserAndRoleTree tree:userTree){
                if(tree.getLevel().equals(1)){
                    hosList.add(tree);
                }
                if(tree.getLevel().equals(2)){
                    powerList.add(tree);
                }
                if(tree.getLevel().equals(3)){
                    deptList.add(tree);
                }
                if(tree.getLevel().equals(4)){
                    sysList.add(tree);
                }
                if(tree.getLevel().equals(5)){
                    userList.add(tree);
                }
            }
        }
        if(!hosList.isEmpty()){
            //组织树
            int id = 1;
            int oneLevelId = 0;
            int twoLevelId = 0;
            int threeLevelId = 0;
            for(Power_UserAndRoleTree hos : hosList){
                //第一级医院
                Power_UserAndRoleTree tree1 = new Power_UserAndRoleTree();
                BeanUtils.copyProperties(hos,tree1);
                tree1.setId(id);
                tree1.setSelfId(hos.getSelfId());
                oneLevelId = id;
                treeList.add(tree1);
                id++;
                //第二级权限系统
                if(!powerList.isEmpty()){
                    for(Power_UserAndRoleTree powerSys : powerList){
                        if(powerSys.getParentId().equals(hos.getSelfId())){
                            Power_UserAndRoleTree tree2 = new Power_UserAndRoleTree();
                            BeanUtils.copyProperties(powerSys,tree2);
                            tree2.setId(id);
                            twoLevelId = id;
                            tree2.setParentId(oneLevelId);
                            tree2.setSysFlag(powerSys.getSysFlag());
                            boolean isParent = false;
                            id++;
                            //第三级用户
                            if(!userList.isEmpty()){
                                //属于该医院的权限系统下有有该用户
                                for(Power_UserAndRoleTree powerUser : userList){
                                    if(null != powerUser.getParentId() && powerUser.getParentId().equals(hos.getSelfId())){
                                        if(StringUtils.isNotBlank(key)){
                                            Power_UserAndRoleTree tree3 = new Power_UserAndRoleTree();
                                            BeanUtils.copyProperties(powerUser,tree3);
                                            tree3.setId(id);
                                            tree3.setParentId(twoLevelId);
                                            if(StringUtils.isNotBlank(powerUser.getRealName())){
                                                tree3.setName(powerUser.getName()+"-"+powerUser.getRealName());
                                                tree3.setNewName(powerUser.getName()+"-"+powerUser.getRealName());
                                            }else{
                                                tree3.setName(powerUser.getName());
                                                tree3.setNewName(powerUser.getName());
                                            }
                                            tree3.setSysFlag("power");
                                            treeList.add(tree3);
                                            id++;
                                        }
                                        isParent = true;
                                    }
                                }
                            }
                            tree2.setIsParent(isParent);
                            treeList.add(tree2);
                        }
                    }
                }
                //第二级科室
                if(!deptList.isEmpty()){
                    for(Power_UserAndRoleTree dept : deptList){
                        if(dept.getParentId().equals(hos.getSelfId())){
                            Power_UserAndRoleTree tree4 = new Power_UserAndRoleTree();
                            BeanUtils.copyProperties(dept,tree4);
                            tree4.setId(id);
                            twoLevelId = id;
                            tree4.setParentId(oneLevelId);
                            tree4.setSelfId(Integer.valueOf(dept.getDeptId()));
                            treeList.add(tree4);
                            id++;
                        }
                        //第三级系统
                        if(!sysList.isEmpty()){
                            for(Power_UserAndRoleTree sys : sysList) {
                                if (null != sys.getParentId() && sys.getDeptId().equals(dept.getDeptId()) && sys.getParentId().equals(hos.getSelfId())) {
                                    Power_UserAndRoleTree tree5 = new Power_UserAndRoleTree();
                                    BeanUtils.copyProperties(sys,tree5);
                                    tree5.setId(id);
                                    tree5.setParentId(twoLevelId);
                                    tree5.setSysFlag(sys.getSysFlag());
                                    threeLevelId = id;
                                    id++;
                                    boolean isParent = false;
                                    //第四级用户
                                    if(!userList.isEmpty()) {
                                        for (Power_UserAndRoleTree users : userList) {
                                            String deptId = users.getDeptId();
                                            if(StringUtils.isNotBlank(deptId)){
                                                //单一科室
                                                if(!deptId.contains(",")){
                                                    if(deptId.equals(dept.getDeptId())){
                                                        isParent = true;
                                                        if(StringUtils.isNotBlank(key)){
                                                            id++;
                                                            Power_UserAndRoleTree tree6 = new Power_UserAndRoleTree();
                                                            BeanUtils.copyProperties(users,tree6);
                                                            tree6.setId(id);
                                                            tree6.setParentId(threeLevelId);
                                                            if(StringUtils.isNotBlank(users.getRealName())){
                                                                tree6.setName(users.getName()+"-"+users.getRealName());
                                                                tree6.setNewName(users.getName()+"-"+users.getRealName());
                                                            }else{
                                                                tree6.setName(users.getName());
                                                                tree6.setNewName(users.getName());
                                                            }
                                                            tree6.setSysFlag(sys.getSysFlag());
                                                            treeList.add(tree6);
                                                            id++;
                                                        }
                                                    }
                                                }else{
                                                    //逗号隔开多科室
                                                    String[] deptIds = deptId.split(",");
                                                    for (String deptStr : deptIds) {
                                                        if(StringUtils.isNotBlank(deptStr) && deptStr.equals(dept.getDeptId())){
                                                            if(StringUtils.isNotBlank(key)){
                                                                Power_UserAndRoleTree tree7 = new Power_UserAndRoleTree();
                                                                BeanUtils.copyProperties(users,tree7);
                                                                tree7.setId(id);
                                                                tree7.setParentId(threeLevelId);
                                                                if(StringUtils.isNotBlank(users.getRealName())){
                                                                    tree7.setName(users.getName()+"-"+users.getRealName());
                                                                    tree7.setNewName(users.getName()+"-"+users.getRealName());
                                                                }else{
                                                                    tree7.setName(users.getName());
                                                                    tree7.setNewName(users.getName());
                                                                }
                                                                tree7.setSysFlag(sys.getSysFlag());
                                                                treeList.add(tree7);
                                                                id++;
                                                            }
                                                            isParent = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    tree5.setIsParent(isParent);
                                    treeList.add(tree5);
                                }
                            }
                        }
                    }
                }
            }
        }
        return treeList;
    }

    @Override
    public List<Power_UserAndRoleTree> getUserTreeByHospitalId(Integer hospitalId) {
        List<Power_User> userList = userMapper.getUserTreeByHospitalId(hospitalId);
        List<Power_UserAndRoleTree> treeList = new ArrayList<>();
        if(null != userList && !userList.isEmpty()){
            for (Power_User users : userList) {
                Power_UserAndRoleTree tree6 = new Power_UserAndRoleTree();
                if(StringUtils.isNotBlank(users.getName())){
                    tree6.setName(users.getUserName()+"-"+users.getName());
                    tree6.setNewName(users.getUserName()+"-"+users.getName());
                }else{
                    tree6.setName(users.getUserName());
                    tree6.setNewName(users.getUserName());
                }
                tree6.setSelfId(users.getUserId());
                treeList.add(tree6);
            }
        }
        return treeList;
    }

    @Override
    public List<Power_UserAndRoleTree> getUserTreeByDeptId(Integer deptId) {
        List<Power_User> userList = userMapper.getUserTreeByDeptId(deptId);
        List<Power_UserAndRoleTree> treeList = new ArrayList<>();
        if(null != userList && !userList.isEmpty()){
            for (Power_User users : userList) {
                Power_UserAndRoleTree tree6 = new Power_UserAndRoleTree();
                if(StringUtils.isNotBlank(users.getName())){
                    tree6.setName(users.getUserName()+"-"+users.getName());
                    tree6.setNewName(users.getUserName()+"-"+users.getName());
                }else{
                    tree6.setName(users.getUserName());
                    tree6.setNewName(users.getUserName());
                }
                tree6.setSelfId(users.getUserId());
                treeList.add(tree6);
            }
        }
        return treeList;
    }

    //根据用户
    /**
      * @ProjectName:    getMenuBySysIdAndUerIdPowerTree
      * @Description:    通过系统id和用户id获取该系统的菜单权限
      * @Param           Integer dictId:系统id, Integer userId:用户id
      * @Return          返回
      * @Author:         曾文和
      * @CreateDate:     2019/4/22 15:07
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/22 15:07
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public List<Power_Menu> getMenuBySysIdAndUerIdPowerTree(String sysFlag, Integer userId) {
        //查询对应系统的且状态为可用的菜单集合
        //系统标识查
        Power_User user = userMapper.selectByPrimaryKey(userId);
        List<Power_Menu> menus = menuMapper.selectAll(sysFlag, 1,user.getRoleId());
        //roleId为-100医院管理员，菜单功能全选中
        if(null != user.getRoleId() && user.getRoleId() == -100){
            if(null != menus && !menus.isEmpty()){
                for (Power_Menu menu : menus) {
                    menu.setChecked("true");
                }
            }
        }else{
            //否则查询对应系统的用户权限菜单id集合
            List<Power_User_Menu> userMenus = userMenuMapper.selectUserAndRoleMenuPower(sysFlag, userId);
            if(null != menus && !menus.isEmpty() && null != userMenus && !userMenus.isEmpty()){
                //有符合权限则checked设为true
                for (Power_Menu menu : menus) {
                    for (Power_User_Menu userMenu : userMenus) {
                        if (menu.getMenuId().equals(userMenu.getMenuId())) {
                            menu.setChecked("true");
                            break;
                        }
                    }
                }
            }
        }
        return menus;
    }

    /**
      * @ProjectName:    addUserMenu
      * @Description:    保存用户菜单表
      * @Param           Integer userId：用户id, Integer dictId：系统id, String menus:菜单id集合
      * @Return          返回
      * @Author:         曾文和
      * @CreateDate:     2019/4/22 15:08
      * @UpdateUser:     更新者
      * @UpdateDate:     2019/4/22 15:08
      * @UpdateRemark:   更新说明
      * @Version:        1.0
     */
    @Override
    public void addUserMenu(Integer userId, String sysFlag, String menus) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        //查询该用户对应系统在用户菜单表中已有的权限，先删除后新增
        userMenuMapper.deleteUserMenuByUserIdAndSysFlag(sysFlag, userId);
        Power_User powerUser = userMapper.selectByPrimaryKey(userId);
        //查询该用户对应的角色菜单权限
        List<Power_Role_Menu> rolePowers = roleMenuMapper.selectRoleMenuPower(sysFlag, powerUser.getRoleId());
        if(null != rolePowers && !rolePowers.isEmpty()){
            if(StringUtils.isBlank(menus)){
                //全取消
                List<Power_User_Menu> list = new ArrayList<>();
                for (Power_Role_Menu rolePower : rolePowers) {
                    list.add(addUserFunction(userName, userId, rolePower.getMenuId().toString(), 0));
                }
                userMenuMapper.simpleInsertUserMenu(list);
            }else{
                //计算新增和删除
                List<String> roles = new ArrayList<>();
                List<String> users = new ArrayList<>();
                for (Power_Role_Menu rolePower : rolePowers) {
                    roles.add(rolePower.getMenuId().toString());
                }
                String[] menu = menus.split(",");
                users =  Arrays.asList(menu);
                //新增部分
                Collection<String> inserts=new ArrayList<String>(users);
                inserts.removeAll(roles);
                if(!inserts.isEmpty()){
                    //新增flag为1
                    List<Power_User_Menu> list = new ArrayList<>();
                    for (String insertMenu : inserts) {
                        if(StringUtils.isNotBlank(insertMenu)){
                           list.add(addUserFunction(userName,userId,insertMenu,1));
                        }
                    }
                    userMenuMapper.simpleInsertUserMenu(list);
                }
                 //删除部分
                Collection<String> deletes=new ArrayList<String>(roles);
                deletes.removeAll(users);
                if(!deletes.isEmpty()){
                    List<Power_User_Menu> list = new ArrayList<>();
                    for(String deleteMenu :  deletes){
                        if(StringUtils.isNotBlank(deleteMenu)){
                           list.add(addUserFunction(userName,userId,deleteMenu,0));
                        }
                    }
                    userMenuMapper.simpleInsertUserMenu(list);
                }
            }
        }else{
            //未设置角色权限，全部添加到用户权限
             if(StringUtils.isNotBlank(menus)) {
                 String[] menu = menus.split(",");
                 //新增flag为1
                 List<Power_User_Menu> list = new ArrayList<>();
                 for (String insertMenu : menu) {
                     if (StringUtils.isNotBlank(insertMenu)) {
                         list.add(addUserFunction(userName, userId, insertMenu, 1));
                     }
                 }
                 userMenuMapper.simpleInsertUserMenu(list);
             }
        }
    }

    //封装新增用户菜单权限表公共部分
    private Power_User_Menu addUserFunction(String userName,Integer userId,String menu,Integer flag){
        Power_User_Menu userMenu = new Power_User_Menu();
        userMenu.setCreater(userName);
        userMenu.setUpdater(userName);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        userMenu.setCreateDate(fmt.format(new Date()));
        userMenu.setUpdateDate(fmt.format(new Date()));
        userMenu.setUserId(userId);
        userMenu.setMenuId(Integer.valueOf(menu));
        userMenu.setFlag(flag);
        return userMenu;
    }

    /**
     * @ProjectName:    getRolePowerTreeBySysFlag
     * @Description:    病案管理系统接口   根据系统标识组织角色树
     * @Param           无
     * @Return          PowerTree
     * @Author:         曾文和
     * @CreateDate:     2019/7/9 10:02
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/09/04 10:02
     * @UpdateRemark:   重新查询
     * @Version:        1.0
     */
    @Override
    public List<PowerTree> getRolePowerTreeBySysFlag(String sysFlag,Power_User user) {
        //根据系统标识查询科室id
        List<Power_Sys_DictVo> dicts = new ArrayList<>();
        if(user.getRoleId() == 0){
            dicts = sysDictMapper.selectAllByAdmin();
        }/*else if(user.getRoleId() == -100){
            dicts = sysDictMapper.selectAllByHosRoleId(user.getUserId());
        }*/else{
            dicts = sysDictMapper.selectAllByHosRoleId(user.getUserId(),user.getRoleId(),null);
            //dicts = sysDictMapper.selectAllByUserId(user.getUserId());
        }
        //获取用户集合
        List<Power_Sys_DictVo> userList = new ArrayList<>();
        List<PowerTree> treeList = new ArrayList<>();
        int id = 0;
        int oneLevel = 0;
        int twoLevel = 0;
        Map<Integer,String>  hospitalNameSet = new HashMap<>();
        if(null != dicts && !dicts.isEmpty()){
            for (Power_Sys_DictVo dict : dicts) {
                if (StringUtils.isNotBlank(dict.getHospitalName())) {
                    hospitalNameSet.put(dict.getDictId(), dict.getHospitalName());
                }
                //用户集合
                if (null == dict.getDictId()) {
                    userList.add(dict);
                }
            }
        }
        if(!hospitalNameSet.isEmpty()){
            for(Integer hosKey : hospitalNameSet.keySet()){
                Map<String,String> deptNameSet = new HashMap<>();
                Map<Integer,Power_Sys_DictVo> poweSysNameSet = new HashMap<>();
                Set<Integer> deptIds = new TreeSet<>();
                //医院层
                id++;
                oneLevel = id;
                PowerTree tree1 = new PowerTree();
                tree1.setId(id);
                tree1.setName(hospitalNameSet.get(hosKey));
                treeList.add(tree1);
                for (Power_Sys_DictVo dict : dicts) {
                    //查询病案系统的科室
                    if (StringUtils.isNotBlank(dict.getSysFlag()) && dict.getSysFlag().equals(sysFlag) && dict.getParentId().equals(hosKey) && null != dict.getDictDeptId()) {
                        deptIds.add(dict.getDictDeptId());
                    }
                }
                if(!deptIds.isEmpty()){
                    for(Integer deptId : deptIds){
                        for (Power_Sys_DictVo dict : dicts) {
                            if (StringUtils.isNotBlank(dict.getDeptIds()) && dict.getDeptIds().equals(deptId.toString()) && StringUtils.isNotBlank(dict.getDeptName())) {
                                deptNameSet.put(dict.getDeptIds(), dict.getDeptName());
                            }
                        }
                    }
                    if(!deptNameSet.isEmpty()){
                        for (String key : deptNameSet.keySet()) {
                            //科室层
                            id++;
                            twoLevel = id;
                            PowerTree tree2 = new PowerTree();
                            tree2.setId(id);
                            tree2.setParentId(oneLevel);
                            tree2.setName(deptNameSet.get(key));
                            treeList.add(tree2);
                            Map<Integer,String> roleMap = new HashMap<>();
                            if (!userList.isEmpty()) {
                                for (Power_Sys_DictVo dictVo : userList) {
                                    if (StringUtils.isNoneBlank(dictVo.getSysType())) {
                                        String deptIdss = dictVo.getDeptIds();
                                        if (StringUtils.isNotBlank(deptIdss)) {
                                            if (!deptIdss.contains(",")) {
                                                if (deptIdss.equals(key)) {
                                                    roleMap.put(dictVo.getParentId(), dictVo.getSysType());
                                                }
                                            } else {
                                                String[] deptIdsss = deptIdss.split(",");
                                                for (String deptId : deptIdsss) {
                                                    if (StringUtils.isNotBlank(deptId) && deptId.equals(key)) {
                                                        roleMap.put(dictVo.getParentId(), dictVo.getSysType());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                for(Integer roleId:roleMap.keySet()){
                                    //角色层
                                    id++;
                                    PowerTree tree3 = new PowerTree();
                                    tree3.setId(id);
                                    tree3.setParentId(twoLevel);
                                    tree3.setName(roleMap.get(roleId));
                                    tree3.setSelfId(roleId);
                                    treeList.add(tree3);
                                }
                            }
                        }
                    }
                }
            }
        }
        return treeList;
    }

    /**
     * @ProjectName:    getUserPowerTreeBySysFlag
     * @Description:    病案管理系统接口 根据系统标识组织用户树
     * @Param           无
     * @Return          PowerTree
     * @Author:         曾文和
     * @CreateDate:     2019/7/9 10:02
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/9/4 10:02
     * @UpdateRemark:   重新查询
     * @Version:        1.0
     */
    @Override
    public List<PowerTree> getUserPowerTreeBySysFlag(String sysFlag,Power_User user) {
        //根据系统标识查询科室id
        List<Power_Sys_DictVo> dicts = new ArrayList<>();
        if(user.getRoleId() == 0){
            dicts = sysDictMapper.selectAllByAdmin();
        }/*else if(user.getRoleId() == -100){
            dicts = sysDictMapper.selectAllByHosRoleId(user.getUserId());
        }*/else{
            dicts = sysDictMapper.selectAllByHosRoleId(user.getUserId(),null,null);
            //dicts = sysDictMapper.selectAllByUserId(user.getUserId());
        }
        List<Power_Sys_DictVo> userList = new ArrayList<>();
        List<PowerTree> treeList = new ArrayList<>();
        int id = 0;
        int oneLevel = 0;
        int twoLevel = 0;
        Map<Integer,String>  hospitalNameSet = new HashMap<>();
        if(null != dicts && !dicts.isEmpty()){
            for (Power_Sys_DictVo dict : dicts) {
                if (StringUtils.isNotBlank(dict.getHospitalName())) {
                    hospitalNameSet.put(dict.getDictId(), dict.getHospitalName());
                }
                //用户集合
                if (null == dict.getDictId()) {
                    userList.add(dict);
                }
            }
        }
        if(!hospitalNameSet.isEmpty()){
            for(Integer hosKey : hospitalNameSet.keySet()){
                Map<String,String> deptNameSet = new HashMap<>();
                Set<Integer> deptIds = new TreeSet<>();
                //医院层
                id++;
                oneLevel = id;
                PowerTree tree1 = new PowerTree();
                tree1.setId(id);
                tree1.setName(hospitalNameSet.get(hosKey));
                treeList.add(tree1);
                for (Power_Sys_DictVo dict : dicts) {
                    //查询病案系统的科室
                    if (StringUtils.isNotBlank(dict.getSysFlag()) && dict.getSysFlag().equals(sysFlag) && dict.getParentId().equals(hosKey)) {
                        deptIds.add(dict.getDictDeptId());
                    }
                }
                if(!deptIds.isEmpty()){
                    for(Integer deptId : deptIds){
                        for (Power_Sys_DictVo dict : dicts) {
                            if (StringUtils.isNotBlank(dict.getDeptIds()) && dict.getDeptIds().equals(deptId.toString()) && StringUtils.isNotBlank(dict.getDeptName())) {
                                deptNameSet.put(dict.getDeptIds(), dict.getDeptName());
                            }
                        }
                    }
                    if(!deptNameSet.isEmpty()){
                        for (String key : deptNameSet.keySet()) {
                            //科室层
                            id++;
                            twoLevel = id;
                            PowerTree tree2 = new PowerTree();
                            tree2.setId(id);
                            tree2.setParentId(oneLevel);
                            tree2.setName(deptNameSet.get(key));
                            treeList.add(tree2);
                            Map<Integer,Power_Sys_DictVo> roleMap = new HashMap<>();
                            //sysName 用户id，hospitalTel 手机号,dictArea用户名，parentId角色id，sysType角色名
                            if (!userList.isEmpty()) {
                                for (Power_Sys_DictVo dictVo : userList) {
                                    if (StringUtils.isNoneBlank(dictVo.getDictArea())) {
                                        String deptIdss = dictVo.getDeptIds();
                                        if (StringUtils.isNotBlank(deptIdss)) {
                                            if (!deptIdss.contains(",")) {
                                                if (deptIdss.equals(key)) {
                                                    roleMap.put(Integer.valueOf(dictVo.getSysName()), dictVo);
                                                }
                                            } else {
                                                String[] deptIdsss = deptIdss.split(",");
                                                for (String deptId : deptIdsss) {
                                                    if (StringUtils.isNotBlank(deptId) && deptId.equals(key)) {
                                                        roleMap.put(Integer.valueOf(dictVo.getSysName()), dictVo);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                for (Map.Entry<Integer,Power_Sys_DictVo> map : roleMap.entrySet()) {
                                    //用户层
                                    id++;
                                    PowerTree tree4 = new PowerTree();
                                    tree4.setId(id);
                                    tree4.setParentId(twoLevel);
                                    if(StringUtils.isNotBlank(map.getValue().getHospitalTel())){
                                        tree4.setName(map.getValue().getUserName()+"-"+map.getValue().getDictArea()+"("+map.getValue().getHospitalTel()+")");
                                    }else{
                                        tree4.setName(map.getValue().getUserName()+"-"+map.getValue().getDictArea());
                                    }
                                    tree4.setSelfId(map.getKey());
                                    tree4.setRoleId(map.getValue().getParentId());
                                    treeList.add(tree4);
                                }
                            }
                        }
                    }
                }
            }
        }
        return treeList;
    }

    //归属管理的树
    @Override
    public List<PowerTree> getDictPowerTree(String content) {
        //roleId为0为系统管理员，系统管理员全查，其余按医院查
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Power_Sys_DictVo> dicts = new ArrayList<>();
        if(user.getRoleId() == 0){
            dicts = sysDictMapper.selectAll(content);
        }else if(user.getRoleId() == -100){
            dicts = sysDictMapper.selectAllByHosRoleId(user.getUserId(),null,content);
        }else{
            dicts = sysDictMapper.selectAllByUserId(user.getUserId(),content);
        }
        List<PowerTree> treeList = new ArrayList<>();
        PowerTree tree = new PowerTree();
        tree.setId(1);
        tree.setSelfId(0);
        tree.setName("医院列表");
        treeList.add(tree);
        int id = 1;
        int oneLevel = 0;
        int twoLevel = 0;
        Map<Integer,String>  hospitalNameSet = new HashMap<>();
        if(null != dicts && !dicts.isEmpty()){
            for (Power_Sys_DictVo dict : dicts) {
                if (StringUtils.isNotBlank(dict.getHospitalName())) {
                    hospitalNameSet.put(dict.getDictId(), dict.getHospitalName());
                }
            }
        }
        if(!hospitalNameSet.isEmpty()){
            for(Integer hosKey : hospitalNameSet.keySet()){
                Map<Integer,String> deptNameSet = new HashMap<>();
                Map<Integer,Power_Sys_DictVo> poweSysNameSet = new HashMap<>();
                //医院层
                id++;
                oneLevel = id;
                PowerTree tree1 = new PowerTree();
                tree1.setId(id);
                tree1.setParentId(1);
                tree1.setSelfId(hosKey);
                tree1.setName(hospitalNameSet.get(hosKey));
                treeList.add(tree1);
                for (Power_Sys_DictVo dict : dicts) {
                    if (dict.getParentId().equals(hosKey)) {
                        String deptName = dict.getDeptName();
                        if (StringUtils.isNoneBlank(deptName)) {
                            deptNameSet.put(dict.getDeptId(), dict.getDeptName());
                        }
                    }
                    //添加权限系统
                    if (dict.getParentId() != null && StringUtils.isNotBlank(dict.getSysFlag()) && dict.getParentId().equals(hosKey) && "权限系统".equals(dict.getSysType())) {
                        poweSysNameSet.put(dict.getDictId(), dict);
                    }
                }
                //添加权限系统
                if(!poweSysNameSet.isEmpty()){
                    for (Integer key : poweSysNameSet.keySet()) {
                        id++;
                        twoLevel = id;
                        PowerTree tree20 = new PowerTree();
                        tree20.setId(id);
                        tree20.setParentId(oneLevel);
                        tree20.setSelfId(key);
                        tree20.setSysType(poweSysNameSet.get(key).getSysType());
                        tree20.setName(poweSysNameSet.get(key).getSysName());
                        tree20.setNewName(poweSysNameSet.get(key).getSysName());
                        treeList.add(tree20);
                    }
                }
                if(!deptNameSet.isEmpty()){
                    for (Integer key : deptNameSet.keySet()) {
                        Map<Integer,String> sysNameSet = new HashMap<>();
                        //科室层
                        id++;
                        twoLevel = id;
                        PowerTree tree2 = new PowerTree();
                        tree2.setId(id);
                        tree2.setParentId(oneLevel);
                        tree2.setName(deptNameSet.get(key));
                        tree2.setSelfId(0-key);
                        treeList.add(tree2);
                        for (Power_Sys_DictVo dict : dicts) {
                            if (dict.getDictDeptId() != null && dict.getDictDeptId().equals(key)
                                    && dict.getParentId() != null && dict.getParentId().equals(hosKey)) {
                                String sysName = dict.getSysName();
                                if (StringUtils.isNoneBlank(sysName)) {
                                    sysNameSet.put(dict.getDictId(), sysName);
                                }
                            }
                        }
                        if(!sysNameSet.isEmpty()){
                            for (Integer dictId : sysNameSet.keySet()) {
                                //系统层
                                id++;
                                PowerTree tree3 = new PowerTree();
                                tree3.setId(id);
                                tree3.setParentId(twoLevel);
                                tree3.setName(sysNameSet.get(dictId));
                                tree3.setSelfId(dictId);
                                treeList.add(tree3);
                            }
                        }
                    }
                }
            }
        }
        return treeList;
    }
}
