package com.sagacloud.endpoints;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.endpoints.item.PhysicalObject;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.DpUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description (应设备设施要求开发)
 * @Date 2018/8/22 11:52
 * @Version 1.0
 */
@Path("facility")
public class EquipmentFacility {

    @Path("/querySpaceOrEquip")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String querySpaceOrEquip(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) {
        try {
            JSONObject queryJson = JSONObject.parseObject(jsonStr);
            String objType = (String) queryJson.get("obj_type");
            if (StringUtils.isBlank(objType)) {
                return DpUtils.errorJsonMsg("缺少必要字段obj_type");
            }
            JSONArray objIds = queryJson.getJSONArray("obj_ids");
            if (objIds == null || objIds.size() == 0) {
                return DpUtils.errorJsonMsg("缺少必要字段obj_ids");
            }
           /* JSONArray returnInfos = (JSONArray) queryJson.get("return_infos");
            if (returnInfos == null || returnInfos.size() == 0) {
                return DpUtils.errorJsonMsg("缺少必要字段return_infos");
            }*/
            if ("space".equals(objType)) {
                return initSpaceResult(projectId, objIds).toJSONString();
            } else if ("equip".equals(objType)) {
                return initEquipResult(projectId, objIds).toJSONString();
            } else {
                return DpUtils.errorJsonMsg("查询失败!objType只支持space,equip!");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(ex.getMessage() == null ? "查询失败!" : ex.getMessage());
        }
    }

    @Path("/querySpaceOrEquipNoHierarchy")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String querySpaceOrEquipNoHierarchy(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) {
        try {
            JSONObject queryJson = JSONObject.parseObject(jsonStr);
            String objType = (String) queryJson.get("obj_type");
            if (StringUtils.isBlank(objType)) {
                return DpUtils.errorJsonMsg("缺少必要字段obj_type");
            }
            JSONArray objIds = queryJson.getJSONArray("obj_ids");
            if (objIds == null || objIds.size() == 0) {
                return DpUtils.errorJsonMsg("缺少必要字段obj_ids");
            }
            JSONObject result = new JSONObject();
            result.put("Result", "success");
            if ("space".equals(objType)) {
                result.put("Content", initSpaceResultNoHierarchyNew(projectId, objIds));
                return result.toJSONString();
            } else if ("equip".equals(objType)) {
                result.put("Content", initEquipResultNoHierarchyNew(projectId, objIds));
                return result.toJSONString();
            } else {
                return DpUtils.errorJsonMsg("查询失败!objType只支持space,equip!");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(ex.getMessage() == null ? "查询失败!" : ex.getMessage());
        }
    }

    /**
     * description 构建设备列表
     * @param projectId 项目id
     * @param objIds
     * @return com.alibaba.fastjson.JSONObject
     * @author feng
     * @since 15:11 2018/8/24
     */
    private JSONObject initEquipResult(String projectId, List objIds) throws Exception {
        Map<String, Map<String, Map<String, Set<String>>>> buildingFloorSpaceEquipMap = new HashMap<>();
        Map<String, Map<String, Map<String, Set<String>>>> buildingShaftSpaceEquipMap = new HashMap<>();
        Set<String> buildAndFloorAndShaftAndSpaceIdSet = new HashSet<>();
        Map<String, JSONObject> equipObjectMap = new HashMap<>();
        initEquipmentMap(projectId, objIds, buildingFloorSpaceEquipMap, buildingShaftSpaceEquipMap, buildAndFloorAndShaftAndSpaceIdSet, equipObjectMap);

        Map<String, JSONObject> buildFloorOrShaftOrSpaceMap = getIdObjectMap(projectId, buildAndFloorAndShaftAndSpaceIdSet);
        Set<String> buildSet = new HashSet<>();
        buildSet.addAll(buildingFloorSpaceEquipMap.keySet());
        buildSet.addAll(buildingShaftSpaceEquipMap.keySet());
        JSONArray buildArray = new JSONArray();
        for (String buildId : buildSet) {
            JSONObject buildObject = new JSONObject();
            buildObject.put("build_id", buildId);
            buildObject.put("build_name", buildFloorOrShaftOrSpaceMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
            Map<String, Map<String, Set<String>>> floorSpaceEquipMap = buildingFloorSpaceEquipMap.get(buildId);
            JSONArray floorArray = new JSONArray();
            if (floorSpaceEquipMap != null) {
                for (String floorId : floorSpaceEquipMap.keySet()) {
                    JSONObject floorInDatabase = buildFloorOrShaftOrSpaceMap.get(floorId);
                    JSONObject floorObject = new JSONObject();
                    floorObject.put("floor_id", floorId);
                    floorObject.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                    floorObject.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                    floorObject.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));
                    Map<String, Set<String>> spaceEquipMap = floorSpaceEquipMap.get(floorId);
                    floorObject.put("spaces", initSpaces(spaceEquipMap, buildFloorOrShaftOrSpaceMap));
                    floorArray.add(floorObject);
                }
            }
            buildObject.put("floors", floorArray);

            Map<String, Map<String, Set<String>>> shaftSpaceMap = buildingShaftSpaceEquipMap.get(buildId);
            JSONArray shaftArray = new JSONArray();
            if (shaftSpaceMap != null) {
                for (String shaftId : shaftSpaceMap.keySet()) {
                    JSONObject shaftInDatabase = buildFloorOrShaftOrSpaceMap.get(shaftId);
                    JSONObject shaftObject = new JSONObject();
                    shaftObject.put("shaft_id", shaftId);
                    shaftObject.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                    shaftObject.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                    Map<String, Set<String>> spaceEquipMap = shaftSpaceMap.get(shaftId);
                    shaftObject.put("spaces", initSpaces(spaceEquipMap, buildFloorOrShaftOrSpaceMap));
                    shaftArray.add(shaftObject);
                }
            }
            buildObject.put("shafts", shaftArray);
            buildArray.add(buildObject);
        }

        JSONObject result = new JSONObject();
        result.put("Result", "success");
        result.put("Content", buildArray);
        return result;
    }


    private JSONArray initEquipResultNoHierarchyNew(String projectId, List equipIds) throws Exception {
        Map<String, JSONObject> equipObjectMap = getIdObjectMap(projectId, new HashSet<>(equipIds));
        if (equipObjectMap == null) {
            return new JSONArray();
        }

        Map<String, String> equipSpaceMap = getEquipSpaceRelation(projectId, equipIds);
        Map<String, JSONObject> spaceMap = getIdObjectMap(projectId, new HashSet<>(equipSpaceMap.values()));
        Map<String,String> spaceShaftMap = getSpaceShaftMap(projectId,new ArrayList<>(equipSpaceMap.values()));

        Set<String> buildingFloorShaftSet = new HashSet<>();
        for (Map.Entry<String, JSONObject> entry : equipObjectMap.entrySet()) {
            JSONObject location = entry.getValue().getJSONObject("location");

            if (location != null) {
                String building = location.getString("building");
                if(StringUtils.isNotBlank(building)){
                    buildingFloorShaftSet.add(building);
                }
            }

            String equipId = entry.getKey();
            String spaceId = equipSpaceMap.get(equipId);
            if (StringUtils.isNotBlank(spaceId) && spaceMap.get(spaceId) != null && spaceMap.get(spaceId).getJSONObject("location") != null) {
                String floorId = spaceMap.get(spaceId).getJSONObject("location").getString("floor");
                if(StringUtils.isNotBlank(floorId)){
                    buildingFloorShaftSet.add(floorId);
                }
            }

            String shaftId = spaceShaftMap.get(spaceId);
            if (StringUtils.isNotBlank(shaftId)) {
                buildingFloorShaftSet.add(shaftId);
            }
        }
        Map<String, JSONObject> buildingFloorShaftMap = getIdObjectMap(projectId, buildingFloorShaftSet);

        JSONArray resultArray = new JSONArray();
        for (Map.Entry<String, JSONObject> equipEntry : equipObjectMap.entrySet()) {
            JSONObject equipResult = new JSONObject();
            JSONObject equipObject = equipEntry.getValue();
            equipResult.put("equip_id", equipEntry.getKey());
            equipResult.put("equip_name", equipObject.getJSONObject("infos").getString("EquipLocalName"));
            equipResult.put("equip_sequence_id", equipObject.getJSONObject("infos").getString("EquipSerial"));
            equipResult.put("obj_code", equipObject.getJSONObject("infos").getString("EquipLocalID"));

            String spaceId = equipSpaceMap.get(equipEntry.getKey());
            if(StringUtils.isNotBlank(spaceId)){
                JSONObject spaceObject = spaceMap.get(spaceId);
                equipResult.put("space_id", spaceId);
                equipResult.put("space_name", spaceObject.getJSONObject("infos").getString("RoomLocalName"));
                equipResult.put("space_sequence_id", spaceObject.getJSONObject("infos").getString("RoomSerial"));
                equipResult.put("room_func_type", spaceObject.getJSONObject("infos").getString("ProjRoomFuncType"));
            }


            JSONObject location = equipEntry.getValue().getJSONObject("location");
            if (location != null) {
                String building = location.getString("building");
                if(StringUtils.isNotBlank(building)){
                    equipResult.put("build_id", building);
                    equipResult.put("build_name", buildingFloorShaftMap.get(building).getJSONObject("infos").getString("BuildLocalName"));
                }
            }

            if (spaceMap.get(spaceId) != null && spaceMap.get(spaceId).getJSONObject("location") != null) {
                String floorId = spaceMap.get(spaceId).getJSONObject("location").getString("floor");
                if(StringUtils.isNotBlank(floorId)){
                    JSONObject floorInDatabase = buildingFloorShaftMap.get(floorId);
                    equipResult.put("floor_id", floorId);
                    equipResult.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                    equipResult.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                    equipResult.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));
                }
            }

            if (spaceMap.get(spaceId) != null && spaceMap.get(spaceId).getJSONObject("location") != null) {
                String shaftId = spaceShaftMap.get(spaceId);
                if(StringUtils.isNotBlank(shaftId)){
                    JSONObject shaftInDatabase = buildingFloorShaftMap.get(shaftId);
                    equipResult.put("shaft_id", shaftId);
                    equipResult.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                    equipResult.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                    equipResult.put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));
                }
            }
            resultArray.add(equipResult);
        }

        return resultArray;
    }
/*    private JSONObject initEquipResultNoHierarchy(String projectId, List equipIds) throws Exception {
        Map<String, Map<String, Map<String, Set<String>>>> buildingFloorSpaceEquipMap = new HashMap<>();
        Map<String, Map<String, Map<String, Set<String>>>> buildingShaftSpaceEquipMap = new HashMap<>();
        Set<String> buildAndFloorAndShaftAndSpaceIdSet = new HashSet<>();
        Map<String, JSONObject> equipObjectMap = new HashMap<>();
        initEquipmentMap(projectId, equipIds, buildingFloorSpaceEquipMap, buildingShaftSpaceEquipMap, buildAndFloorAndShaftAndSpaceIdSet, equipObjectMap);

        Map<String, JSONObject> buildFloorOrShaftOrSpaceMap = getIdObjectMap(projectId, buildAndFloorAndShaftAndSpaceIdSet);
        Set<String> buildSet = new HashSet<>();
        buildSet.addAll(buildingFloorSpaceEquipMap.keySet());
        buildSet.addAll(buildingShaftSpaceEquipMap.keySet());
        Map<String,JSONObject> equipResultMap  = new HashMap<>();
        for (String buildId : buildSet) {
       *//*     JSONObject buildObject = new JSONObject();
            buildObject.put("build_id", buildId);
            buildObject.put("build_name", buildFloorOrShaftOrSpaceMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));*//*
            Map<String, Map<String, Set<String>>> floorSpaceEquipMap = buildingFloorSpaceEquipMap.get(buildId);
            if (floorSpaceEquipMap != null) {
                for (String floorId : floorSpaceEquipMap.keySet()) {
                    Map<String, Set<String>> spaceEquipMap = floorSpaceEquipMap.get(floorId);
                    for (String spaceId : spaceEquipMap.keySet()) {
                        Set<String> equipIdSet = spaceEquipMap.get(spaceId);
                        for(String equipId:equipIdSet){
                            JSONObject equipResult = new JSONObject();
                            JSONObject equipObject = equipObjectMap.get(equipId);
                            equipResult.put("equip_id", equipId);
                            equipResult.put("equip_name", equipObject.getJSONObject("infos").getString("RoomLocalName"));
                            equipResult.put("equip_sequence_id", equipObject.getJSONObject("infos").getString("EquipSerial"));

                            JSONObject spaceInDatabase = buildFloorOrShaftOrSpaceMap.get(spaceId);
                            equipResult.put("space_id", spaceId);
                            equipResult.put("space_name", spaceInDatabase.getJSONObject("infos").getString("RoomLocalName"));
                            equipResult.put("space_sequence_id", spaceInDatabase.getJSONObject("infos").getString("RoomSerial"));
                            equipResult.put("room_func_type", spaceInDatabase.getJSONObject("infos").getString("RoomFuncType"));

                            JSONObject floorInDatabase = buildFloorOrShaftOrSpaceMap.get(floorId);
                            equipResult.put("floor_id", floorId);
                            equipResult.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                            equipResult.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                            equipResult.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));

                            equipResult.put("build_id", buildId);
                            equipResult.put("build_name", buildFloorOrShaftOrSpaceMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
                            equipResultMap.put(equipId, equipResult);
                        }
                    }
                }
            }

            Map<String, Map<String, Set<String>>> shaftSpaceMap = buildingShaftSpaceEquipMap.get(buildId);
            if (shaftSpaceMap != null) {
                for (String shaftId : shaftSpaceMap.keySet()) {

                    Map<String, Set<String>> spaceEquipMap = shaftSpaceMap.get(shaftId);
                    for (String spaceId : spaceEquipMap.keySet()) {
                        Set<String> equipIdSet = spaceEquipMap.get(spaceId);
                        for(String equipId:equipIdSet){
                            if(equipResultMap.containsKey(equipId)){
                                JSONObject shaftInDatabase = buildFloorOrShaftOrSpaceMap.get(shaftId);
                                equipResultMap.get(equipId).put("shaft_id", shaftId);
                                equipResultMap.get(equipId).put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                                equipResultMap.get(equipId).put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                                equipResultMap.get(equipId).put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));
                            } else {
                                JSONObject equipResult = new JSONObject();
                                JSONObject equipObject = equipObjectMap.get(equipId);
                                equipResult.put("equip_id", equipId);
                                equipResult.put("equip_name", equipObject.getJSONObject("infos").getString("EquipLocalName"));
                                equipResult.put("equip_sequence_id", equipObject.getJSONObject("infos").getString("EquipSerial"));

                                JSONObject spaceInDatabase = buildFloorOrShaftOrSpaceMap.get(spaceId);
                                equipResult.put("space_id", spaceId);
                                equipResult.put("space_name", spaceInDatabase.getJSONObject("infos").getString("RoomLocalName"));
                                equipResult.put("space_sequence_id", spaceInDatabase.getJSONObject("infos").getString("RoomSerial"));
                                equipResult.put("room_func_type", spaceInDatabase.getJSONObject("infos").getString("RoomFuncType"));

                                JSONObject shaftInDatabase = buildFloorOrShaftOrSpaceMap.get(shaftId);
                                equipResult.put("shaft_id", shaftId);
                                equipResult.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                                equipResult.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                                equipResult.put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));

                                equipResult.put("build_id", buildId);
                                equipResult.put("build_name", buildFloorOrShaftOrSpaceMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
                                equipResultMap.put(equipId, equipResult);
                            }
                        }
                    }
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("Result", "success");
        result.put("Content", equipResultMap.values());
        return result;
    }*/

    /**
     * description 构建返回的空间数组
     * @param spaceEquipMap
     * @param buildFloorOrShaftOrSpaceMap
     * @return com.alibaba.fastjson.JSONArray
     * @author feng
     * @since 15:13 2018/8/24
     */
    private JSONArray initSpaces(Map<String, Set<String>> spaceEquipMap, Map<String, JSONObject> buildFloorOrShaftOrSpaceMap) {
        JSONArray spaceArray = new JSONArray();
        for (String spaceId : spaceEquipMap.keySet()) {
            JSONObject spaceInDatabase = buildFloorOrShaftOrSpaceMap.get(spaceId);
            JSONObject spaceObject = new JSONObject();
            spaceObject.put("space_id", spaceId);
            spaceObject.put("space_name", spaceInDatabase.getJSONObject("infos").getString("RoomLocalName"));
            spaceObject.put("room_func_type", spaceInDatabase.getJSONObject("infos").getString("ProjRoomFuncType"));
            spaceObject.put("room_sequence_id", spaceInDatabase.getJSONObject("infos").getString("RoomSerial"));
            spaceObject.put("equips", spaceEquipMap.get(spaceId));
            spaceArray.add(spaceObject);
        }
        return spaceArray;
    }

    /**
     * description  构建空间列表
     * @param projectId
     * @param objIds
     * @return com.alibaba.fastjson.JSONObject
     * @author feng
     * @since 15:15 2018/8/24
     */
    private JSONObject initSpaceResult(String projectId, List objIds) throws Exception {
        Map<String, Map<String, Set<String>>> buildingFloorSpaceMap = new HashMap<>();
        Map<String, Map<String, Set<String>>> buildingShaftSpaceMap = new HashMap<>();
        Set<String> buildAndFloorAndShaftIdSet = new HashSet<>();
        Map<String, JSONObject> spaceObjectMap = new HashMap<>();
        initSpaceMap(projectId, objIds, buildingFloorSpaceMap, buildingShaftSpaceMap, buildAndFloorAndShaftIdSet, spaceObjectMap);

        Map<String, JSONObject> buildFloorOrShaftMap = getIdObjectMap(projectId, buildAndFloorAndShaftIdSet);
        Set<String> buildSet = new HashSet<>();
        buildSet.addAll(buildingFloorSpaceMap.keySet());
        buildSet.addAll(buildingShaftSpaceMap.keySet());
        JSONArray buildArray = new JSONArray();
        for (String buildId : buildSet) {
            JSONObject buildObject = new JSONObject();
            buildObject.put("build_id", buildId);
            buildObject.put("build_name", buildFloorOrShaftMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
            Map<String, Set<String>> floorSpaceMap = buildingFloorSpaceMap.get(buildId);
            JSONArray floorArray = new JSONArray();
            if (floorSpaceMap != null) {
                for (String floorId : floorSpaceMap.keySet()) {
                    JSONObject floorInDatabase = buildFloorOrShaftMap.get(floorId);
                    JSONObject floorObject = new JSONObject();
                    floorObject.put("floor_id", floorId);
                    floorObject.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                    floorObject.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                    floorObject.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));
                    floorObject.put("spaces", floorSpaceMap.get(floorId));
                    floorArray.add(floorObject);
                }
            }

            buildObject.put("floors", floorArray);

            Map<String, Set<String>> shaftSpaceMap = buildingShaftSpaceMap.get(buildId);
            JSONArray shaftArray = new JSONArray();
            if (shaftSpaceMap != null) {
                for (String shaftId : shaftSpaceMap.keySet()) {
                    JSONObject shaftInDatabase = buildFloorOrShaftMap.get(shaftId);
                    JSONObject shaftObject = new JSONObject();
                    shaftObject.put("shaft_id", shaftId);
                    shaftObject.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                    shaftObject.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                    shaftObject.put("spaces", shaftSpaceMap.get(shaftId));
                    shaftArray.add(shaftObject);
                }
            }

            buildObject.put("shafts", shaftArray);
            buildArray.add(buildObject);
        }

        JSONObject result = new JSONObject();
        result.put("Result", "success");
        result.put("Content", buildArray);
        return result;
    }

    private JSONArray initSpaceResultNoHierarchyNew (String projectId, List spaceIds) throws Exception {
        Map<String, JSONObject> spaceObjectMap = getIdObjectMap(projectId, new HashSet<>(spaceIds));
        if (spaceObjectMap == null) {
            return new JSONArray();
        }


        Set<String> buildingFloorShaftSet = new HashSet<>();

        Map<String, String> spaceShaftMap = getSpaceShaftMap(projectId, spaceIds);

        for (Map.Entry<String, JSONObject> spaceEntry : spaceObjectMap.entrySet()) {
            JSONObject location = spaceEntry.getValue().getJSONObject("location");
            if (location == null) {
                continue;
            }
            String building = location.getString("building");
            String floorId = location.getString("floor");
         //   String shaftId = location.getString("shaft");
            String shaftId = spaceShaftMap.get(spaceEntry.getKey());

            if (StringUtils.isNotBlank(building)) {
                buildingFloorShaftSet.add(building);
            }

            if (StringUtils.isNotBlank(floorId)) {
                buildingFloorShaftSet.add(floorId);
            }

            if (StringUtils.isNotBlank(shaftId)) {
                buildingFloorShaftSet.add(shaftId);
            }
        }
        Map<String, JSONObject> buildingFloorShaftMap = getIdObjectMap(projectId, buildingFloorShaftSet);

        JSONArray resultArray = new JSONArray();

        for (Map.Entry<String, JSONObject> spaceEntry : spaceObjectMap.entrySet()) {
            JSONObject spaceResult = new JSONObject();
            JSONObject spaceObject = spaceObjectMap.get(spaceEntry.getKey());
            spaceResult.put("space_id", spaceEntry.getKey());
            spaceResult.put("space_name", spaceObject.getJSONObject("infos").getString("RoomLocalName"));
            spaceResult.put("space_sequence_id", spaceObject.getJSONObject("infos").getString("RoomSerial"));
            spaceResult.put("room_func_type", spaceObject.getJSONObject("infos").getString("ProjRoomFuncType"));
            spaceResult.put("obj_code", spaceObject.getJSONObject("infos").getString("RoomLocalID"));

            JSONObject location = spaceEntry.getValue().getJSONObject("location");
            if(location == null){
                continue;
            }
            String building = location.getString("building");
            String floorId = location.getString("floor");
        //    String shaftId = location.getString("shaft");
            String shaftId = spaceShaftMap.get(spaceEntry.getKey());

            if (StringUtils.isNotBlank(building)) {
                spaceResult.put("build_id", building);
                spaceResult.put("build_name", buildingFloorShaftMap.get(building).getJSONObject("infos").getString("BuildLocalName"));
            }

            if (StringUtils.isNotBlank(floorId)) {
                JSONObject floorInDatabase = buildingFloorShaftMap.get(floorId);
                spaceResult.put("floor_id", floorId);
                spaceResult.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                spaceResult.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                spaceResult.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));
            }

            if (StringUtils.isNotBlank(shaftId)) {
                JSONObject shaftInDatabase = buildingFloorShaftMap.get(shaftId);
                spaceResult.put("shaft_id", shaftId);
                spaceResult.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                spaceResult.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                spaceResult.put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));
            }
            resultArray.add(spaceResult);
        }

        return resultArray;
    }


  /*  private JSONObject initSpaceResultNoHierarchy (String projectId, List spaceIds) throws Exception {
        Map<String, Map<String, Set<String>>> buildingFloorSpaceMap = new HashMap<>();
        Map<String, Map<String, Set<String>>> buildingShaftSpaceMap = new HashMap<>();
        Set<String> buildAndFloorAndShaftIdSet = new HashSet<>();
        Map<String, JSONObject> spaceObjectMap = new HashMap<>();
        initSpaceMap(projectId, spaceIds, buildingFloorSpaceMap, buildingShaftSpaceMap, buildAndFloorAndShaftIdSet, spaceObjectMap);

        Map<String, JSONObject> buildFloorOrShaftMap = getIdObjectMap(projectId, buildAndFloorAndShaftIdSet);
        Set<String> buildSet = new HashSet<>();
        buildSet.addAll(buildingFloorSpaceMap.keySet());
        buildSet.addAll(buildingShaftSpaceMap.keySet());
        Map<String,JSONObject> spaceResultMap  = new HashMap<>();
        for (String buildId : buildSet) {
            Map<String, Set<String>> floorSpaceMap = buildingFloorSpaceMap.get(buildId);
            if (floorSpaceMap != null) {
                for (String floorId : floorSpaceMap.keySet()) {
                    Set<String> spaceIdSet = floorSpaceMap.get(floorId);
                    for(String spaceId:spaceIdSet){
                        JSONObject spaceResult = new JSONObject();
                        JSONObject spaceObject = spaceObjectMap.get(spaceId);
                        spaceResult.put("space_id", spaceId);
                        spaceResult.put("space_name", spaceObject.getJSONObject("infos").getString("RoomLocalName"));
                        spaceResult.put("space_sequence_id", spaceObject.getJSONObject("infos").getString("RoomSerial"));
                        spaceResult.put("room_func_type", spaceObject.getJSONObject("infos").getString("RoomFuncType"));

                        JSONObject floorInDatabase = buildFloorOrShaftMap.get(floorId);
                        spaceResult.put("floor_id", floorId);
                        spaceResult.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                        spaceResult.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                        spaceResult.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));

                        spaceResult.put("build_id", buildId);
                        spaceResult.put("build_name", buildFloorOrShaftMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
                        spaceResultMap.put(spaceId, spaceResult);
                    }
                   *//* J
                    JSONObject floorObject = new JSONObject();
                    floorObject.put("floor_id", floorId);
                    floorObject.put("floor_name", floorInDatabase.getJSONObject("infos").getString("FloorLocalName"));
                    floorObject.put("floor_sequence_id", floorInDatabase.getJSONObject("infos").getString("FloorSequenceID"));
                    floorObject.put("floor_identity", floorInDatabase.getJSONObject("infos").getString("FloorIdentity"));
                    floorObject.put("spaces", );
                    floorArray.add(floorObject);*//*
                }
            }

            Map<String, Set<String>> shaftSpaceMap = buildingShaftSpaceMap.get(buildId);
            if (shaftSpaceMap != null) {
                for (String shaftId : shaftSpaceMap.keySet()) {
                    Set<String> spaceIdSet = shaftSpaceMap.get(shaftId);
                    for(String spaceId:spaceIdSet){
                        if(spaceResultMap.containsKey(spaceId)){
                            JSONObject shaftInDatabase = buildFloorOrShaftMap.get(shaftId);
                            spaceResultMap.get(spaceId).put("shaft_id", shaftId);
                            spaceResultMap.get(spaceId).put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                            spaceResultMap.get(spaceId).put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                            spaceResultMap.get(spaceId).put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));
                        } else {
                            JSONObject spaceResult = new JSONObject();
                            JSONObject spaceObject = spaceObjectMap.get(spaceId);
                            spaceResult.put("space_id", spaceId);
                            spaceResult.put("space_name", spaceObject.getJSONObject("infos").getString("RoomLocalName"));
                            spaceResult.put("space_sequence_id", spaceObject.getJSONObject("infos").getString("RoomSerial"));
                            spaceResult.put("room_func_type", spaceObject.getJSONObject("infos").getString("RoomFuncType"));

                            JSONObject shaftInDatabase = buildFloorOrShaftMap.get(shaftId);
                            spaceResult.put("shaft_id", shaftId);
                            spaceResult.put("shaft_name", shaftInDatabase.getJSONObject("infos").getString("ShaftLocalName"));
                            spaceResult.put("shaft_sequence_id", shaftInDatabase.getJSONObject("infos").getString("ShaftSequenceID"));
                            spaceResult.put("shaft_func_type", shaftInDatabase.getJSONObject("infos").getString("ShaftFuncType"));

                            spaceResult.put("build_id", buildId);
                            spaceResult.put("build_name", buildFloorOrShaftMap.get(buildId).getJSONObject("infos").getString("BuildLocalName"));
                            spaceResultMap.put(spaceId, spaceResult);
                        }
                    }
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("Result", "success");
        result.put("Content", spaceResultMap.values());
        return result;
    }*/

    /**
     * description 构建设备对象map
     * @param projectId
     * @param equipmentList
     * @param buildingFloorSpaceEquipMap
     * @param buildingShaftSpaceEquipMap
     * @param buildAndFloorAndShaftAndEquipIdSet
     * @return void
     * @author feng
     * @since 15:16 2018/8/24
     */
    private void initEquipmentMap(String projectId, List<String> equipmentList, Map<String, Map<String, Map<String, Set<String>>>> buildingFloorSpaceEquipMap,
                                  Map<String, Map<String, Map<String, Set<String>>>> buildingShaftSpaceEquipMap, Set<String> buildAndFloorAndShaftAndEquipIdSet,
                                  Map<String, JSONObject> equipObjectMap) throws Exception {
        equipObjectMap.putAll(getIdObjectMap(projectId, new HashSet<>(equipmentList)));
        Map<String, String> equipSpaceMap = getEquipSpaceRelation(projectId, equipmentList);
        Map<String, JSONObject> spaceMap = getIdObjectMap(projectId, new HashSet<>(equipSpaceMap.values()));
        Map<String, String> spaceShaftMap = getSpaceShaftMap(projectId, new ArrayList<>(equipSpaceMap.values()));

        for (Map.Entry<String, JSONObject> entry : equipObjectMap.entrySet()) {
            JSONObject location = entry.getValue().getJSONObject("location");
            String building = null;
            if (location != null) {
                building = location.getString("building");
            }

            String equipId = entry.getValue().getString("id");

            String spaceId = equipSpaceMap.get(equipId);
            String floorId = null;
            if (spaceMap.get(spaceId) != null && spaceMap.get(spaceId).getJSONObject("location") != null) {
                floorId = spaceMap.get(spaceId).getJSONObject("location").getString("floor");
            }

            String shaftId = spaceShaftMap.get(spaceId);

            if (StringUtils.isBlank(building) || (StringUtils.isBlank(floorId) && StringUtils.isBlank(shaftId))
                    || StringUtils.isBlank(spaceId) || StringUtils.isBlank(equipId)) {
                continue;
            }
            buildAndFloorAndShaftAndEquipIdSet.add(building);
            if (StringUtils.isNotBlank(floorId)) {
                initBuildingObjectSpaceEquipMap(buildingFloorSpaceEquipMap, building, floorId, spaceId, equipId);
                buildAndFloorAndShaftAndEquipIdSet.add(floorId);
            }
            if (StringUtils.isNotBlank(shaftId)) {
                initBuildingObjectSpaceEquipMap(buildingShaftSpaceEquipMap, building, shaftId, spaceId, equipId);
                buildAndFloorAndShaftAndEquipIdSet.add(shaftId);
            }
            buildAndFloorAndShaftAndEquipIdSet.add(spaceId);
            buildAndFloorAndShaftAndEquipIdSet.add(equipId);
        }
    }

    /**
     * description 构建空间对象Map
     * @param projectId
     * @param spaceOrEquipmentList
     * @param buildingFloorSpaceMap
     * @param buildingShaftSpaceMap
     * @param buildAndFloorAndShaftIdSet
     * @return void
     * @author feng
     * @since 15:16 2018/8/24
     */
    private void initSpaceMap(String projectId, List<String> spaceList, Map<String, Map<String, Set<String>>> buildingFloorSpaceMap,
                              Map<String, Map<String, Set<String>>> buildingShaftSpaceMap, Set<String> buildAndFloorAndShaftIdSet,
                              Map<String, JSONObject> spaceObjectMap) throws Exception {
        spaceObjectMap.putAll(getIdObjectMap(projectId, new HashSet<>(spaceList)));

        Map<String, String> spaceShaftMap = getSpaceShaftMap(projectId, new ArrayList<>(spaceObjectMap.keySet()));
        for (Map.Entry<String, JSONObject> entry: spaceObjectMap.entrySet()) {
            JSONObject location = entry.getValue().getJSONObject("location");
            if (location == null) {
                continue;
            }
            String building = location.getString("building");

            buildAndFloorAndShaftIdSet.add(building);
            String spaceId = entry.getValue().getString("id");
            String floorId = location.getString("floor");
         //   String shaftId = location.getString("shaft");
            String shaftId = spaceShaftMap.get(entry.getKey());
            if (StringUtils.isBlank(building) || (StringUtils.isBlank(floorId) && StringUtils.isBlank(shaftId)) || StringUtils.isBlank(spaceId)) {
                continue;
            }
            if (StringUtils.isNotBlank(floorId)) {
                initBuildingObjectSpaceMap(buildingFloorSpaceMap, building, floorId, spaceId);
                buildAndFloorAndShaftIdSet.add(floorId);
            }
            if (StringUtils.isNotBlank(shaftId)) {
                initBuildingObjectSpaceMap(buildingShaftSpaceMap, building, shaftId, spaceId);
                buildAndFloorAndShaftIdSet.add(shaftId);
            }
        }
    }

    private void initBuildingObjectSpaceMap(Map<String, Map<String, Set<String>>> buildingObjectSpaceMap, String building, String floorOrShaft, String spaceId) {
        Map<String, Set<String>> shaftSpaceMap = buildingObjectSpaceMap.get(building);
        if(shaftSpaceMap == null){
            shaftSpaceMap = new HashMap<>();
            buildingObjectSpaceMap.put(building, shaftSpaceMap);
            Set<String> shaftSpaceList = shaftSpaceMap.get(floorOrShaft);
            if (shaftSpaceList == null) {
                shaftSpaceList = new HashSet<>();
                shaftSpaceList.add(spaceId);
                shaftSpaceMap.put(floorOrShaft, shaftSpaceList);
            } else {
                shaftSpaceList.add(spaceId);
            }
        }

        Set<String> shaftSpaceList = shaftSpaceMap.get(floorOrShaft);
        if (shaftSpaceList == null) {
            shaftSpaceList = new HashSet<>();
            shaftSpaceList.add(spaceId);
            shaftSpaceMap.put(floorOrShaft, shaftSpaceList);
        } else {
            shaftSpaceList.add(spaceId);
        }
    }

    private void initBuildingObjectSpaceEquipMap(Map<String, Map<String, Map<String, Set<String>>>> buildingObjectSpaceEquipMap, String building, String floorOrShaft, String spaceId, String equipId) {
        Map<String, Map<String, Set<String>>> objectSpaceEquipMap = buildingObjectSpaceEquipMap.computeIfAbsent(building, k -> new HashMap<>());

        Map<String, Set<String>> spaceEquipMap = objectSpaceEquipMap.computeIfAbsent(floorOrShaft, k -> new HashMap<>());

        Set<String> equipSet = spaceEquipMap.get(spaceId);
        if (equipSet == null) {
            equipSet = new HashSet<>();
            equipSet.add(equipId);
            spaceEquipMap.put(spaceId, equipSet);
        } else {
            equipSet.add(equipId);
        }
    }

    private JSONArray batchQuery(String projectId, List<String> idList) throws Exception {
        if (CollectionUtils.isEmpty(idList)) {
            return new JSONArray();
        }
        JSONObject queryObject = new JSONObject();
        queryObject.put("valid", null);
        JSONArray criteriaArray = new JSONArray();
        for (String id : idList) {
            JSONObject criteriaObject = new JSONObject();
            criteriaObject.put("id", id);
            criteriaArray.add(criteriaObject);
        }
        queryObject.put("criterias", criteriaArray);
        PhysicalObject physicalObject = new PhysicalObject();

        String queryResult = physicalObject.batchQueryById(projectId, queryObject.toJSONString());
        return JSONObject.parseObject(queryResult).getJSONArray("Content");
    }

    private Map<String, JSONObject> getIdObjectMap(String projectId, Set<String> idSet) throws Exception {
        JSONArray jsonArray = batchQuery(projectId, new ArrayList<>(idSet));
        if (jsonArray == null || jsonArray.size() == 0) {
            return new HashMap<>();
        }
        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String id = object.getString("id");
            jsonObjectMap.put(id, object);
        }
        return jsonObjectMap;
    }

    // 查询设备与指定空间的关系
    private Map<String, String> getEquipSpaceRelation(String projectId, List<String> equipList) throws Exception {
        JSONObject graphQuery = new JSONObject();
        JSONObject criteriaObject = new JSONObject();
        criteriaObject.put("graph_type", "EquipinSpace");
        graphQuery.put("criteria", criteriaObject);
        Relation relation = new Relation();
        String graphInstanceStr = relation.queryGraphInstance(projectId, graphQuery.toJSONString());
        JSONObject graphInstanceObject = JSONObject.parseObject(graphInstanceStr);
        // 1.图实例id
        String graphId = null;
        if ("success".equals(graphInstanceObject.getString("Result"))) {
            JSONArray contentArray = graphInstanceObject.getJSONArray("Content");
            if (contentArray == null || contentArray.size() == 0) {
                return new HashMap<>();
            }
            graphId = graphInstanceObject.getJSONArray("Content").getJSONObject(0).getString("graph_id");
        }

        // 2.请求参数
        JSONObject relationParam = new JSONObject();
        JSONArray criteriaArray = new JSONArray();
        for (String equipId : equipList) {
            JSONObject criteria = new JSONObject();
            criteria.put("from_id", equipId);
            criteria.put("graph_id", graphId);
            criteria.put("rel_type", "1");
            criteriaArray.add(criteria);
        }

        relationParam.put("criterias", criteriaArray);
        relationParam.put("merge", true);
        String queryResult = relation.query(projectId, relationParam.toJSONString());

        Map<String, String> resultMap = new HashMap<>();
        if (null != queryResult && queryResult.contains("success")) {
            JSONObject resultJsonObj = JSONObject.parseObject(queryResult);
            JSONArray contentData = resultJsonObj.getJSONArray("Content");
            if (null != contentData && !contentData.isEmpty()) {
                for (int i = 0; i < contentData.size(); i++) {
                    JSONObject item = contentData.getJSONObject(i);
                    resultMap.put(item.getString("from_id"), item.getString("to_id"));
                }
            }
        }
        return resultMap;
    }

    private Map<String,String> getSpaceShaftMap(String projectId,List<String> spaceList){
        //查询图实例ID
        String graphId = queryGraphInstance(projectId, "ShaftandSpace");
        if(StringUtils.isBlank(graphId)){
            return new HashMap<>();
        }
        Relation relation = new Relation();

        // 2.请求参数
        JSONObject relationParam = new JSONObject();
        JSONArray criteriaArray = new JSONArray();
        for (String spaceId : spaceList) {
            JSONObject criteria = new JSONObject();
            criteria.put("to_id", spaceId);
            criteria.put("graph_id", graphId);
            criteria.put("rel_type", "1");
            criteriaArray.add(criteria);
        }

        relationParam.put("criterias", criteriaArray);
        relationParam.put("merge", true);
        String queryResult = relation.query(projectId, relationParam.toJSONString());

        Map<String, String> resultMap = new HashMap<>();
        if (null != queryResult && queryResult.contains("success")) {
            JSONObject resultJsonObj = JSONObject.parseObject(queryResult);
            JSONArray contentData = resultJsonObj.getJSONArray("Content");
            if (null != contentData && !contentData.isEmpty()) {
                for (int i = 0; i < contentData.size(); i++) {
                    JSONObject item = contentData.getJSONObject(i);
                    resultMap.put( item.getString("to_id"),item.getString("from_id"));
                }
            }
        }
        return resultMap;
    }

    /**
     * 功能描述： 获取数据平台图实例
     * @param projectId
     * @param graphType
     * @return
     * @throws Exception
     */
    private String queryGraphInstance(String projectId, String graphType) {
        JSONObject graphInstance = null;
        JSONObject jsonObject = new JSONObject();
        JSONObject criteria = new JSONObject();
        criteria.put("graph_type", graphType);
        jsonObject.put("criteria", criteria);
        String graphInstanceResult = new Relation().queryGraphInstance(projectId, jsonObject.toJSONString());
        JSONObject graphInstanceJson = JSONObject.parseObject(graphInstanceResult);
        if (null != graphInstanceResult && graphInstanceResult.contains("success")) {
            JSONArray graphInstanceContents = graphInstanceJson.getJSONArray("Content");
            if (graphInstanceContents != null && graphInstanceContents.size() > 0) {
                graphInstance = graphInstanceContents.getJSONObject(0);
            }
        }
        if (graphInstance != null) {
            //图实例ID
            return graphInstance.getString("graph_id");
        }
        return null;
    }
}
