package cn.ibizlab.core.extensions.service;


import cn.ibizlab.core.uaa.domain.SYS_ROLE_PERMISSION;
import cn.ibizlab.core.uaa.service.ISYS_PERMISSIONService;
import cn.ibizlab.core.uaa.service.ISYS_PSAPPMENUITEMService;
import cn.ibizlab.core.uaa.service.ISYS_ROLE_PERMISSIONService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class UAACoreService {
    @Autowired
    private ISYS_PERMISSIONService isys_permissionService;
    @Autowired
    private ISYS_PSAPPMENUITEMService isys_psappmenuitemService;
    @Autowired
    private ISYS_ROLE_PERMISSIONService isys_role_permissionService;
    /**
     * 获取应用菜单
     *
     * @return
     */
    public JSONArray getAppMenu() {
        // 用户所在系统id,R7的AuthenticationUser中已经没有systemid了
//        String systemid= AuthenticationUser.getAuthenticationUser().getSystemid();

        StringBuilder nPermissionSQL = new StringBuilder();
        nPermissionSQL.append("SELECT ");
        nPermissionSQL.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        nPermissionSQL.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
//        nPermissionSQL.append(" t1.PERMISSIONID as permissionid, ");
        nPermissionSQL.append(" t1.PSAPPMENUITEMID as permissionid, ");
//        nPermissionSQL.append(" t1.P_PERMISSIONID as p_permissionid, ");
        nPermissionSQL.append(" t1.PSAPPPMENUITEMID as p_permissionid, ");
        nPermissionSQL.append(" t1.PSAPPID as psappid, ");
        nPermissionSQL.append(" t1.PSAPPNAME as psappname, ");
        nPermissionSQL.append(" t1.PSAPPMENUID as psappmenuid, ");
        nPermissionSQL.append(" t1.PSAPPMENUNAME as psappmenuname, ");
        nPermissionSQL.append(" t1.PSSYSTEMID as systemid ");
        nPermissionSQL.append(" FROM IBZPERMISSION t");
        nPermissionSQL.append(" INNER JOIN IBZPSAPPMENUITEM t1 ON t.SYS_PERMISSIONID = t1.SYS_PSAPPMENUITEMID and t.enable =1");
        List<JSONObject> permissions = isys_psappmenuitemService.select(nPermissionSQL.toString(), null);

        // 清空sql,获取应用菜单所处系统
        nPermissionSQL.delete(0, nPermissionSQL.length());
        nPermissionSQL.append("select temp.systemid from (  ");
        nPermissionSQL.append(" SELECT ");
        nPermissionSQL.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        nPermissionSQL.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
//        nPermissionSQL.append(" t1.PERMISSIONID as permissionid, ");
        nPermissionSQL.append(" t1.PSAPPMENUITEMID as permissionid, ");
//        nPermissionSQL.append(" t1.P_PERMISSIONID as p_permissionid, ");
        nPermissionSQL.append(" t1.PSAPPPMENUITEMID as p_permissionid, ");
        nPermissionSQL.append(" t1.PSAPPID as psappid, ");
        nPermissionSQL.append(" t1.PSAPPNAME as psappname, ");
        nPermissionSQL.append(" t1.PSAPPMENUID as psappmenuid, ");
        nPermissionSQL.append(" t1.PSAPPMENUNAME as psappmenuname, ");
        nPermissionSQL.append(" t1.PSSYSTEMID as systemid ");
        nPermissionSQL.append(" FROM IBZPERMISSION t INNER JOIN IBZPSAPPMENUITEM t1 ON t.SYS_PERMISSIONID = t1.SYS_PSAPPMENUITEMID and t.enable =1");
        nPermissionSQL.append(" )temp group by temp.systemid");
        List<JSONObject> systems = isys_psappmenuitemService.select(nPermissionSQL.toString(), null);


        JSONArray treeNode = new JSONArray();
        if (permissions.size() > 0 && systems.size() > 0) {
            treeNode = this.transferAppMenuToELTree(permissions, systems);
        }

        return treeNode;
    }

    /**
     * 用于将资源表中菜单数据转换成饿了么树格式数据
     *
     * @param permissions
     * @param systems
     * @return
     */
    private JSONArray transferAppMenuToELTree(List<JSONObject> permissions, List<JSONObject> systems) {
        Map<String, String> appKeyMap = new HashMap<>();
        Map<String, String> appMenuKeyMap = new HashMap<>();
        JSONObject groupByMenuObj = this.groupByAppMenu(permissions, systems, appKeyMap, appMenuKeyMap);//将数据库数据进行分组
        JSONArray elTreeObj = transferAppMenuToELTree(groupByMenuObj, appKeyMap, appMenuKeyMap);//将分组后的数据转换成饿了么树格式数据
        return elTreeObj;
    }

    /**
     * 将数据库中的菜单数据进行分组
     *
     * @param permissions
     * @param systems
     * @param appKeyMap
     * @param appMenuKeyMap
     * @return
     */
    private JSONObject groupByAppMenu(List<JSONObject> permissions, List<JSONObject> systems, Map<String, String> appKeyMap, Map<String, String> appMenuKeyMap) {
        JSONObject permission_system = new JSONObject(); //顶级系统数据
        for (JSONObject system : systems) {
            String systemid = system.getString("systemid");
            JSONObject permission_app = new JSONObject(); //次级应用数据
            for (JSONObject obj : permissions) {
                String str_app = String.format("IBIZAPP-%s", obj.get("psappid"));
                String str_appName = String.format("%s", obj.get("psappname"));
                String str_appMenu = String.format("IBIZMENU-%s", obj.get("psappmenuid"));
                String str_appMenuName = String.format("%s", obj.get("psappmenuname"));
                String str_systemid = String.format("%s", obj.get("systemid"));

//               String sys_permissionId = DigestUtils.md5DigestAsHex(String.format("%s%s", systemId, obj.get("permissionid")).getBytes());
                String permissionId = String.format("%s", obj.get("permissionid"));
                String sys_permissionId = String.format("%s", obj.get("sys_permissionid"));
                String p_sys_permissionId = "";

                if (!StringUtils.isEmpty(obj.get("p_permissionid"))) {
//               p_sys_permissionId = DigestUtils.md5DigestAsHex(String.format("%s%s", systemId, obj.get("p_permissionid")).getBytes());
                    p_sys_permissionId = String.format("%s", obj.get("p_permissionid"));
                }

                // 根据systemid进行操作
                if (systemid.equals(str_systemid)) {
                    JSONObject cur_system = new JSONObject();
                    JSONObject cur_app = new JSONObject();
                    JSONArray cur_app_menu = new JSONArray();


                    if (permission_system.containsKey(str_systemid))// 系统合并
                        cur_system = permission_system.getJSONObject(str_systemid);

                    if (permission_app.containsKey(str_app))//合并前端应用
                        cur_app = permission_app.getJSONObject(str_app);

                    if (cur_app.containsKey(str_appMenu))//合并菜单
                        cur_app_menu = cur_app.getJSONArray(str_appMenu);

                    JSONObject permission = new JSONObject();
                    permission.put("id", permissionId);
                    permission.put("sys_permissionId", sys_permissionId);
                    permission.put("pid", p_sys_permissionId);
                    permission.put("label", obj.get("sys_permissionname"));

                    cur_app_menu.add(permission);
                    cur_app.put(str_appMenu, cur_app_menu);
                    cur_system.put(str_app, cur_app);

                    permission_app.put(str_app, cur_app);
                    permission_system.put(str_systemid, cur_system);

                    // 构造树节点名称集合
                    if (!appKeyMap.containsKey(str_systemid)) {// 系统
                        appKeyMap.put(str_systemid, str_systemid);
                    }
                    if (!appKeyMap.containsKey(str_app)) {// 应用
                        appKeyMap.put(str_app, str_appName);
                    }
                    if (!appMenuKeyMap.containsKey(str_appMenu)) {// 应用菜单
                        appMenuKeyMap.put(str_appMenu, str_appMenuName);
                    }


                }

            }
        }
//        return permission_app;
        return permission_system;
    }

    /**
     * 将以分组的树节点转换成饿了么格式的树
     * 格式为：系统->应用->应用菜单->菜单项
     *
     * @param sysApps
     * @return
     */
    private JSONArray transferAppMenuToELTree(JSONObject sysApps, Map<String, String> appKeyMap, Map<String, String> appMenuKeyMap) {
        JSONArray appMenuArr = new JSONArray();
        Set<String> sysAppkeys = sysApps.keySet();
        for (String sysAppkey : sysAppkeys) {
            Object appMenu = sysApps.get(sysAppkey);
            if (appMenu instanceof JSONObject) {
                JSONArray appChildMenuItemArr = transferAppMenuToELTree((JSONObject) appMenu, appKeyMap, appMenuKeyMap); //递归遍历输出下级节点信息
                JSONObject appMenuItem = new JSONObject();
                appMenuItem.put("id", sysAppkey);
                sysAppkey = praseLabel(sysAppkey, appKeyMap, appMenuKeyMap);
                appMenuItem.put("label", sysAppkey);
                appMenuItem.put("children", appChildMenuItemArr);
                appMenuArr.add(appMenuItem);
            } else {
                if (appMenu instanceof JSONArray) {
                    JSONArray appMenuItemArr = sysApps.getJSONArray(sysAppkey);
                    JSONObject appMenuItem = new JSONObject();
                    appMenuItem.put("id", sysAppkey);
                    sysAppkey = praseLabel(sysAppkey, appKeyMap, appMenuKeyMap);
                    appMenuItem.put("label", sysAppkey);
                    appMenuItem.put("children", getTreesData(appMenuItemArr, ""));
                    appMenuArr.add(appMenuItem);
                }
            }
        }
        return appMenuArr;
    }

    /**
     * 递归遍历树节点
     *
     * @param PermissionNodes
     * @param parentId
     * @return
     */
    private JSONArray getTreesData(JSONArray PermissionNodes, Object parentId) {
        JSONArray treeDatas = new JSONArray();
        for (int a = 0; a < PermissionNodes.size(); a++) {
            JSONObject PermissionNode = PermissionNodes.getJSONObject(a);
            String p_permissionId = PermissionNode.getString("pid");
            if (StringUtils.isEmpty(p_permissionId)) {
                p_permissionId = "";
            }
            if (parentId.equals(p_permissionId)) {
                JSONArray childCodeItem = getTreesData(PermissionNodes, PermissionNode.getString("id"));
                if (childCodeItem.size() > 0) {
                    PermissionNode.put("children", childCodeItem);
                }
                treeDatas.add(PermissionNode);
            }
        }
        return treeDatas;
    }

    /**
     * 拿到带有IBIZAPP-或IBIZMENU-标识的key把标记移除
     */
    private String praseLabel(String key, Map<String, String> appKeyMap, Map<String, String> appMenuKeyMap) {
        if (key.startsWith("IBIZAPP-")) {
            if (appKeyMap.containsKey(key)) {
                key = appKeyMap.get(key);
            }
            key = key.replace("IBIZAPP-", "");
        }
        if (key.startsWith("IBIZMENU-")) {
            if (appMenuKeyMap.containsKey(key)) {
                key = appMenuKeyMap.get(key);
            }
            key = key.replace("IBIZMENU-", "");
        }
        return key;
    }


    /**
     * 获取数据能力
     *
     * @return
     */
    public JSONArray getDEOppriv() {
        JSONArray treeNode = new JSONArray();
        StringBuilder permissionsSql = new StringBuilder();
        permissionsSql.append("select ");
        permissionsSql.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        permissionsSql.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
        permissionsSql.append(" t1.PSSYSMODULEID as pssysmoduleid, ");
        permissionsSql.append(" t1.PSSYSMODULENAME as pssysmodulename, ");
        permissionsSql.append(" t1.PSDATAENTITYID as psdataentityid, ");
        permissionsSql.append(" t1.PSDATAENTITYNAME as psdataentityname, ");
        permissionsSql.append(" t1.Pssourceid as pssourceid, ");
        permissionsSql.append(" t1.Pssourcename as pssourcename,");
        permissionsSql.append(" t1.PSDEDATARANGEID as psdedatarangeid, ");
        permissionsSql.append(" t1.PSDEDATARANGENAME as psdedatarangename,");
        permissionsSql.append(" t1.PSSYSTEMID as systemid ");
        permissionsSql.append(" FROM IBZPERMISSION t INNER JOIN IBZPSDEOPPRIV t1 ON t.SYS_PERMISSIONID = t1.SYS_PSDEOPPRIVID and t.enable=1");
        List<JSONObject> permissions = isys_permissionService.select(permissionsSql.toString(), null);

        // 清空sql,获取数据能力所处系统
        permissionsSql.delete(0, permissionsSql.length());
        permissionsSql.append("select temp.systemid from ( ");
        permissionsSql.append(" select ");
        permissionsSql.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        permissionsSql.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
        permissionsSql.append(" t1.PSSYSMODULEID as pssysmoduleid, ");
        permissionsSql.append(" t1.PSSYSMODULENAME as pssysmodulename, ");
        permissionsSql.append(" t1.PSDATAENTITYID as psdataentityid, ");
        permissionsSql.append(" t1.PSDATAENTITYNAME as psdataentityname, ");
        permissionsSql.append(" t1.Pssourceid as pssourceid, ");
        permissionsSql.append(" t1.Pssourcename as pssourcename,");
        permissionsSql.append(" t1.PSDEDATARANGEID as psdedatarangeid, ");
        permissionsSql.append(" t1.PSDEDATARANGENAME as psdedatarangename,");
        permissionsSql.append(" t1.PSSYSTEMID as systemid ");
        permissionsSql.append(" FROM IBZPERMISSION t INNER JOIN IBZPSDEOPPRIV t1 ON t.SYS_PERMISSIONID = t1.SYS_PSDEOPPRIVID and t.enable=1");
        permissionsSql.append(" )temp group by temp.systemid");
        List<JSONObject> systems = isys_permissionService.select(permissionsSql.toString(), null);

        if (permissions.size() > 0 && systems.size() > 0) {
            treeNode = this.transferDataCapabilityToELTree(permissions, systems);
        }

        return treeNode;
    }


    /**
     * 用于将资源表中数据能力数据转换成饿了么树格式数据
     *
     * @param permissions
     * @param systems
     * @return
     */
    public JSONArray transferDataCapabilityToELTree(List<JSONObject> permissions, List<JSONObject> systems) {
        Map<String, String> opprivTreeNameMap = new HashMap<>();
        JSONObject groupByMenuObj = groupByDataCapability(permissions, systems, opprivTreeNameMap);//将数据库数据进行分组
        JSONArray elTreeObj = transferDataCapabilityToELTree(groupByMenuObj, opprivTreeNameMap);//将分组后的数据转换成饿了么树格式数据
        return elTreeObj;
    }

    /**
     * 将数据库中的数据能力数据进行分组
     * 格式为：系统->模块->实体->数据集/实体行为->数据能力
     *
     * @param permissions
     * @param systems
     * @return
     */
    private JSONObject groupByDataCapability(List<JSONObject> permissions, List<JSONObject> systems, Map<String, String> opprivTreeNameMap) {
        JSONObject permission_system = new JSONObject(); //顶级系统数据
        for (JSONObject system : systems) {
            String systemid = system.getString("systemid");
            JSONObject permission_moudle = new JSONObject(); //次级模块数据
            for (JSONObject obj : permissions) {
                JSONObject jobj = new JSONObject();
                jobj.putAll(obj);

                String str_systemid = jobj.getString("systemid");// 系统标识
                String str_moudle = jobj.getString("pssysmoduleid");// 系统模块标识
                String str_moudle_name = jobj.getString("pssysmodulename");// 系统模块名称
                String str_entity = jobj.getString("psdataentityid");// 实体标识
                String str_entity_name = jobj.getString("psdataentityname");// 实体名称
                String str_dataset = jobj.getString("pssourceid");// 数据集，实体行为标识
                String str_dataset_name = jobj.getString("pssourcename");// 数据集，实体行为名称
//                String str_datarange = jobj.getString("psdedatarangeid");// 实体数据范围标识
//                String str_datarange_name = jobj.getString("psdedatarangename");// 实体数据范围名称
                String str_permissionid = jobj.getString("sys_permissionid");// 实体数据操作名称
                String str_permissionname = jobj.getString("sys_permissionname");// 实体数据操作标识

                // 根据systemid进行操作
                if (systemid.equals(str_systemid)) {
                    JSONObject cur_system = new JSONObject();
                    JSONObject cur_moudle = new JSONObject();
                    JSONObject cur_entity = new JSONObject();
//                    JSONObject cur_dataset = new JSONObject();
                    JSONArray cur_dataset = new JSONArray();
//                    JSONArray cur_data_range = new JSONArray();

                    if (permission_system.containsKey(str_systemid))// 系统合并
                        cur_system = permission_system.getJSONObject(str_systemid);

                    if (permission_moudle.containsKey(str_moudle))//模块合并
                        cur_moudle = permission_moudle.getJSONObject(str_moudle);

                    if (cur_moudle.containsKey(str_entity))//实体合并
                        cur_entity = cur_moudle.getJSONObject(str_entity);

                    if (cur_entity.containsKey(str_dataset))//数据集,实体行为合并
                        cur_dataset = cur_entity.getJSONArray(str_dataset);

//                    if (cur_dataset.containsKey(str_datarange))//数据范围合并
//                        cur_data_range = cur_dataset.getJSONArray(str_datarange);

                    JSONObject permission = new JSONObject();
                    permission.put("id", str_permissionid);
                    permission.put("label", str_permissionname);
//                    cur_data_range.add(permission);
//
//                    cur_dataset.put(str_datarange, cur_data_range);
                    cur_dataset.add(permission);
                    cur_entity.put(str_dataset, cur_dataset);
                    cur_moudle.put(str_entity, cur_entity);
                    cur_system.put(str_moudle, cur_moudle);

                    permission_moudle.put(str_moudle, cur_moudle);
                    permission_system.put(str_systemid, cur_system);

                    //构造树节点名称集合
                    if (!opprivTreeNameMap.containsKey(str_systemid)) {// 系统
                        opprivTreeNameMap.put(str_systemid, str_systemid);
                    }
                    if (!opprivTreeNameMap.containsKey(str_moudle)) {//　模块
                        opprivTreeNameMap.put(str_moudle, str_moudle_name);
                    }
                    if (!opprivTreeNameMap.containsKey(str_entity)) {// 实体
                        opprivTreeNameMap.put(str_entity, str_entity_name);
                    }
                    if (!opprivTreeNameMap.containsKey(str_dataset)) {// 数据集,实体行为
                        opprivTreeNameMap.put(str_dataset, str_dataset_name);
                    }
//                    if (!opprivTreeNameMap.containsKey(str_datarange_name)) {// 数据范围
//                        opprivTreeNameMap.put(str_datarange, str_datarange_name);
//                    }


                }

            }
        }

//        return permission_moudle;
        return permission_system;
    }

    /**
     * 权限树递归
     *
     * @param childNode
     * @return
     */
    private JSONArray transferDataCapabilityToELTree(JSONObject childNode, Map<String, String> opprivTreeNameMap) {
        JSONArray array = new JSONArray();
        Set<String> keys = childNode.keySet();
        for (String key : keys) {
            Object obj = childNode.get(key);
            if (obj instanceof JSONObject) {
                JSONArray childArr = transferDataCapabilityToELTree(childNode.getJSONObject(key), opprivTreeNameMap); //递归遍历输出下级节点信息
                JSONObject childNodeObj = new JSONObject();
                childNodeObj.put("id", key);
                childNodeObj.put("label", opprivTreeNameMap.get(key));
                childNodeObj.put("children", childArr);
                array.add(childNodeObj);
            } else {
                if (obj instanceof JSONArray) {

                    JSONArray permissionArr = new JSONArray();
                    JSONArray jsonArray = childNode.getJSONArray(key);
                    for (int a = 0; a < jsonArray.size(); a++) {   //最后一层
                        JSONObject permissionObj = jsonArray.getJSONObject(a);
                        JSONObject transPermissionObj = new JSONObject();
                        transPermissionObj.put("id", permissionObj.getString("id"));
                        transPermissionObj.put("label", permissionObj.getString("label"));
                        permissionArr.add(transPermissionObj);
                    }

                    JSONObject childNodeObj = new JSONObject();
                    childNodeObj.put("id", key);
                    childNodeObj.put("label", opprivTreeNameMap.get(key));
                    childNodeObj.put("children", permissionArr);
                    array.add(childNodeObj);
                }
            }
        }
        return array;
    }


    /**
     * 获取统一资源
     *
     * @return
     */
    public JSONArray getUnires() {
        JSONArray treeNode = new JSONArray();
        StringBuilder permissionsSql = new StringBuilder();
        permissionsSql.append("select ");
        permissionsSql.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        permissionsSql.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
        permissionsSql.append(" t1.SYS_PSSYSUNIRESID as uniresid, ");
        permissionsSql.append(" t1.SYS_PSSYSUNIRESNAME as uniresname, ");
        permissionsSql.append(" t1.UNIRESCODE as unirescode,");
        permissionsSql.append(" t.SYSTEMID as systemid ");
        permissionsSql.append(" FROM ibzpermission t INNER JOIN IBZPSSYSUNIRES t1 ON t.SYS_PERMISSIONID = t1.SYS_PSSYSUNIRESID and t.enable=1");
        List<JSONObject> permissions = isys_permissionService.select(permissionsSql.toString(), null);

        // 清空sql,获取统一资源所处系统
        permissionsSql.delete(0, permissionsSql.length());
        permissionsSql.append("select temp.systemid from ( ");
        permissionsSql.append(" select ");
        permissionsSql.append(" t.SYS_PERMISSIONID as sys_permissionid, ");
        permissionsSql.append(" t.SYS_PERMISSIONNAME as sys_permissionname, ");
        permissionsSql.append(" t1.SYS_PSSYSUNIRESID as uniresid, ");
        permissionsSql.append(" t1.SYS_PSSYSUNIRESNAME as uniresname, ");
        permissionsSql.append(" t1.UNIRESCODE as unirescode, ");
        permissionsSql.append(" t.SYSTEMID as systemid ");
        permissionsSql.append(" FROM ibzpermission t INNER JOIN IBZPSSYSUNIRES t1 ON t.SYS_PERMISSIONID = t1.SYS_PSSYSUNIRESID and t.enable=1");
        permissionsSql.append(" )temp group by temp.systemid");
        List<JSONObject> systems = isys_permissionService.select(permissionsSql.toString(), null);

        if (permissions.size() > 0 && systems.size() > 0) {
            treeNode = this.transferDataUniresToELTree(permissions, systems);
        }


        return treeNode;
    }

    /**
     * 用于将资源表中统一资源数据转换成饿了么树格式数据
     *
     * @param permissions
     * @param systems
     * @return
     */
    private JSONArray transferDataUniresToELTree(List<JSONObject> permissions, List<JSONObject> systems) {
        Map<String, String> uniresTreeNameMap = new HashMap<>();
        JSONObject groupByUniresObj = groupByDataUnires(permissions, systems, uniresTreeNameMap);//将数据库数据进行分组
        JSONArray elTreeObj = transferDataUniresToELTree(groupByUniresObj, uniresTreeNameMap);//将分组后的数据转换成饿了么树格式数据
        return elTreeObj;
    }

    /**
     * 将数据库中的数据能力数据进行分组
     * 格式为：系统－>统一资源
     *
     * @param permissions
     * @param systems
     * @param uniresTreeNameMap
     * @return
     */
    private JSONObject groupByDataUnires(List<JSONObject> permissions, List<JSONObject> systems, Map<String, String> uniresTreeNameMap) {
        JSONObject permission_system = new JSONObject(); //顶级系统数据
        for (JSONObject system : systems) {
            String systemid = system.getString("systemid");
            for (JSONObject obj : permissions) {
                JSONObject jobj = new JSONObject();
                jobj.putAll(obj);

                String str_systemid = jobj.getString("systemid");// 系统标识
                String str_uniresid = jobj.getString("uniresid");// 统一资源标识
                String str_uniresname = jobj.getString("uniresname");// 统一资源名称
                String str_unirescode = jobj.getString("unirescode");// 资源代码
                String str_permissionid = jobj.getString("sys_permissionid");// 实体数据操作名称
                String str_permissionname = jobj.getString("sys_permissionname");// 实体数据操作标识

                // 根据systemid进行操作
                if (systemid.equals(str_systemid)) {
                    JSONArray cur_system = new JSONArray();

                    if (permission_system.containsKey(str_systemid))// 系统合并
                        cur_system = permission_system.getJSONArray(str_systemid);

                    JSONObject cur_unires = new JSONObject();
                    cur_unires.put("id", str_permissionid);
                    cur_unires.put("label", str_permissionname);
                    cur_system.add(cur_unires);

                    permission_system.put(str_systemid, cur_system);

                    //构造树节点名称集合
                    if (!uniresTreeNameMap.containsKey(str_systemid)) {// 系统
                        uniresTreeNameMap.put(str_systemid, str_systemid);
                    }
                    if (!uniresTreeNameMap.containsKey(str_uniresid)) {//　资源
                        uniresTreeNameMap.put(str_uniresid, str_uniresname);
                    }


                }

            }
        }

        return permission_system;
    }

    /**
     * 权限树递归
     *
     * @param childNode
     * @param uniresTreeNameMap
     * @return
     */
    private JSONArray transferDataUniresToELTree(JSONObject childNode, Map<String, String> uniresTreeNameMap) {
        JSONArray array = new JSONArray();
        Set<String> keys = childNode.keySet();
        for (String key : keys) {
            Object obj = childNode.get(key);
            if (obj instanceof JSONObject) {
                JSONArray childArr = transferDataCapabilityToELTree(childNode.getJSONObject(key), uniresTreeNameMap); //递归遍历输出下级节点信息
                JSONObject childNodeObj = new JSONObject();
                childNodeObj.put("id", key);
                childNodeObj.put("label", uniresTreeNameMap.get(key));
                childNodeObj.put("children", childArr);
                array.add(childNodeObj);
            } else {
                if (obj instanceof JSONArray) {

                    JSONArray permissionArr = new JSONArray();
                    JSONArray jsonArray = childNode.getJSONArray(key);
                    for (int a = 0; a < jsonArray.size(); a++) {   //最后一层
                        JSONObject permissionObj = jsonArray.getJSONObject(a);
                        JSONObject transPermissionObj = new JSONObject();
                        transPermissionObj.put("id", permissionObj.getString("id"));
                        transPermissionObj.put("label", permissionObj.getString("label"));
                        permissionArr.add(transPermissionObj);
                    }

                    JSONObject childNodeObj = new JSONObject();
                    childNodeObj.put("id", key);
                    childNodeObj.put("label", uniresTreeNameMap.get(key));
                    childNodeObj.put("children", permissionArr);
                    array.add(childNodeObj);
                }
            }
        }
        return array;
    }

    /**
     * 根据角色id查询所有权限
     * @return
     * @param roleid
     */
    public JSONArray getallPermissionByRoleid(@NotBlank(message = "roleid不允许为空") String roleid) {
        JSONArray rolepermission = new JSONArray();

        StringBuilder sql = new StringBuilder();
        sql.append("select t.SYS_PERMISSIONID as permissionid,t.SYS_PERMISSIONNAME as permissionname,t1.PERMISSIONTYPE as permissiontype  from  ibzrole_permission t inner join ibzpermission t1 on t.SYS_PERMISSIONID=t1.SYS_PERMISSIONID where t1.enable='1' and t.sys_roleid='"+ roleid +"'");
        List<JSONObject> select = isys_permissionService.select(sql.toString(),null);
        for (JSONObject obj : select) {
            String permissionid = obj.getString("permissionid");
            String permissionname = obj.getString("permissionname");
            String permissiontype = obj.getString("permissiontype");
            JSONObject childNodeObj = new JSONObject();
            // 应用菜单需要对权限id进行处理
            if ("APPMENU".equals(permissiontype)){
                String appmenu_permissionid = permissionid.substring(permissionid.lastIndexOf("-")+1, permissionid.length());
                childNodeObj.put("id", appmenu_permissionid);
            }else{
                childNodeObj.put("id", permissionid);
            }
            childNodeObj.put("label", permissionname);
            rolepermission.add(childNodeObj);
        }

        return rolepermission;
    }

    /**
     * 根据角色id删除角色权限关系
     * @param roleid
     */
    public void clearRolePermissionByRoleid(String roleid) {
        isys_role_permissionService.removeByRoleid(roleid);
    }

    /**
     * 根据角色id保存选中的权限信息
     * @param roleid
     * @param checkedNodes
     */
    public void saveRolePermissionByRoleid(String roleid, JSONArray checkedNodes) {
        for (int i = 0; i < checkedNodes.size(); i++) {
            JSONObject obj = checkedNodes.getJSONObject(i);
            SYS_ROLE_PERMISSION rolePermission = new SYS_ROLE_PERMISSION();
            rolePermission.setRoleid(roleid);
            rolePermission.setPermissionid(obj.getString("sys_permissionid"));
            isys_role_permissionService.save(rolePermission);
        }

    }



}
